module.exports = /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 9548: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; const os = __importStar(__webpack_require__(2087)); const utils_1 = __webpack_require__(7472); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 7117: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = __webpack_require__(9548); const file_command_1 = __webpack_require__(2469); const utils_1 = __webpack_require__(7472); const os = __importStar(__webpack_require__(2087)); const path = __importStar(__webpack_require__(5622)); const oidc_utils_1 = __webpack_require__(5172); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = utils_1.toCommandValue(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { const delimiter = '_GitHubActionsFileCommandDelimeter_'; const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; file_command_1.issueCommand('ENV', commandValue); } else { command_1.issueCommand('set-env', { name }, convertedVal); } } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { file_command_1.issueCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } if (options && options.trimWhitespace === false) { return val; } return val.trim(); } exports.getInput = getInput; /** * Gets the values of an multiline input. Each value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string[] * */ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); return inputs; } exports.getMultilineInput = getMultilineInput; /** * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. * Support boolean input list: `true | True | TRUE | false | False | FALSE` . * The return value is also in boolean type. * ref: https://yaml.org/spec/1.2/spec.html#id2804923 * * @param name name of the input to get * @param options optional. See InputOptions. * @returns boolean */ function getBooleanInput(name, options) { const trueValue = ['true', 'True', 'TRUE']; const falseValue = ['false', 'False', 'FALSE']; const val = getInput(name, options); if (trueValue.includes(val)) return true; if (falseValue.includes(val)) return false; throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { process.stdout.write(os.EOL); command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { command_1.issue('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** * Adds a warning issue * @param message warning issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** * Adds a notice issue * @param message notice issue message. Errors will be converted to string via toString() * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { command_1.issueCommand('save-state', { name }, value); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; function getIDToken(aud) { return __awaiter(this, void 0, void 0, function* () { return yield oidc_utils_1.OidcClient.getIDToken(aud); }); } exports.getIDToken = getIDToken; //# sourceMappingURL=core.js.map /***/ }), /***/ 2469: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issueCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__webpack_require__(5747)); const os = __importStar(__webpack_require__(2087)); const utils_1 = __webpack_require__(7472); function issueCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { encoding: 'utf8' }); } exports.issueCommand = issueCommand; //# sourceMappingURL=file-command.js.map /***/ }), /***/ 5172: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; const http_client_1 = __webpack_require__(9926); const auth_1 = __webpack_require__(9206); const core_1 = __webpack_require__(7117); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { allowRetries: allowRetry, maxRetries: maxRetry }; return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } static getRequestToken() { const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; if (!token) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } return token; } static getIDTokenUrl() { const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; if (!runtimeUrl) { throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } return runtimeUrl; } static getCall(id_token_url) { var _a; return __awaiter(this, void 0, void 0, function* () { const httpclient = OidcClient.createHttpClient(); const res = yield httpclient .getJson(id_token_url) .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n Error Message: ${error.result.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { throw new Error('Response json body do not have ID Token field'); } return id_token; }); } static getIDToken(audience) { return __awaiter(this, void 0, void 0, function* () { try { // New ID Token is requested from action service let id_token_url = OidcClient.getIDTokenUrl(); if (audience) { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } core_1.debug(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); core_1.setSecret(id_token); return id_token; } catch (error) { throw new Error(`Error message: ${error.message}`); } }); } } exports.OidcClient = OidcClient; //# sourceMappingURL=oidc-utils.js.map /***/ }), /***/ 7472: /***/ ((__unused_webpack_module, exports) => { "use strict"; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toCommandProperties = exports.toCommandValue = void 0; /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } exports.toCommandValue = toCommandValue; /** * * @param annotationProperties * @returns The command properties to send with the actual annotation command * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 */ function toCommandProperties(annotationProperties) { if (!Object.keys(annotationProperties).length) { return {}; } return { title: annotationProperties.title, file: annotationProperties.file, line: annotationProperties.startLine, endLine: annotationProperties.endLine, col: annotationProperties.startColumn, endColumn: annotationProperties.endColumn }; } exports.toCommandProperties = toCommandProperties; //# sourceMappingURL=utils.js.map /***/ }), /***/ 9206: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); class BasicCredentialHandler { constructor(username, password) { this.username = username; this.password = password; } prepareRequest(options) { options.headers['Authorization'] = 'Basic ' + Buffer.from(this.username + ':' + this.password).toString('base64'); } // This handler cannot handle 401 canHandleAuthentication(response) { return false; } handleAuthentication(httpClient, requestInfo, objs) { return null; } } exports.BasicCredentialHandler = BasicCredentialHandler; class BearerCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { options.headers['Authorization'] = 'Bearer ' + this.token; } // This handler cannot handle 401 canHandleAuthentication(response) { return false; } handleAuthentication(httpClient, requestInfo, objs) { return null; } } exports.BearerCredentialHandler = BearerCredentialHandler; class PersonalAccessTokenCredentialHandler { constructor(token) { this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 prepareRequest(options) { options.headers['Authorization'] = 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); } // This handler cannot handle 401 canHandleAuthentication(response) { return false; } handleAuthentication(httpClient, requestInfo, objs) { return null; } } exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; /***/ }), /***/ 9926: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const http = __webpack_require__(8605); const https = __webpack_require__(7211); const pm = __webpack_require__(3466); let tunnel; var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; })(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; })(Headers = exports.Headers || (exports.Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; })(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ function getProxyUrl(serverUrl) { let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); return proxyUrl ? proxyUrl.href : ''; } exports.getProxyUrl = getProxyUrl; const HttpRedirectCodes = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ]; const HttpResponseRetryCodes = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ]; const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; const ExponentialBackoffCeiling = 10; const ExponentialBackoffTimeSlice = 5; class HttpClientError extends Error { constructor(message, statusCode) { super(message); this.name = 'HttpClientError'; this.statusCode = statusCode; Object.setPrototypeOf(this, HttpClientError.prototype); } } exports.HttpClientError = HttpClientError; class HttpClientResponse { constructor(message) { this.message = message; } readBody() { return new Promise(async (resolve, reject) => { let output = Buffer.alloc(0); this.message.on('data', (chunk) => { output = Buffer.concat([output, chunk]); }); this.message.on('end', () => { resolve(output.toString()); }); }); } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { let parsedUrl = new URL(requestUrl); return parsedUrl.protocol === 'https:'; } exports.isHttps = isHttps; class HttpClient { constructor(userAgent, handlers, requestOptions) { this._ignoreSslError = false; this._allowRedirects = true; this._allowRedirectDowngrade = false; this._maxRedirects = 50; this._allowRetries = false; this._maxRetries = 1; this._keepAlive = false; this._disposed = false; this.userAgent = userAgent; this.handlers = handlers || []; this.requestOptions = requestOptions; if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError; } this._socketTimeout = requestOptions.socketTimeout; if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects; } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive; } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries; } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries; } } } options(requestUrl, additionalHeaders) { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); } get(requestUrl, additionalHeaders) { return this.request('GET', requestUrl, null, additionalHeaders || {}); } del(requestUrl, additionalHeaders) { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); } post(requestUrl, data, additionalHeaders) { return this.request('POST', requestUrl, data, additionalHeaders || {}); } patch(requestUrl, data, additionalHeaders) { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); } put(requestUrl, data, additionalHeaders) { return this.request('PUT', requestUrl, data, additionalHeaders || {}); } head(requestUrl, additionalHeaders) { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); } sendStream(verb, requestUrl, stream, additionalHeaders) { return this.request(verb, requestUrl, stream, additionalHeaders); } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ async getJson(requestUrl, additionalHeaders = {}) { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); let res = await this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); } async postJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async putJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } async patchJson(requestUrl, obj, additionalHeaders = {}) { let data = JSON.stringify(obj, null, 2); additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); let res = await this.patch(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ async request(verb, requestUrl, data, headers) { if (this._disposed) { throw new Error('Client has already been disposed.'); } let parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 ? this._maxRetries + 1 : 1; let numTries = 0; let response; while (numTries < maxTries) { response = await this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i]; break; } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data); } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response; } } let redirectsRemaining = this._maxRedirects; while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } let parsedRedirectUrl = new URL(redirectUrl); if (parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade) { throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); } // we need to finish reading the response before reassigning response // which will leak the open socket. await response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (let header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header]; } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers); response = await this.requestRaw(info, data); redirectsRemaining--; } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { await response.readBody(); await this._performExponentialBackoff(numTries); } } return response; } /** * Needs to be called if keepAlive is set to true in request options. */ dispose() { if (this._agent) { this._agent.destroy(); } this._disposed = true; } /** * Raw request. * @param info * @param data */ requestRaw(info, data) { return new Promise((resolve, reject) => { let callbackForResult = function (err, res) { if (err) { reject(err); } resolve(res); }; this.requestRawWithCallback(info, data, callbackForResult); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { let socket; if (typeof data === 'string') { info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; let handleResult = (err, res) => { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } }; let req = info.httpModule.request(info.options, (msg) => { let res = new HttpClientResponse(msg); handleResult(null, res); }); req.on('socket', sock => { socket = sock; }); // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end(); } handleResult(new Error('Request timeout: ' + info.options.path), null); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null); }); if (data && typeof data === 'string') { req.write(data, 'utf8'); } if (data && typeof data !== 'string') { data.on('close', function () { req.end(); }); data.pipe(req); } else { req.end(); } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl) { let parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; const usingSsl = info.parsedUrl.protocol === 'https:'; info.httpModule = usingSsl ? https : http; const defaultPort = usingSsl ? 443 : 80; info.options = {}; info.options.host = info.parsedUrl.hostname; info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort; info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); info.options.method = method; info.options.headers = this._mergeHeaders(headers); if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent; } info.options.agent = this._getAgent(info.parsedUrl); // gives handlers an opportunity to participate if (this.handlers) { this.handlers.forEach(handler => { handler.prepareRequest(info.options); }); } return info; } _mergeHeaders(headers) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; let proxyUrl = pm.getProxyUrl(parsedUrl); let useProxy = proxyUrl && proxyUrl.hostname; if (this._keepAlive && useProxy) { agent = this._proxyAgent; } if (this._keepAlive && !useProxy) { agent = this._agent; } // if agent is already assigned use that agent. if (!!agent) { return agent; } const usingSsl = parsedUrl.protocol === 'https:'; let maxSockets = 100; if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = __webpack_require__(9382); } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { ...((proxyUrl.username || proxyUrl.password) && { proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` }), host: proxyUrl.hostname, port: proxyUrl.port } }; let tunnelAgent; const overHttps = proxyUrl.protocol === 'https:'; if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; } agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent; } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }); } return agent; } _performExponentialBackoff(retryNumber) { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); } static dateTimeDeserializer(key, value) { if (typeof value === 'string') { let a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } async _processResponse(res, options) { return new Promise(async (resolve, reject) => { const statusCode = res.message.statusCode; const response = { statusCode: statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode == HttpCodes.NotFound) { resolve(response); } let obj; let contents; // get the result from the body try { contents = await res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); } else { obj = JSON.parse(contents); } response.result = obj; } response.headers = res.message.headers; } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg; // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message; } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents; } else { msg = 'Failed request: (' + statusCode + ')'; } let err = new HttpClientError(msg, statusCode); err.result = response.result; reject(err); } else { resolve(response); } }); } } exports.HttpClient = HttpClient; /***/ }), /***/ 3466: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function getProxyUrl(reqUrl) { let usingSsl = reqUrl.protocol === 'https:'; let proxyUrl; if (checkBypass(reqUrl)) { return proxyUrl; } let proxyVar; if (usingSsl) { proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; } if (proxyVar) { proxyUrl = new URL(proxyVar); } return proxyUrl; } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; } // Determine the request port let reqPort; if (reqUrl.port) { reqPort = Number(reqUrl.port); } else if (reqUrl.protocol === 'http:') { reqPort = 80; } else if (reqUrl.protocol === 'https:') { reqPort = 443; } // Format the request hostname and hostname with port let upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (let upperNoProxyItem of noProxy .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { if (upperReqHosts.some(x => x === upperNoProxyItem)) { return true; } } return false; } exports.checkBypass = checkBypass; /***/ }), /***/ 3353: /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 3197: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var concatMap = __webpack_require__(4527); var balanced = __webpack_require__(3353); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, // but a{},b}c will be expanded to [a}c,abc]. // One could argue that this is a bug in Bash, but since the goal of // this module is to match Bash's rules, we escape a leading {} if (str.substr(0, 2) === '{}') { str = '\\{\\}' + str.substr(2); } return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(',') >= 0; if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*\}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } /***/ }), /***/ 4527: /***/ ((module) => { module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; /***/ }), /***/ 8945: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = realpath realpath.realpath = realpath realpath.sync = realpathSync realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch var fs = __webpack_require__(5747) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) var old = __webpack_require__(4403) function newError (er) { return er && er.syscall === 'realpath' && ( er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG' ) } function realpath (p, cache, cb) { if (ok) { return origRealpath(p, cache, cb) } if (typeof cache === 'function') { cb = cache cache = null } origRealpath(p, cache, function (er, result) { if (newError(er)) { old.realpath(p, cache, cb) } else { cb(er, result) } }) } function realpathSync (p, cache) { if (ok) { return origRealpathSync(p, cache) } try { return origRealpathSync(p, cache) } catch (er) { if (newError(er)) { return old.realpathSync(p, cache) } else { throw er } } } function monkeypatch () { fs.realpath = realpath fs.realpathSync = realpathSync } function unmonkeypatch () { fs.realpath = origRealpath fs.realpathSync = origRealpathSync } /***/ }), /***/ 4403: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var pathModule = __webpack_require__(5622); var isWindows = process.platform === 'win32'; var fs = __webpack_require__(5747); // JavaScript implementation of realpath, ported from node pre-v6 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); function rethrow() { // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and // is fairly slow to generate. var callback; if (DEBUG) { var backtrace = new Error; callback = debugCallback; } else callback = missingCallback; return callback; function debugCallback(err) { if (err) { backtrace.message = err.message; err = backtrace; missingCallback(err); } } function missingCallback(err) { if (err) { if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs else if (!process.noDeprecation) { var msg = 'fs: missing callback ' + (err.stack || err.message); if (process.traceDeprecation) console.trace(msg); else console.error(msg); } } } } function maybeCallback(cb) { return typeof cb === 'function' ? cb : rethrow(); } var normalize = pathModule.normalize; // Regexp that finds the next partion of a (partial) path // result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] if (isWindows) { var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; } else { var nextPartRe = /(.*?)(?:[\/]+|$)/g; } // Regex to find the device root, including trailing slash. E.g. 'c:\\'. if (isWindows) { var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; } else { var splitRootRe = /^[\/]*/; } exports.realpathSync = function realpathSync(p, cache) { // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return cache[p]; } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstatSync(base); knownHard[base] = true; } } // walk down the path, swapping out linked pathparts for their real // values // NB: p.length changes. while (pos < p.length) { // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { continue; } var resolvedLink; if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // some known symbolic link. no need to stat again. resolvedLink = cache[base]; } else { var stat = fs.lstatSync(base); if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; continue; } // read the link if it wasn't read before // dev/ino always return 0 on windows, so skip the check. var linkTarget = null; if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { linkTarget = seenLinks[id]; } } if (linkTarget === null) { fs.statSync(base); linkTarget = fs.readlinkSync(base); } resolvedLink = pathModule.resolve(previous, linkTarget); // track this, if given a cache. if (cache) cache[base] = resolvedLink; if (!isWindows) seenLinks[id] = linkTarget; } // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } if (cache) cache[original] = p; return p; }; exports.realpath = function realpath(p, cache, cb) { if (typeof cb !== 'function') { cb = maybeCallback(cache); cache = null; } // make p is absolute p = pathModule.resolve(p); if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { return process.nextTick(cb.bind(null, null, cache[p])); } var original = p, seenLinks = {}, knownHard = {}; // current character position in p var pos; // the partial path so far, including a trailing slash if any var current; // the partial path without a trailing slash (except when pointing at a root) var base; // the partial path scanned in the previous round, with slash var previous; start(); function start() { // Skip over roots var m = splitRootRe.exec(p); pos = m[0].length; current = m[0]; base = m[0]; previous = ''; // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard[base]) { fs.lstat(base, function(err) { if (err) return cb(err); knownHard[base] = true; LOOP(); }); } else { process.nextTick(LOOP); } } // walk down the path, swapping out linked pathparts for their real // values function LOOP() { // stop if scanned past end of path if (pos >= p.length) { if (cache) cache[original] = p; return cb(null, p); } // find the next part nextPartRe.lastIndex = pos; var result = nextPartRe.exec(p); previous = current; current += result[0]; base = previous + result[1]; pos = nextPartRe.lastIndex; // continue if not a symlink if (knownHard[base] || (cache && cache[base] === base)) { return process.nextTick(LOOP); } if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { // known symbolic link. no need to stat again. return gotResolvedLink(cache[base]); } return fs.lstat(base, gotStat); } function gotStat(err, stat) { if (err) return cb(err); // if not a symlink, skip to the next path part if (!stat.isSymbolicLink()) { knownHard[base] = true; if (cache) cache[base] = base; return process.nextTick(LOOP); } // stat & read the link if not read before // call gotTarget as soon as the link target is known // dev/ino always return 0 on windows, so skip the check. if (!isWindows) { var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); if (seenLinks.hasOwnProperty(id)) { return gotTarget(null, seenLinks[id], base); } } fs.stat(base, function(err) { if (err) return cb(err); fs.readlink(base, function(err, target) { if (!isWindows) seenLinks[id] = target; gotTarget(err, target); }); }); } function gotTarget(err, target, base) { if (err) return cb(err); var resolvedLink = pathModule.resolve(previous, target); if (cache) cache[base] = resolvedLink; gotResolvedLink(resolvedLink); } function gotResolvedLink(resolvedLink) { // resolve the link, then start over p = pathModule.resolve(resolvedLink, p.slice(pos)); start(); } }; /***/ }), /***/ 3561: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(9244) /***/ }), /***/ 9244: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const stream = __webpack_require__(2413) const EventEmitter = __webpack_require__(8614) const LZWEncoder = __webpack_require__(4348) const NeuQuant = __webpack_require__(3829) const { OctreeQuant, Color } = __webpack_require__(9328) class ByteArray { constructor() { this.data = [] } getData() { return Buffer.from(this.data) } writeByte(val) { this.data.push(val) } writeUTFBytes(str) { for (var len = str.length, i = 0; i < len; i++) { this.writeByte(str.charCodeAt(i)) } } writeBytes(array, offset, length) { for (var len = length || array.length, i = offset || 0; i < len; i++) { this.writeByte(array[i]) } } } class GIFEncoder extends EventEmitter { constructor(width, height, algorithm = 'neuquant', useOptimizer = false, totalFrames = 0) { super() this.width = ~~width this.height = ~~height this.algorithm = algorithm this.useOptimizer = useOptimizer this.totalFrames = totalFrames this.frames = 1 this.threshold = 90 this.indexedPixels = null this.palSizeNeu = 7 this.palSizeOct = 7 this.sample = 10 this.colorTab = null this.reuseTab = null this.colorDepth = null this.usedEntry = new Array() this.firstFrame = true this.started = false this.image = null this.prevImage = null this.dispose = -1 this.repeat = 0 this.delay = 0 this.transparent = null this.transIndex = 0 this.readStreams = [] this.out = new ByteArray() } createReadStream(rs) { if (!rs) { rs = new stream.Readable() rs._read = function() {} } this.readStreams.push(rs) return rs } emitData() { if (this.readStreams.length === 0) { return } if (this.out.data.length) { this.readStreams.forEach(rs => { rs.push(Buffer.from(this.out.data)) }) this.out.data = [] } } start() { this.out.writeUTFBytes('GIF89a') this.started = true this.emitData() } end() { if (this.readStreams.length === null) { return } this.emitData() this.readStreams.forEach(rs => rs.push(null)) this.readStreams = [] } addFrame(input) { if (input && input.getImageData) { this.image = input.getImageData(0, 0, this.width, this.height).data } else { this.image = input } this.analyzePixels() if (this.firstFrame) { this.writeLSD() this.writePalette() if (this.repeat >= 0) { this.writeNetscapeExt() } } this.writeGraphicCtrlExt() this.writeImageDesc() if (!this.firstFrame) { this.writePalette() } this.writePixels() this.firstFrame = false this.emitData() if (this.totalFrames) { this.emit('progress', Math.floor((this.frames++ / this.totalFrames) * 100)) } } analyzePixels() { const w = this.width const h = this.height var data = this.image if (this.useOptimizer && this.prevImage) { var delta = 0 for (var len = data.length, i = 0; i < len; i += 4) { if ( data[i] !== this.prevImage[i] || data[i + 1] !== this.prevImage[i + 1] || data[i + 2] !== this.prevImage[i + 2] ) { delta++ } } const match = 100 - Math.ceil((delta / (data.length / 4)) * 100) this.reuseTab = match >= this.threshold } this.prevImage = data if (this.algorithm === 'neuquant') { var count = 0 this.pixels = new Uint8Array(w * h * 3) for (var i = 0; i < h; i++) { for (var j = 0; j < w; j++) { var b = i * w * 4 + j * 4 this.pixels[count++] = data[b] this.pixels[count++] = data[b + 1] this.pixels[count++] = data[b + 2] } } var nPix = this.pixels.length / 3 this.indexedPixels = new Uint8Array(nPix) if (!this.reuseTab) { this.quantizer = new NeuQuant(this.pixels, this.sample) this.quantizer.buildColormap() this.colorTab = this.quantizer.getColormap() } var k = 0 for (var j = 0; j < nPix; j++) { var index = this.quantizer.lookupRGB( this.pixels[k++] & 0xff, this.pixels[k++] & 0xff, this.pixels[k++] & 0xff ) this.usedEntry[index] = true this.indexedPixels[j] = index } this.colorDepth = 8 this.palSizeNeu = 7 this.pixels = null } else if (this.algorithm === 'octree') { this.colors = [] if (!this.reuseTab) { this.quantizer = new OctreeQuant() } for (var i = 0; i < h; i++) { for (var j = 0; j < w; j++) { var b = i * w * 4 + j * 4 const color = new Color(data[b], data[b + 1], data[b + 2]) this.colors.push(color) if (!this.reuseTab) { this.quantizer.addColor(color) } } } const nPix = this.colors.length this.indexedPixels = new Uint8Array(nPix) if (!this.reuseTab) { this.colorTab = [] const palette = this.quantizer.makePalette(Math.pow(2, this.palSizeOct + 1)) for (const p of palette) { this.colorTab.push(p.red, p.green, p.blue) } } for (var i = 0; i < nPix; i++) { this.indexedPixels[i] = this.quantizer.getPaletteIndex(this.colors[i]) } this.colorDepth = this.palSizeOct + 1 } if (this.transparent !== null) { this.transIndex = this.findClosest(this.transparent) for (var pixelIndex = 0; pixelIndex < nPix; pixelIndex++) { if (this.image[pixelIndex * 4 + 3] == 0) { this.indexedPixels[pixelIndex] = this.transIndex } } } } findClosest(c) { if (this.colorTab === null) { return -1 } var r = (c & 0xff0000) >> 16 var g = (c & 0x00ff00) >> 8 var b = c & 0x0000ff var minpos = 0 var dmin = 256 * 256 * 256 var len = this.colorTab.length for (var i = 0; i < len; ) { var index = i / 3 var dr = r - (this.colorTab[i++] & 0xff) var dg = g - (this.colorTab[i++] & 0xff) var db = b - (this.colorTab[i++] & 0xff) var d = dr * dr + dg * dg + db * db if (this.usedEntry[index] && d < dmin) { dmin = d minpos = index } } return minpos } setFrameRate(fps) { this.delay = Math.round(100 / fps) } setDelay(ms) { this.delay = Math.round(ms / 10) } setDispose(code) { if (code >= 0) { this.dispose = code } } setRepeat(repeat) { this.repeat = repeat } setTransparent(color) { this.transparent = color } setQuality(quality) { if (quality < 1) { quality = 1 } this.quality = quality } setThreshold(threshold) { if (threshold > 100) { threshold = 100 } else if (threshold < 0) { threshold = 0 } this.threshold = threshold } setPaletteSize(size) { if (size > 7) { size = 7 } else if (size < 4) { size = 4 } this.palSizeOct = size } writeLSD() { this.writeShort(this.width) this.writeShort(this.height) this.out.writeByte(0x80 | 0x70 | 0x00 | this.palSizeNeu) this.out.writeByte(0) this.out.writeByte(0) } writeGraphicCtrlExt() { this.out.writeByte(0x21) this.out.writeByte(0xf9) this.out.writeByte(4) var transp, disp if (this.transparent === null) { transp = 0 disp = 0 } else { transp = 1 disp = 2 } if (this.dispose >= 0) { disp = this.dispose & 7 } disp <<= 2 this.out.writeByte(0 | disp | 0 | transp) this.writeShort(this.delay) this.out.writeByte(this.transIndex) this.out.writeByte(0) } writeNetscapeExt() { this.out.writeByte(0x21) this.out.writeByte(0xff) this.out.writeByte(11) this.out.writeUTFBytes('NETSCAPE2.0') this.out.writeByte(3) this.out.writeByte(1) this.writeShort(this.repeat) this.out.writeByte(0) } writeImageDesc() { this.out.writeByte(0x2c) this.writeShort(0) this.writeShort(0) this.writeShort(this.width) this.writeShort(this.height) if (this.firstFrame) { this.out.writeByte(0) } else { this.out.writeByte(0x80 | 0 | 0 | 0 | this.palSizeNeu) } } writePalette() { this.out.writeBytes(this.colorTab) var n = 3 * 256 - this.colorTab.length for (var i = 0; i < n; i++) { this.out.writeByte(0) } } writeShort(pValue) { this.out.writeByte(pValue & 0xff) this.out.writeByte((pValue >> 8) & 0xff) } writePixels() { var enc = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth) enc.encode(this.out) } finish() { this.out.writeByte(0x3b) this.end() } } module.exports = GIFEncoder /***/ }), /***/ 4348: /***/ ((module) => { /* LZWEncoder.js Authors Kevin Weiner (original Java version - kweiner@fmsware.com) Thibault Imbert (AS3 version - bytearray.org) Johan Nordberg (JS version - code@johan-nordberg.com) Acknowledgements GIFCOMPR.C - GIF Image compression routines Lempel-Ziv compression based on 'compress'. GIF modifications by David Rowley (mgardi@watdcsu.waterloo.edu) GIF Image compression - modified 'compress' Based on: compress.c - File compression ala IEEE Computer, June 1984. By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) Jim McKie (decvax!mcvax!jim) Steve Davies (decvax!vax135!petsd!peora!srd) Ken Turkowski (decvax!decwrl!turtlevax!ken) James A. Woods (decvax!ihnp4!ames!jaw) Joe Orost (decvax!vax135!petsd!joe) */ var EOF = -1 var BITS = 12 var HSIZE = 5003 // 80% occupancy var masks = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff ] function LZWEncoder(width, height, pixels, colorDepth) { var initCodeSize = Math.max(2, colorDepth) var accum = new Uint8Array(256) var htab = new Int32Array(HSIZE) var codetab = new Int32Array(HSIZE) var cur_accum, cur_bits = 0 var a_count var free_ent = 0 // first unused entry var maxcode // block compression parameters -- after all codes are used up, // and compression rate changes, start over. var clear_flg = false // Algorithm: use open addressing double hashing (no chaining) on the // prefix code / next character combination. We do a variant of Knuth's // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime // secondary probe. Here, the modular division first probe is gives way // to a faster exclusive-or manipulation. Also do block compression with // an adaptive reset, whereby the code table is cleared when the compression // ratio decreases, but after the table fills. The variable-length output // codes are re-sized at this point, and a special CLEAR code is generated // for the decompressor. Late addition: construct the table according to // file size for noticeable speed improvement on small files. Please direct // questions about this implementation to ames!jaw. var g_init_bits, ClearCode, EOFCode // Add a character to the end of the current packet, and if it is 254 // characters, flush the packet to disk. function char_out(c, outs) { accum[a_count++] = c if (a_count >= 254) flush_char(outs) } // Clear out the hash table // table clear for block compress function cl_block(outs) { cl_hash(HSIZE) free_ent = ClearCode + 2 clear_flg = true output(ClearCode, outs) } // Reset code table function cl_hash(hsize) { for (var i = 0; i < hsize; ++i) htab[i] = -1 } function compress(init_bits, outs) { var fcode, c, i, ent, disp, hsize_reg, hshift // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits // Set up the necessary values clear_flg = false n_bits = g_init_bits maxcode = MAXCODE(n_bits) ClearCode = 1 << (init_bits - 1) EOFCode = ClearCode + 1 free_ent = ClearCode + 2 a_count = 0 // clear packet ent = nextPixel() hshift = 0 for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift hshift = 8 - hshift // set hash code range bound hsize_reg = HSIZE cl_hash(hsize_reg) // clear hash table output(ClearCode, outs) outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << BITS) + ent i = (c << hshift) ^ ent // xor hashing if (htab[i] === fcode) { ent = codetab[i] continue } else if (htab[i] >= 0) { // non-empty slot disp = hsize_reg - i // secondary hash (after G. Knott) if (i === 0) disp = 1 do { if ((i -= disp) < 0) i += hsize_reg if (htab[i] === fcode) { ent = codetab[i] continue outer_loop } } while (htab[i] >= 0) } output(ent, outs) ent = c if (free_ent < 1 << BITS) { codetab[i] = free_ent++ // code -> hashtable htab[i] = fcode } else { cl_block(outs) } } // Put out the final code. output(ent, outs) output(EOFCode, outs) } function encode(outs) { outs.writeByte(initCodeSize) // write "initial code size" byte remaining = width * height // reset navigation variables curPixel = 0 compress(initCodeSize + 1, outs) // compress and write the pixel data outs.writeByte(0) // write block terminator } // Flush the packet to disk, and reset the accumulator function flush_char(outs) { if (a_count > 0) { outs.writeByte(a_count) outs.writeBytes(accum, 0, a_count) a_count = 0 } } function MAXCODE(n_bits) { return (1 << n_bits) - 1 } // Return the next pixel from the image function nextPixel() { if (remaining === 0) return EOF --remaining var pix = pixels[curPixel++] return pix & 0xff } function output(code, outs) { cur_accum &= masks[cur_bits] if (cur_bits > 0) cur_accum |= code << cur_bits else cur_accum = code cur_bits += n_bits while (cur_bits >= 8) { char_out(cur_accum & 0xff, outs) cur_accum >>= 8 cur_bits -= 8 } // If the next entry is going to be too big for the code size, // then increase it, if possible. if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE((n_bits = g_init_bits)) clear_flg = false } else { ++n_bits if (n_bits == BITS) maxcode = 1 << BITS else maxcode = MAXCODE(n_bits) } } if (code == EOFCode) { // At EOF, write the rest of the buffer. while (cur_bits > 0) { char_out(cur_accum & 0xff, outs) cur_accum >>= 8 cur_bits -= 8 } flush_char(outs) } } this.encode = encode } module.exports = LZWEncoder /***/ }), /***/ 9328: /***/ ((module) => { /* Authors Dmitry Alimov (Python version) https://github.com/delimitry/octree_color_quantizer Tom MacWright (JavaScript version) https://observablehq.com/@tmcw/octree-color-quantization */ const MAX_DEPTH = 8 class OctreeQuant { constructor() { this.levels = Array.from({ length: MAX_DEPTH }, () => []) this.root = new Node(0, this) } addColor(color) { this.root.addColor(color, 0, this) } makePalette(colorCount) { let palette = [] let paletteIndex = 0 let leafCount = this.leafNodes.length for (let level = MAX_DEPTH - 1; level > -1; level -= 1) { if (this.levels[level]) { for (let node of this.levels[level]) { leafCount -= node.removeLeaves() if (leafCount <= colorCount) break } if (leafCount <= colorCount) break this.levels[level] = [] } } for (let node of this.leafNodes) { if (paletteIndex >= colorCount) break if (node.isLeaf) palette.push(node.color) node.paletteIndex = paletteIndex paletteIndex++ } return palette } *makePaletteIncremental(colorCount) { let palette = [] let paletteIndex = 0 let leafCount = this.leafNodes.length for (let level = MAX_DEPTH - 1; level > -1; level -= 1) { if (this.levels[level]) { for (let node of this.levels[level]) { leafCount -= node.removeLeaves() if (leafCount <= colorCount) break } if (leafCount <= colorCount) break this.levels[level] = [] } yield } for (let node of this.leafNodes) { if (paletteIndex >= colorCount) break if (node.isLeaf) palette.push(node.color) node.paletteIndex = paletteIndex paletteIndex++ } yield return palette } get leafNodes() { return this.root.leafNodes } addLevelNode(level, node) { this.levels[level].push(node) } getPaletteIndex(color) { return this.root.getPaletteIndex(color, 0) } } class Node { constructor(level, parent) { this._color = new Color(0, 0, 0) this.pixelCount = 0 this.paletteIndex = 0 this.children = [] this._debugColor if (level < MAX_DEPTH - 1) parent.addLevelNode(level, this) } get isLeaf() { return this.pixelCount > 0 } get leafNodes() { let leafNodes = [] for (let node of this.children) { if (!node) continue if (node.isLeaf) { leafNodes.push(node) } else { leafNodes.push(...node.leafNodes) } } return leafNodes } addColor(color, level, parent) { if (level >= MAX_DEPTH) { this._color.add(color) this.pixelCount++ return } let index = getColorIndex(color, level) if (!this.children[index]) { this.children[index] = new Node(level, parent) } this.children[index].addColor(color, level + 1, parent) } getPaletteIndex(color, level) { if (this.isLeaf) { return this.paletteIndex } let index = getColorIndex(color, level) if (this.children[index]) { return this.children[index].getPaletteIndex(color, level + 1) } else { for (let node of this.children) { if (node) { return node.getPaletteIndex(color, level + 1) } } } } removeLeaves() { let result = 0 for (let node of this.children) { if (!node) continue this._color.add(node._color) this.pixelCount += node.pixelCount result++ } this.children = [] return result - 1 } get debugColor() { if (this._debugColor) return this._debugColor if (this.isLeaf) return this.color let c = new Color() let count = 0 function traverse(node) { for (let child of node.children) { if (child.isLeaf) { c.add(child._color) count++ } else { traverse(child) } } } traverse(this) return c.normalized(count) } get color() { return this._color.normalized(this.pixelCount) } } class Color { constructor(red = 0, green = 0, blue = 0) { this.red = red this.green = green this.blue = blue } clone() { return new Color(this.red, this.green, this.blue) } get array() { return [this.red, this.green, this.blue, this.red + this.green + this.blue] } toString() { return [this.red, this.green, this.blue].join(',') } toCSS() { return `rgb(${[this.red, this.green, this.blue].map(n => Math.floor(n)).join(',')})` } normalized(pixelCount) { return new Color(this.red / pixelCount, this.green / pixelCount, this.blue / pixelCount) } add(color) { this.red += color.red this.green += color.green this.blue += color.blue } } function getColorIndex(color, level) { let index = 0 let mask = 0b10000000 >> level if (color.red & mask) index |= 0b100 if (color.green & mask) index |= 0b010 if (color.blue & mask) index |= 0b001 return index } module.exports = { OctreeQuant, Node, Color } /***/ }), /***/ 3829: /***/ ((module) => { /* NeuQuant Neural-Net Quantization Algorithm * ------------------------------------------ * * Copyright (c) 1994 Anthony Dekker * * NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994. * See "Kohonen neural networks for optimal colour quantization" * in "Network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367. * for a discussion of the algorithm. * See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML * * Any party obtaining a copy of these files from the author, directly or * indirectly, is granted, free of charge, a full and unrestricted irrevocable, * world-wide, paid up, royalty-free, nonexclusive right and license to deal * in this software and documentation files (the "Software"), including without * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons who receive * copies from any such party to do so, with the only requirement being * that this copyright notice remain intact. * * (JavaScript port 2012 by Johan Nordberg) */ var ncycles = 100 // number of learning cycles var netsize = 256 // number of colors used var maxnetpos = netsize - 1 // defs for freq and bias var netbiasshift = 4 // bias for colour values var intbiasshift = 16 // bias for fractions var intbias = 1 << intbiasshift var gammashift = 10 var gamma = 1 << gammashift var betashift = 10 var beta = intbias >> betashift /* beta = 1/1024 */ var betagamma = intbias << (gammashift - betashift) // defs for decreasing radius factor var initrad = netsize >> 3 // for 256 cols, radius starts var radiusbiasshift = 6 // at 32.0 biased by 6 bits var radiusbias = 1 << radiusbiasshift var initradius = initrad * radiusbias //and decreases by a var radiusdec = 30 // factor of 1/30 each cycle // defs for decreasing alpha factor var alphabiasshift = 10 // alpha starts at 1.0 var initalpha = 1 << alphabiasshift var alphadec // biased by 10 bits /* radbias and alpharadbias used for radpower calculation */ var radbiasshift = 8 var radbias = 1 << radbiasshift var alpharadbshift = alphabiasshift + radbiasshift var alpharadbias = 1 << alpharadbshift // four primes near 500 - assume no image has a length so large that it is // divisible by all four primes var prime1 = 499 var prime2 = 491 var prime3 = 487 var prime4 = 503 var minpicturebytes = 3 * prime4 /* Constructor: NeuQuant Arguments: pixels - array of pixels in RGB format samplefac - sampling factor 1 to 30 where lower is better quality > > pixels = [r, g, b, r, g, b, r, g, b, ..] > */ function NeuQuant(pixels, samplefac) { var network // int[netsize][4] var netindex // for network lookup - really 256 // bias and freq arrays for learning var bias var freq var radpower /* Private Method: init sets up arrays */ function init() { network = [] netindex = new Int32Array(256) bias = new Int32Array(netsize) freq = new Int32Array(netsize) radpower = new Int32Array(netsize >> 3) var i, v for (i = 0; i < netsize; i++) { v = (i << (netbiasshift + 8)) / netsize network[i] = new Float64Array([v, v, v, 0]) //network[i] = [v, v, v, 0] freq[i] = intbias / netsize bias[i] = 0 } } /* Private Method: unbiasnet unbiases network to give byte values 0..255 and record position i to prepare for sort */ function unbiasnet() { for (var i = 0; i < netsize; i++) { network[i][0] >>= netbiasshift network[i][1] >>= netbiasshift network[i][2] >>= netbiasshift network[i][3] = i // record color number } } /* Private Method: altersingle moves neuron *i* towards biased (b,g,r) by factor *alpha* */ function altersingle(alpha, i, b, g, r) { network[i][0] -= (alpha * (network[i][0] - b)) / initalpha network[i][1] -= (alpha * (network[i][1] - g)) / initalpha network[i][2] -= (alpha * (network[i][2] - r)) / initalpha } /* Private Method: alterneigh moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha* */ function alterneigh(radius, i, b, g, r) { var lo = Math.abs(i - radius) var hi = Math.min(i + radius, netsize) var j = i + 1 var k = i - 1 var m = 1 var p, a while (j < hi || k > lo) { a = radpower[m++] if (j < hi) { p = network[j++] p[0] -= (a * (p[0] - b)) / alpharadbias p[1] -= (a * (p[1] - g)) / alpharadbias p[2] -= (a * (p[2] - r)) / alpharadbias } if (k > lo) { p = network[k--] p[0] -= (a * (p[0] - b)) / alpharadbias p[1] -= (a * (p[1] - g)) / alpharadbias p[2] -= (a * (p[2] - r)) / alpharadbias } } } /* Private Method: contest searches for biased BGR values */ function contest(b, g, r) { /* finds closest neuron (min dist) and updates freq finds best neuron (min dist-bias) and returns position for frequently chosen neurons, freq[i] is high and bias[i] is negative bias[i] = gamma * ((1 / netsize) - freq[i]) */ var bestd = ~(1 << 31) var bestbiasd = bestd var bestpos = -1 var bestbiaspos = bestpos var i, n, dist, biasdist, betafreq for (i = 0; i < netsize; i++) { n = network[i] dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r) if (dist < bestd) { bestd = dist bestpos = i } biasdist = dist - (bias[i] >> (intbiasshift - netbiasshift)) if (biasdist < bestbiasd) { bestbiasd = biasdist bestbiaspos = i } betafreq = freq[i] >> betashift freq[i] -= betafreq bias[i] += betafreq << gammashift } freq[bestpos] += beta bias[bestpos] -= betagamma return bestbiaspos } /* Private Method: inxbuild sorts network and builds netindex[0..255] */ function inxbuild() { var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0 for (i = 0; i < netsize; i++) { p = network[i] smallpos = i smallval = p[1] // index on g // find smallest in i..netsize-1 for (j = i + 1; j < netsize; j++) { q = network[j] if (q[1] < smallval) { // index on g smallpos = j smallval = q[1] // index on g } } q = network[smallpos] // swap p (i) and q (smallpos) entries if (i != smallpos) { j = q[0] q[0] = p[0] p[0] = j j = q[1] q[1] = p[1] p[1] = j j = q[2] q[2] = p[2] p[2] = j j = q[3] q[3] = p[3] p[3] = j } // smallval entry is now in position i if (smallval != previouscol) { netindex[previouscol] = (startpos + i) >> 1 for (j = previouscol + 1; j < smallval; j++) netindex[j] = i previouscol = smallval startpos = i } } netindex[previouscol] = (startpos + maxnetpos) >> 1 for (j = previouscol + 1; j < 256; j++) netindex[j] = maxnetpos // really 256 } /* Private Method: inxsearch searches for BGR values 0..255 and returns a color index */ function inxsearch(b, g, r) { var a, p, dist var bestd = 1000 // biggest possible dist is 256*3 var best = -1 var i = netindex[g] // index on g var j = i - 1 // start at netindex[g] and work outwards while (i < netsize || j >= 0) { if (i < netsize) { p = network[i] dist = p[1] - g // inx key if (dist >= bestd) i = netsize // stop iter else { i++ if (dist < 0) dist = -dist a = p[0] - b if (a < 0) a = -a dist += a if (dist < bestd) { a = p[2] - r if (a < 0) a = -a dist += a if (dist < bestd) { bestd = dist best = p[3] } } } } if (j >= 0) { p = network[j] dist = g - p[1] // inx key - reverse dif if (dist >= bestd) j = -1 // stop iter else { j-- if (dist < 0) dist = -dist a = p[0] - b if (a < 0) a = -a dist += a if (dist < bestd) { a = p[2] - r if (a < 0) a = -a dist += a if (dist < bestd) { bestd = dist best = p[3] } } } } } return best } /* Private Method: learn "Main Learning Loop" */ function learn() { var i var lengthcount = pixels.length var alphadec = 30 + (samplefac - 1) / 3 var samplepixels = lengthcount / (3 * samplefac) var delta = ~~(samplepixels / ncycles) var alpha = initalpha var radius = initradius var rad = radius >> radiusbiasshift if (rad <= 1) rad = 0 for (i = 0; i < rad; i++) radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad)) var step if (lengthcount < minpicturebytes) { samplefac = 1 step = 3 } else if (lengthcount % prime1 !== 0) { step = 3 * prime1 } else if (lengthcount % prime2 !== 0) { step = 3 * prime2 } else if (lengthcount % prime3 !== 0) { step = 3 * prime3 } else { step = 3 * prime4 } var b, g, r, j var pix = 0 // current pixel i = 0 while (i < samplepixels) { b = (pixels[pix] & 0xff) << netbiasshift g = (pixels[pix + 1] & 0xff) << netbiasshift r = (pixels[pix + 2] & 0xff) << netbiasshift j = contest(b, g, r) altersingle(alpha, j, b, g, r) if (rad !== 0) alterneigh(rad, j, b, g, r) // alter neighbours pix += step if (pix >= lengthcount) pix -= lengthcount i++ if (delta === 0) delta = 1 if (i % delta === 0) { alpha -= alpha / alphadec radius -= radius / radiusdec rad = radius >> radiusbiasshift if (rad <= 1) rad = 0 for (j = 0; j < rad; j++) radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad)) } } } /* Method: buildColormap 1. initializes network 2. trains it 3. removes misconceptions 4. builds colorindex */ function buildColormap() { init() learn() unbiasnet() inxbuild() } this.buildColormap = buildColormap /* Method: getColormap builds colormap from the index returns array in the format: > > [r, g, b, r, g, b, r, g, b, ..] > */ function getColormap() { var map = [] var index = [] for (var i = 0; i < netsize; i++) index[network[i][3]] = i var k = 0 for (var l = 0; l < netsize; l++) { var j = index[l] map[k++] = network[j][0] map[k++] = network[j][1] map[k++] = network[j][2] } return map } this.getColormap = getColormap /* Method: lookupRGB looks for the closest *r*, *g*, *b* color in the map and returns its index */ this.lookupRGB = inxsearch } module.exports = NeuQuant /***/ }), /***/ 2821: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { exports.alphasort = alphasort exports.alphasorti = alphasorti exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs exports.finish = finish exports.mark = mark exports.isIgnored = isIgnored exports.childrenIgnored = childrenIgnored function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } var path = __webpack_require__(5622) var minimatch = __webpack_require__(9566) var isAbsolute = __webpack_require__(1323) var Minimatch = minimatch.Minimatch function alphasorti (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()) } function alphasort (a, b) { return a.localeCompare(b) } function setupIgnores (self, options) { self.ignore = options.ignore || [] if (!Array.isArray(self.ignore)) self.ignore = [self.ignore] if (self.ignore.length) { self.ignore = self.ignore.map(ignoreMap) } } // ignore patterns are always in dot:true mode. function ignoreMap (pattern) { var gmatcher = null if (pattern.slice(-3) === '/**') { var gpattern = pattern.replace(/(\/\*\*)+$/, '') gmatcher = new Minimatch(gpattern, { dot: true }) } return { matcher: new Minimatch(pattern, { dot: true }), gmatcher: gmatcher } } function setopts (self, pattern, options) { if (!options) options = {} // base-matching: just use globstar for that. if (options.matchBase && -1 === pattern.indexOf("/")) { if (options.noglobstar) { throw new Error("base matching requires globstar") } pattern = "**/" + pattern } self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false self.realpath = !!options.realpath self.realpathCache = options.realpathCache || Object.create(null) self.follow = !!options.follow self.dot = !!options.dot self.mark = !!options.mark self.nodir = !!options.nodir if (self.nodir) self.mark = true self.sync = !!options.sync self.nounique = !!options.nounique self.nonull = !!options.nonull self.nosort = !!options.nosort self.nocase = !!options.nocase self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) self.statCache = options.statCache || Object.create(null) self.symlinks = options.symlinks || Object.create(null) setupIgnores(self, options) self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) self.cwd = cwd else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd } self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true options.nocomment = true self.minimatch = new Minimatch(pattern, options) self.options = self.minimatch.options } function finish (self) { var nou = self.nounique var all = nou ? [] : Object.create(null) for (var i = 0, l = self.matches.length; i < l; i ++) { var matches = self.matches[i] if (!matches || Object.keys(matches).length === 0) { if (self.nonull) { // do like the shell, and spit out the literal glob var literal = self.minimatch.globSet[i] if (nou) all.push(literal) else all[literal] = true } } else { // had matches var m = Object.keys(matches) if (nou) all.push.apply(all, m) else m.forEach(function (m) { all[m] = true }) } } if (!nou) all = Object.keys(all) if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort) // at *some* point we statted all of these if (self.mark) { for (var i = 0; i < all.length; i++) { all[i] = self._mark(all[i]) } if (self.nodir) { all = all.filter(function (e) { var notDir = !(/\/$/.test(e)) var c = self.cache[e] || self.cache[makeAbs(self, e)] if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c) return notDir }) } } if (self.ignore.length) all = all.filter(function(m) { return !isIgnored(self, m) }) self.found = all } function mark (self, p) { var abs = makeAbs(self, p) var c = self.cache[abs] var m = p if (c) { var isDir = c === 'DIR' || Array.isArray(c) var slash = p.slice(-1) === '/' if (isDir && !slash) m += '/' else if (!isDir && slash) m = m.slice(0, -1) if (m !== p) { var mabs = makeAbs(self, m) self.statCache[mabs] = self.statCache[abs] self.cache[mabs] = self.cache[abs] } } return m } // lotta situps... function makeAbs (self, f) { var abs = f if (f.charAt(0) === '/') { abs = path.join(self.root, f) } else if (isAbsolute(f) || f === '') { abs = f } else if (self.changedCwd) { abs = path.resolve(self.cwd, f) } else { abs = path.resolve(f) } if (process.platform === 'win32') abs = abs.replace(/\\/g, '/') return abs } // Return true, if pattern ends with globstar '**', for the accompanying parent directory. // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents function isIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) }) } function childrenIgnored (self, path) { if (!self.ignore.length) return false return self.ignore.some(function(item) { return !!(item.gmatcher && item.gmatcher.match(path)) }) } /***/ }), /***/ 3700: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { // Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var fs = __webpack_require__(5747) var rp = __webpack_require__(8945) var minimatch = __webpack_require__(9566) var Minimatch = minimatch.Minimatch var inherits = __webpack_require__(6919) var EE = __webpack_require__(8614).EventEmitter var path = __webpack_require__(5622) var assert = __webpack_require__(2357) var isAbsolute = __webpack_require__(1323) var globSync = __webpack_require__(7433) var common = __webpack_require__(2821) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = __webpack_require__(9442) var util = __webpack_require__(1669) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = __webpack_require__(7197) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) } /***/ }), /***/ 7433: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = globSync globSync.GlobSync = GlobSync var fs = __webpack_require__(5747) var rp = __webpack_require__(8945) var minimatch = __webpack_require__(9566) var Minimatch = minimatch.Minimatch var Glob = __webpack_require__(3700).Glob var util = __webpack_require__(1669) var path = __webpack_require__(5622) var assert = __webpack_require__(2357) var isAbsolute = __webpack_require__(1323) var common = __webpack_require__(2821) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored function globSync (pattern, options) { if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') return new GlobSync(pattern, options).found } function GlobSync (pattern, options) { if (!pattern) throw new Error('must provide pattern') if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n'+ 'See: https://github.com/isaacs/node-glob/issues/167') if (!(this instanceof GlobSync)) return new GlobSync(pattern, options) setopts(this, pattern, options) if (this.noprocess) return this var n = this.minimatch.set.length this.matches = new Array(n) for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false) } this._finish() } GlobSync.prototype._finish = function () { assert(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { var set = self.matches[index] = Object.create(null) for (var p in matchset) { try { p = self._makeAbs(p) var real = rp.realpathSync(p, self.realpathCache) set[real] = true } catch (er) { if (er.syscall === 'stat') set[self._makeAbs(p)] = true else throw er } } }) } common.finish(this) } GlobSync.prototype._process = function (pattern, index, inGlobStar) { assert(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // See if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip processing if (childrenIgnored(this, read)) return var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // if the abs isn't a dir, then nothing can match! if (!entries) return // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix.slice(-1) !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) newPattern = [prefix, e] else newPattern = [e] this._process(newPattern.concat(remain), index, inGlobStar) } } GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return var abs = this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) { e = abs } if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true if (this.stat) this._stat(e) } GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false) var entries var lstat var stat try { lstat = fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist return null } } var isSym = lstat && lstat.isSymbolicLink() this.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE' else entries = this._readdir(abs, false) return entries } GlobSync.prototype._readdir = function (abs, inGlobStar) { var entries if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return null if (Array.isArray(c)) return c } try { return this._readdirEntries(abs, fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null } } GlobSync.prototype._readdirEntries = function (abs, entries) { // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries // mark and cache dir-ness return entries } GlobSync.prototype._readdirError = function (f, er) { // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code throw error } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) throw er if (!this.silent) console.error('glob error', er) break } } GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { var entries = this._readdir(abs, inGlobStar) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false) var len = entries.length var isSym = this.symlinks[abs] // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true) var below = gspref.concat(entries[i], remain) this._process(below, index, true) } } GlobSync.prototype._processSimple = function (prefix, index) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var exists = this._stat(prefix) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) } // Returns either 'DIR', 'FILE', or false GlobSync.prototype._stat = function (f) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return false if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return c if (needDir && c === 'FILE') return false // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (!stat) { var lstat try { lstat = fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return false } } if (lstat && lstat.isSymbolicLink()) { try { stat = fs.statSync(abs) } catch (er) { stat = lstat } } else { stat = lstat } } this.statCache[abs] = stat var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return false return c } GlobSync.prototype._mark = function (p) { return common.mark(this, p) } GlobSync.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } /***/ }), /***/ 9442: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var wrappy = __webpack_require__(4586) var reqs = Object.create(null) var once = __webpack_require__(7197) module.exports = wrappy(inflight) function inflight (key, cb) { if (reqs[key]) { reqs[key].push(cb) return null } else { reqs[key] = [cb] return makeres(key) } } function makeres (key) { return once(function RES () { var cbs = reqs[key] var len = cbs.length var args = slice(arguments) // XXX It's somewhat ambiguous whether a new callback added in this // pass should be queued for later execution if something in the // list of callbacks throws, or if it should just be discarded. // However, it's such an edge case that it hardly matters, and either // choice is likely as surprising as the other. // As it happens, we do go ahead and schedule it for later execution. try { for (var i = 0; i < len; i++) { cbs[i].apply(null, args) } } finally { if (cbs.length > len) { // added more in the interim. // de-zalgo, just in case, but don't call again. cbs.splice(0, len) process.nextTick(function () { RES.apply(null, args) }) } else { delete reqs[key] } } }) } function slice (args) { var length = args.length var array = [] for (var i = 0; i < length; i++) array[i] = args[i] return array } /***/ }), /***/ 6919: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { try { var util = __webpack_require__(1669); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { /* istanbul ignore next */ module.exports = __webpack_require__(7526); } /***/ }), /***/ 7526: /***/ ((module) => { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }) } }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } } /***/ }), /***/ 9566: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch var path = { sep: '/' } try { path = __webpack_require__(5622) } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} var expand = __webpack_require__(3197) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, '*': { open: '(?:', close: ')*' }, '@': { open: '(?:', close: ')' } } // any single thing other than / // don't need to escape / when using new RegExp() var qmark = '[^/]' // * => any number of characters var star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' // characters that need to be escaped in RegExp. var reSpecials = charSet('().*{}+?[]^$\\!') // "abc" -> { a:true, b:true, c:true } function charSet (s) { return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) } // normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {} b = b || {} var t = {} Object.keys(b).forEach(function (k) { t[k] = b[k] }) Object.keys(a).forEach(function (k) { t[k] = a[k] }) return t } minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return minimatch var orig = minimatch var m = function minimatch (p, pattern, options) { return orig.minimatch(p, pattern, ext(def, options)) } m.Minimatch = function Minimatch (pattern, options) { return new orig.Minimatch(pattern, ext(def, options)) } return m } Minimatch.defaults = function (def) { if (!def || !Object.keys(def).length) return Minimatch return minimatch.defaults(def).Minimatch } function minimatch (p, pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') { throw new TypeError('glob pattern string required') } if (!options) options = {} pattern = pattern.trim() // windows support: need to use /, not \ if (path.sep !== '/') { pattern = pattern.split(path.sep).join('/') } this.options = options this.set = [] this.pattern = pattern this.regexp = null this.negate = false this.comment = false this.empty = false // make the set of regexps etc. this.make() } Minimatch.prototype.debug = function () {} Minimatch.prototype.make = make function make () { // don't do it more than once. if (this._made) return var pattern = this.pattern var options = this.options // empty patterns and comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') { this.comment = true return } if (!pattern) { this.empty = true return } // step 1: figure out negation, etc. this.parseNegate() // step 2: expand braces var set = this.globSet = this.braceExpand() if (options.debug) this.debug = console.error this.debug(this.pattern, set) // step 3: now we have a set, so turn each one into a series of path-portion // matching patterns. // These will be regexps, except in the case of "**", which is // set to the GLOBSTAR object for globstar behavior, // and will not contain any / characters set = this.globParts = set.map(function (s) { return s.split(slashSplit) }) this.debug(this.pattern, set) // glob --> regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return s.indexOf(false) === -1 }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern var negate = false var options = this.options var negateOffset = 0 if (options.nonegate) return for (var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === '!' ; i++) { negate = !negate negateOffset++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) { options = this.options } else { options = {} } } pattern = typeof pattern === 'undefined' ? this.pattern : pattern if (typeof pattern === 'undefined') { throw new TypeError('undefined pattern') } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { if (pattern.length > 1024 * 64) { throw new TypeError('pattern is too long') } var options = this.options // shortcuts if (!options.noglobstar && pattern === '**') return GLOBSTAR if (pattern === '') return '' var re = '' var hasMagic = !!options.nocase var escaping = false // ? => one single character var patternListStack = [] var negativeLists = [] var stateChar var inClass = false var reClassStart = -1 var classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. var patternStart = pattern.charAt(0) === '.' ? '' // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)' var self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case '*': re += star hasMagic = true break case '?': re += qmark hasMagic = true break default: re += '\\' + stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for (var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i++) { this.debug('%s\t%s %s %j', pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += '\\' + c escaping = false continue } switch (c) { case '/': // completely not allowed, even escaped. // Should already be path-split by now. return false case '\\': clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case '?': case '*': case '+': case '@': case '!': this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === '!' && i === classStart + 1) c = '^' re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case '(': if (inClass) { re += '(' continue } if (!stateChar) { re += '\\(' continue } patternListStack.push({ type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, close: plTypes[stateChar].close }) // negation is (?:(?!js)[^/]*) re += stateChar === '!' ? '(?:(?!(?:' : '(?:' this.debug('plType %j %j', stateChar, re) stateChar = false continue case ')': if (inClass || !patternListStack.length) { re += '\\)' continue } clearStateChar() hasMagic = true var pl = patternListStack.pop() // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close if (pl.type === '!') { negativeLists.push(pl) } pl.reEnd = re.length continue case '|': if (inClass || !patternListStack.length || escaping) { re += '\\|' escaping = false continue } clearStateChar() re += '|' continue // these are mostly the same in regexp and glob case '[': // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += '\\' + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case ']': // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += '\\' + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" if (inClass) { // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === '^' && inClass)) { re += '\\' } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is cs = pattern.substr(classStart + 1) sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + pl.open.length) this.debug('setting tail', re, pl) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = '\\' } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + '|' }) this.debug('tail=%j\n %s', tail, tail, pl, re) var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + '\\(' + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += '\\\\' } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case '.': case '[': case '(': addPatternStart = true } // Hack to work around lack of negative lookbehind in JS // A pattern like: *.!(x).!(y|z) needs to ensure that a name // like 'a.xyz.yz' doesn't match. So, the first negative // lookahead, has to look ALL the way ahead, to the end of // the pattern. for (var n = negativeLists.length - 1; n > -1; n--) { var nl = negativeLists[n] var nlBefore = re.slice(0, nl.reStart) var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) var nlAfter = re.slice(nl.reEnd) nlLast += nlAfter // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. var openParensBefore = nlBefore.split('(').length - 1 var cleanAfter = nlAfter for (i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter var dollar = '' if (nlAfter === '' && isSub !== SUBPARSE) { dollar = '$' } var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast re = newRe } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== '' && hasMagic) { re = '(?=.)' + re } if (addPatternStart) { re = patternStart + re } // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [re, hasMagic] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? 'i' : '' try { var regExp = new RegExp('^' + re + '$', flags) } catch (er) { // If it was an invalid regular expression, then it can't match // anything. This trick looks for a character after the end of // the string, which is of course impossible, except in multi-line // mode, but it's not a /m regex. return new RegExp('$.') } regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) { this.regexp = false return this.regexp } var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot var flags = options.nocase ? 'i' : '' var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === 'string') ? regExpEscape(p) : p._src }).join('\\\/') }).join('|') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) { this.regexp = false } return this.regexp } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = match function match (f, partial) { this.debug('match', f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === '' if (f === '/' && partial) return true var options = this.options // windows: need to use /, not \ if (path.sep !== '/') { f = f.split(path.sep).join('/') } // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, 'split', f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, 'set', set) // Find the basename of the path by looking for the last non-empty segment var filename var i for (i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (i = 0; i < set.length; i++) { var pattern = set[i] var file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug('matchOne', { 'this': this, file: file, pattern: pattern }) this.debug('matchOne', file.length, pattern.length) for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length ; (fi < fl) && (pi < pl) ; fi++, pi++) { this.debug('matchOne loop') var p = pattern[pi] var f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi var pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for (; fi < fl; fi++) { if (file[fi] === '.' || file[fi] === '..' || (!options.dot && file[fi].charAt(0) === '.')) return false } return true } // ok, let's see if we can swallow whatever we can. while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === '.' || swallowee === '..' || (!options.dot && swallowee.charAt(0) === '.')) { this.debug('dot detected!', file, fr, pattern, pr) break } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file this.debug('\n>>> no match, partial?', file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === 'string') { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase() } else { hit = f === p } this.debug('string match', p, f, hit) } else { hit = f.match(p) this.debug('pattern match', p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') return emptyFileEnd } // should be unreachable. throw new Error('wtf?') } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, '$1') } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') } /***/ }), /***/ 2197: /***/ ((module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Stream = _interopDefault(__webpack_require__(2413)); var http = _interopDefault(__webpack_require__(8605)); var Url = _interopDefault(__webpack_require__(8835)); var whatwgUrl = _interopDefault(__webpack_require__(3932)); var https = _interopDefault(__webpack_require__(7211)); var zlib = _interopDefault(__webpack_require__(8761)); // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js // fix for "Readable" isn't a named export issue const Readable = Stream.Readable; const BUFFER = Symbol('buffer'); const TYPE = Symbol('type'); class Blob { constructor() { this[TYPE] = ''; const blobParts = arguments[0]; const options = arguments[1]; const buffers = []; let size = 0; if (blobParts) { const a = blobParts; const length = Number(a.length); for (let i = 0; i < length; i++) { const element = a[i]; let buffer; if (element instanceof Buffer) { buffer = element; } else if (ArrayBuffer.isView(element)) { buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); } else if (element instanceof ArrayBuffer) { buffer = Buffer.from(element); } else if (element instanceof Blob) { buffer = element[BUFFER]; } else { buffer = Buffer.from(typeof element === 'string' ? element : String(element)); } size += buffer.length; buffers.push(buffer); } } this[BUFFER] = Buffer.concat(buffers); let type = options && options.type !== undefined && String(options.type).toLowerCase(); if (type && !/[^\u0020-\u007E]/.test(type)) { this[TYPE] = type; } } get size() { return this[BUFFER].length; } get type() { return this[TYPE]; } text() { return Promise.resolve(this[BUFFER].toString()); } arrayBuffer() { const buf = this[BUFFER]; const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); return Promise.resolve(ab); } stream() { const readable = new Readable(); readable._read = function () {}; readable.push(this[BUFFER]); readable.push(null); return readable; } toString() { return '[object Blob]'; } slice() { const size = this.size; const start = arguments[0]; const end = arguments[1]; let relativeStart, relativeEnd; if (start === undefined) { relativeStart = 0; } else if (start < 0) { relativeStart = Math.max(size + start, 0); } else { relativeStart = Math.min(start, size); } if (end === undefined) { relativeEnd = size; } else if (end < 0) { relativeEnd = Math.max(size + end, 0); } else { relativeEnd = Math.min(end, size); } const span = Math.max(relativeEnd - relativeStart, 0); const buffer = this[BUFFER]; const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); const blob = new Blob([], { type: arguments[2] }); blob[BUFFER] = slicedBuffer; return blob; } } Object.defineProperties(Blob.prototype, { size: { enumerable: true }, type: { enumerable: true }, slice: { enumerable: true } }); Object.defineProperty(Blob.prototype, Symbol.toStringTag, { value: 'Blob', writable: false, enumerable: false, configurable: true }); /** * fetch-error.js * * FetchError interface for operational errors */ /** * Create FetchError instance * * @param String message Error message for human * @param String type Error type for machine * @param String systemError For Node.js system error * @return FetchError */ function FetchError(message, type, systemError) { Error.call(this, message); this.message = message; this.type = type; // when err.type is `system`, err.code contains system error code if (systemError) { this.code = this.errno = systemError.code; } // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } FetchError.prototype = Object.create(Error.prototype); FetchError.prototype.constructor = FetchError; FetchError.prototype.name = 'FetchError'; let convert; try { convert = __webpack_require__(9609).convert; } catch (e) {} const INTERNALS = Symbol('Body internals'); // fix an issue where "PassThrough" isn't a named export for node <10 const PassThrough = Stream.PassThrough; /** * Body mixin * * Ref: https://fetch.spec.whatwg.org/#body * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ function Body(body) { var _this = this; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$size = _ref.size; let size = _ref$size === undefined ? 0 : _ref$size; var _ref$timeout = _ref.timeout; let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; if (body == null) { // body is undefined or null body = null; } else if (isURLSearchParams(body)) { // body is a URLSearchParams body = Buffer.from(body.toString()); } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { // body is ArrayBuffer body = Buffer.from(body); } else if (ArrayBuffer.isView(body)) { // body is ArrayBufferView body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); } else if (body instanceof Stream) ; else { // none of the above // coerce to string then buffer body = Buffer.from(String(body)); } this[INTERNALS] = { body, disturbed: false, error: null }; this.size = size; this.timeout = timeout; if (body instanceof Stream) { body.on('error', function (err) { const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); _this[INTERNALS].error = error; }); } } Body.prototype = { get body() { return this[INTERNALS].body; }, get bodyUsed() { return this[INTERNALS].disturbed; }, /** * Decode response as ArrayBuffer * * @return Promise */ arrayBuffer() { return consumeBody.call(this).then(function (buf) { return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); }); }, /** * Return raw response as Blob * * @return Promise */ blob() { let ct = this.headers && this.headers.get('content-type') || ''; return consumeBody.call(this).then(function (buf) { return Object.assign( // Prevent copying new Blob([], { type: ct.toLowerCase() }), { [BUFFER]: buf }); }); }, /** * Decode response as json * * @return Promise */ json() { var _this2 = this; return consumeBody.call(this).then(function (buffer) { try { return JSON.parse(buffer.toString()); } catch (err) { return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); } }); }, /** * Decode response as text * * @return Promise */ text() { return consumeBody.call(this).then(function (buffer) { return buffer.toString(); }); }, /** * Decode response as buffer (non-spec api) * * @return Promise */ buffer() { return consumeBody.call(this); }, /** * Decode response as text, while automatically detecting the encoding and * trying to decode to UTF-8 (non-spec api) * * @return Promise */ textConverted() { var _this3 = this; return consumeBody.call(this).then(function (buffer) { return convertBody(buffer, _this3.headers); }); } }; // In browsers, all properties are enumerable. Object.defineProperties(Body.prototype, { body: { enumerable: true }, bodyUsed: { enumerable: true }, arrayBuffer: { enumerable: true }, blob: { enumerable: true }, json: { enumerable: true }, text: { enumerable: true } }); Body.mixIn = function (proto) { for (const name of Object.getOwnPropertyNames(Body.prototype)) { // istanbul ignore else: future proof if (!(name in proto)) { const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); Object.defineProperty(proto, name, desc); } } }; /** * Consume and convert an entire Body to a Buffer. * * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body * * @return Promise */ function consumeBody() { var _this4 = this; if (this[INTERNALS].disturbed) { return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); } this[INTERNALS].disturbed = true; if (this[INTERNALS].error) { return Body.Promise.reject(this[INTERNALS].error); } let body = this.body; // body is null if (body === null) { return Body.Promise.resolve(Buffer.alloc(0)); } // body is blob if (isBlob(body)) { body = body.stream(); } // body is buffer if (Buffer.isBuffer(body)) { return Body.Promise.resolve(body); } // istanbul ignore if: should never happen if (!(body instanceof Stream)) { return Body.Promise.resolve(Buffer.alloc(0)); } // body is stream // get ready to actually consume the body let accum = []; let accumBytes = 0; let abort = false; return new Body.Promise(function (resolve, reject) { let resTimeout; // allow timeout on slow response body if (_this4.timeout) { resTimeout = setTimeout(function () { abort = true; reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); }, _this4.timeout); } // handle stream errors body.on('error', function (err) { if (err.name === 'AbortError') { // if the request was aborted, reject with this Error abort = true; reject(err); } else { // other errors, such as incorrect content-encoding reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); } }); body.on('data', function (chunk) { if (abort || chunk === null) { return; } if (_this4.size && accumBytes + chunk.length > _this4.size) { abort = true; reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); return; } accumBytes += chunk.length; accum.push(chunk); }); body.on('end', function () { if (abort) { return; } clearTimeout(resTimeout); try { resolve(Buffer.concat(accum, accumBytes)); } catch (err) { // handle streams that have accumulated too much data (issue #414) reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); } }); }); } /** * Detect buffer encoding and convert to target encoding * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding * * @param Buffer buffer Incoming buffer * @param String encoding Target encoding * @return String */ function convertBody(buffer, headers) { if (typeof convert !== 'function') { throw new Error('The package `encoding` must be installed to use the textConverted() function'); } const ct = headers.get('content-type'); let charset = 'utf-8'; let res, str; // header if (ct) { res = /charset=([^;]*)/i.exec(ct); } // no charset in content type, peek at response body for at most 1024 bytes str = buffer.slice(0, 1024).toString(); // html5 if (!res && str) { res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; this[MAP] = Object.create(null); if (init instanceof Headers) { const rawHeaders = init.raw(); const headerNames = Object.keys(rawHeaders); for (const headerName of headerNames) { for (const value of rawHeaders[headerName]) { this.append(headerName, value); } } return; } // We don't worry about converting prop to ByteString here as append() // will handle it. if (init == null) ; else if (typeof init === 'object') { const method = init[Symbol.iterator]; if (method != null) { if (typeof method !== 'function') { throw new TypeError('Header pairs must be iterable'); } // sequence> // Note: per spec we have to first exhaust the lists then process them const pairs = []; for (const pair of init) { if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { throw new TypeError('Each header pair must be iterable'); } pairs.push(Array.from(pair)); } for (const pair of pairs) { if (pair.length !== 2) { throw new TypeError('Each header pair must be a name/value tuple'); } this.append(pair[0], pair[1]); } } else { // record for (const key of Object.keys(init)) { const value = init[key]; this.append(key, value); } } } else { throw new TypeError('Provided initializer must be an object'); } } /** * Return combined header value given name * * @param String name Header name * @return Mixed */ get(name) { name = `${name}`; validateName(name); const key = find(this[MAP], name); if (key === undefined) { return null; } return this[MAP][key].join(', '); } /** * Iterate over all headers * * @param Function callback Executed for each item with parameters (value, name, thisArg) * @param Boolean thisArg `this` context for callback function * @return Void */ forEach(callback) { let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; let pairs = getHeaders(this); let i = 0; while (i < pairs.length) { var _pairs$i = pairs[i]; const name = _pairs$i[0], value = _pairs$i[1]; callback.call(thisArg, value, name, this); pairs = getHeaders(this); i++; } } /** * Overwrite header values given name * * @param String name Header name * @param String value Header value * @return Void */ set(name, value) { name = `${name}`; value = `${value}`; validateName(name); validateValue(value); const key = find(this[MAP], name); this[MAP][key !== undefined ? key : name] = [value]; } /** * Append a value onto existing header * * @param String name Header name * @param String value Header value * @return Void */ append(name, value) { name = `${name}`; value = `${value}`; validateName(name); validateValue(value); const key = find(this[MAP], name); if (key !== undefined) { this[MAP][key].push(value); } else { this[MAP][name] = [value]; } } /** * Check for header name existence * * @param String name Header name * @return Boolean */ has(name) { name = `${name}`; validateName(name); return find(this[MAP], name) !== undefined; } /** * Delete all header values given name * * @param String name Header name * @return Void */ delete(name) { name = `${name}`; validateName(name); const key = find(this[MAP], name); if (key !== undefined) { delete this[MAP][key]; } } /** * Return raw headers (non-spec api) * * @return Object */ raw() { return this[MAP]; } /** * Get an iterator on keys. * * @return Iterator */ keys() { return createHeadersIterator(this, 'key'); } /** * Get an iterator on values. * * @return Iterator */ values() { return createHeadersIterator(this, 'value'); } /** * Get an iterator on entries. * * This is the default iterator of the Headers object. * * @return Iterator */ [Symbol.iterator]() { return createHeadersIterator(this, 'key+value'); } } Headers.prototype.entries = Headers.prototype[Symbol.iterator]; Object.defineProperty(Headers.prototype, Symbol.toStringTag, { value: 'Headers', writable: false, enumerable: false, configurable: true }); Object.defineProperties(Headers.prototype, { get: { enumerable: true }, forEach: { enumerable: true }, set: { enumerable: true }, append: { enumerable: true }, has: { enumerable: true }, delete: { enumerable: true }, keys: { enumerable: true }, values: { enumerable: true }, entries: { enumerable: true } }); function getHeaders(headers) { let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; const keys = Object.keys(headers[MAP]).sort(); return keys.map(kind === 'key' ? function (k) { return k.toLowerCase(); } : kind === 'value' ? function (k) { return headers[MAP][k].join(', '); } : function (k) { return [k.toLowerCase(), headers[MAP][k].join(', ')]; }); } const INTERNAL = Symbol('internal'); function createHeadersIterator(target, kind) { const iterator = Object.create(HeadersIteratorPrototype); iterator[INTERNAL] = { target, kind, index: 0 }; return iterator; } const HeadersIteratorPrototype = Object.setPrototypeOf({ next() { // istanbul ignore if if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { throw new TypeError('Value of `this` is not a HeadersIterator'); } var _INTERNAL = this[INTERNAL]; const target = _INTERNAL.target, kind = _INTERNAL.kind, index = _INTERNAL.index; const values = getHeaders(target, kind); const len = values.length; if (index >= len) { return { value: undefined, done: true }; } this[INTERNAL].index = index + 1; return { value: values[index], done: false }; } }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { value: 'HeadersIterator', writable: false, enumerable: false, configurable: true }); /** * Export the Headers object in a form that Node.js can consume. * * @param Headers headers * @return Object */ function exportNodeCompatibleHeaders(headers) { const obj = Object.assign({ __proto__: null }, headers[MAP]); // http.request() only supports string as Host header. This hack makes // specifying custom Host header possible. const hostHeaderKey = find(headers[MAP], 'Host'); if (hostHeaderKey !== undefined) { obj[hostHeaderKey] = obj[hostHeaderKey][0]; } return obj; } /** * Create a Headers object from an object of headers, ignoring those that do * not conform to HTTP grammar productions. * * @param Object obj Object of headers * @return Headers */ function createHeadersLenient(obj) { const headers = new Headers(); for (const name of Object.keys(obj)) { if (invalidTokenRegex.test(name)) { continue; } if (Array.isArray(obj[name])) { for (const val of obj[name]) { if (invalidHeaderCharRegex.test(val)) { continue; } if (headers[MAP][name] === undefined) { headers[MAP][name] = [val]; } else { headers[MAP][name].push(val); } } } else if (!invalidHeaderCharRegex.test(obj[name])) { headers[MAP][name] = [obj[name]]; } } return headers; } const INTERNALS$1 = Symbol('Response internals'); // fix an issue where "STATUS_CODES" aren't a named export for node <10 const STATUS_CODES = http.STATUS_CODES; /** * Response class * * @param Stream body Readable stream * @param Object opts Response options * @return Void */ class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } } Body.mixIn(Response.prototype); Object.defineProperties(Response.prototype, { url: { enumerable: true }, status: { enumerable: true }, ok: { enumerable: true }, redirected: { enumerable: true }, statusText: { enumerable: true }, headers: { enumerable: true }, clone: { enumerable: true } }); Object.defineProperty(Response.prototype, Symbol.toStringTag, { value: 'Response', writable: false, enumerable: false, configurable: true }); const INTERNALS$2 = Symbol('Request internals'); const URL = Url.URL || whatwgUrl.URL; // fix an issue where "format", "parse" aren't a named export for node <10 const parse_url = Url.parse; const format_url = Url.format; /** * Wrapper around `new URL` to handle arbitrary URLs * * @param {string} urlStr * @return {void} */ function parseURL(urlStr) { /* Check whether the URL is absolute or not Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 */ if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { urlStr = new URL(urlStr).toString(); } // Fallback to old implementation for arbitrary URLs return parse_url(urlStr); } const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; /** * Check if a value is an instance of Request. * * @param Mixed input * @return Boolean */ function isRequest(input) { return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; } function isAbortSignal(signal) { const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); return !!(proto && proto.constructor.name === 'AbortSignal'); } /** * Request class * * @param Mixed input Url or Request instance * @param Object init Custom options * @return Void */ class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parseURL(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parseURL(`${input}`); } input = {}; } else { parsedURL = parseURL(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } } Body.mixIn(Request.prototype); Object.defineProperty(Request.prototype, Symbol.toStringTag, { value: 'Request', writable: false, enumerable: false, configurable: true }); Object.defineProperties(Request.prototype, { method: { enumerable: true }, url: { enumerable: true }, headers: { enumerable: true }, redirect: { enumerable: true }, clone: { enumerable: true }, signal: { enumerable: true } }); /** * Convert a Request to Node.js http request options. * * @param Request A Request instance * @return Object The options object to be passed to http.request */ function getNodeRequestOptions(request) { const parsedURL = request[INTERNALS$2].parsedURL; const headers = new Headers(request[INTERNALS$2].headers); // fetch step 1.3 if (!headers.has('Accept')) { headers.set('Accept', '*/*'); } // Basic fetch if (!parsedURL.protocol || !parsedURL.hostname) { throw new TypeError('Only absolute URLs are supported'); } if (!/^https?:$/.test(parsedURL.protocol)) { throw new TypeError('Only HTTP(S) protocols are supported'); } if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); } // HTTP-network-or-cache fetch steps 2.4-2.7 let contentLengthValue = null; if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { contentLengthValue = '0'; } if (request.body != null) { const totalBytes = getTotalBytes(request); if (typeof totalBytes === 'number') { contentLengthValue = String(totalBytes); } } if (contentLengthValue) { headers.set('Content-Length', contentLengthValue); } // HTTP-network-or-cache fetch step 2.11 if (!headers.has('User-Agent')) { headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); } // HTTP-network-or-cache fetch step 2.15 if (request.compress && !headers.has('Accept-Encoding')) { headers.set('Accept-Encoding', 'gzip,deflate'); } let agent = request.agent; if (typeof agent === 'function') { agent = agent(parsedURL); } if (!headers.has('Connection') && !agent) { headers.set('Connection', 'close'); } // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js return Object.assign({}, parsedURL, { method: request.method, headers: exportNodeCompatibleHeaders(headers), agent }); } /** * abort-error.js * * AbortError interface for cancelled requests */ /** * Create AbortError instance * * @param String message Error message for human * @return AbortError */ function AbortError(message) { Error.call(this, message); this.type = 'aborted'; this.message = message; // hide custom error implementation details from end-users Error.captureStackTrace(this, this.constructor); } AbortError.prototype = Object.create(Error.prototype); AbortError.prototype.constructor = AbortError; AbortError.prototype.name = 'AbortError'; const URL$1 = Url.URL || whatwgUrl.URL; // fix an issue where "PassThrough", "resolve" aren't a named export for node <10 const PassThrough$1 = Stream.PassThrough; const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { const orig = new URL$1(original).hostname; const dest = new URL$1(destination).hostname; return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; /** * Fetch function * * @param Mixed url Absolute url or Request instance * @param Object opts Fetch options * @return Promise */ function fetch(url, opts) { // allow custom promise if (!fetch.Promise) { throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); } Body.Promise = fetch.Promise; // wrap http.request into fetch return new fetch.Promise(function (resolve, reject) { // build request object const request = new Request(url, opts); const options = getNodeRequestOptions(request); const send = (options.protocol === 'https:' ? https : http).request; const signal = request.signal; let response = null; const abort = function abort() { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { request.body.destroy(error); } if (!response || !response.body) return; response.body.emit('error', error); }; if (signal && signal.aborted) { abort(); return; } const abortAndFinalize = function abortAndFinalize() { abort(); finalize(); }; // send request const req = send(options); let reqTimeout; if (signal) { signal.addEventListener('abort', abortAndFinalize); } function finalize() { req.abort(); if (signal) signal.removeEventListener('abort', abortAndFinalize); clearTimeout(reqTimeout); } if (request.timeout) { req.once('socket', function (socket) { reqTimeout = setTimeout(function () { reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); finalize(); }, request.timeout); }); } req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); finalize(); }); req.on('response', function (res) { clearTimeout(reqTimeout); const headers = createHeadersLenient(res.headers); // HTTP fetch step 5 if (fetch.isRedirect(res.statusCode)) { // HTTP fetch step 5.2 const location = headers.get('Location'); // HTTP fetch step 5.3 let locationURL = null; try { locationURL = location === null ? null : new URL$1(location, request.url).toString(); } catch (err) { // error here can only be invalid URL in Location: header // do not throw when options.redirect == manual // let the user extract the errorneous redirect URL if (request.redirect !== 'manual') { reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); finalize(); return; } } // HTTP fetch step 5.5 switch (request.redirect) { case 'error': reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); finalize(); return; case 'manual': // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. if (locationURL !== null) { // handle corrupted header try { headers.set('Location', locationURL); } catch (err) { // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request reject(err); } } break; case 'follow': // HTTP-redirect fetch step 2 if (locationURL === null) { break; } // HTTP-redirect fetch step 5 if (request.counter >= request.follow) { reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); finalize(); return; } // HTTP-redirect fetch step 6 (counter increment) // Create a new Request object. const requestOpts = { headers: new Headers(request.headers), follow: request.follow, counter: request.counter + 1, agent: request.agent, compress: request.compress, method: request.method, body: request.body, signal: request.signal, timeout: request.timeout, size: request.size }; if (!isDomainOrSubdomain(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOpts.headers.delete(name); } } // HTTP-redirect fetch step 9 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); finalize(); return; } // HTTP-redirect fetch step 11 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { requestOpts.method = 'GET'; requestOpts.body = undefined; requestOpts.headers.delete('content-length'); } // HTTP-redirect fetch step 15 resolve(fetch(new Request(locationURL, requestOpts))); finalize(); return; } } // prepare response res.once('end', function () { if (signal) signal.removeEventListener('abort', abortAndFinalize); }); let body = res.pipe(new PassThrough$1()); const response_options = { url: request.url, status: res.statusCode, statusText: res.statusMessage, headers: headers, size: request.size, timeout: request.timeout, counter: request.counter }; // HTTP-network fetch step 12.1.1.3 const codings = headers.get('Content-Encoding'); // HTTP-network fetch step 12.1.1.4: handle content codings // in following scenarios we ignore compression support // 1. compression support is disabled // 2. HEAD request // 3. no Content-Encoding header // 4. no content response (204) // 5. content not modified response (304) if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { response = new Response(body, response_options); resolve(response); return; } // For Node v6+ // Be less strict when decoding compressed responses, since sometimes // servers send slightly invalid responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. const zlibOptions = { flush: zlib.Z_SYNC_FLUSH, finishFlush: zlib.Z_SYNC_FLUSH }; // for gzip if (codings == 'gzip' || codings == 'x-gzip') { body = body.pipe(zlib.createGunzip(zlibOptions)); response = new Response(body, response_options); resolve(response); return; } // for deflate if (codings == 'deflate' || codings == 'x-deflate') { // handle the infamous raw deflate response from old servers // a hack for old IIS and Apache servers const raw = res.pipe(new PassThrough$1()); raw.once('data', function (chunk) { // see http://stackoverflow.com/questions/37519828 if ((chunk[0] & 0x0F) === 0x08) { body = body.pipe(zlib.createInflate()); } else { body = body.pipe(zlib.createInflateRaw()); } response = new Response(body, response_options); resolve(response); }); return; } // for br if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { body = body.pipe(zlib.createBrotliDecompress()); response = new Response(body, response_options); resolve(response); return; } // otherwise, use response as-is response = new Response(body, response_options); resolve(response); }); writeToStream(req, request); }); } /** * Redirect code matching * * @param Number code Status code * @return Boolean */ fetch.isRedirect = function (code) { return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; }; // expose Promise fetch.Promise = global.Promise; module.exports = exports = fetch; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.default = exports; exports.Headers = Headers; exports.Request = Request; exports.Response = Response; exports.FetchError = FetchError; /***/ }), /***/ 7197: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var wrappy = __webpack_require__(4586) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) Object.defineProperty(Function.prototype, 'onceStrict', { value: function () { return onceStrict(this) }, configurable: true }) }) function once (fn) { var f = function () { if (f.called) return f.value f.called = true return f.value = fn.apply(this, arguments) } f.called = false return f } function onceStrict (fn) { var f = function () { if (f.called) throw new Error(f.onceError) f.called = true return f.value = fn.apply(this, arguments) } var name = fn.name || 'Function wrapped with `once`' f.onceError = name + " shouldn't be called more than once" f.called = false return f } /***/ }), /***/ 1323: /***/ ((module) => { "use strict"; function posix(path) { return path.charAt(0) === '/'; } function win32(path) { // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute return Boolean(result[2] || isUnc); } module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; /***/ }), /***/ 2780: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { const assert = __webpack_require__(2357) const path = __webpack_require__(5622) const fs = __webpack_require__(5747) let glob = undefined try { glob = __webpack_require__(3700) } catch (_err) { // treat glob as optional. } const defaultGlobOpts = { nosort: true, silent: true } // for EMFILE handling let timeout = 0 const isWindows = (process.platform === "win32") const defaults = options => { const methods = [ 'unlink', 'chmod', 'stat', 'lstat', 'rmdir', 'readdir' ] methods.forEach(m => { options[m] = options[m] || fs[m] m = m + 'Sync' options[m] = options[m] || fs[m] }) options.maxBusyTries = options.maxBusyTries || 3 options.emfileWait = options.emfileWait || 1000 if (options.glob === false) { options.disableGlob = true } if (options.disableGlob !== true && glob === undefined) { throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') } options.disableGlob = options.disableGlob || false options.glob = options.glob || defaultGlobOpts } const rimraf = (p, options, cb) => { if (typeof options === 'function') { cb = options options = {} } assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert.equal(typeof cb, 'function', 'rimraf: callback function required') assert(options, 'rimraf: invalid options argument provided') assert.equal(typeof options, 'object', 'rimraf: options should be object') defaults(options) let busyTries = 0 let errState = null let n = 0 const next = (er) => { errState = errState || er if (--n === 0) cb(errState) } const afterGlob = (er, results) => { if (er) return cb(er) n = results.length if (n === 0) return cb() results.forEach(p => { const CB = (er) => { if (er) { if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && busyTries < options.maxBusyTries) { busyTries ++ // try again, with the same exact callback as this one. return setTimeout(() => rimraf_(p, options, CB), busyTries * 100) } // this one won't happen if graceful-fs is used. if (er.code === "EMFILE" && timeout < options.emfileWait) { return setTimeout(() => rimraf_(p, options, CB), timeout ++) } // already gone if (er.code === "ENOENT") er = null } timeout = 0 next(er) } rimraf_(p, options, CB) }) } if (options.disableGlob || !glob.hasMagic(p)) return afterGlob(null, [p]) options.lstat(p, (er, stat) => { if (!er) return afterGlob(null, [p]) glob(p, options.glob, afterGlob) }) } // Two possible strategies. // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR // // Both result in an extra syscall when you guess wrong. However, there // are likely far more normal files in the world than directories. This // is based on the assumption that a the average number of files per // directory is >= 1. // // If anyone ever complains about this, then I guess the strategy could // be made configurable somehow. But until then, YAGNI. const rimraf_ = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === "ENOENT") return cb(null) // Windows can EPERM on stat. Life is suffering. if (er && er.code === "EPERM" && isWindows) fixWinEPERM(p, options, er, cb) if (st && st.isDirectory()) return rmdir(p, options, er, cb) options.unlink(p, er => { if (er) { if (er.code === "ENOENT") return cb(null) if (er.code === "EPERM") return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) if (er.code === "EISDIR") return rmdir(p, options, er, cb) } return cb(er) }) }) } const fixWinEPERM = (p, options, er, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.chmod(p, 0o666, er2 => { if (er2) cb(er2.code === "ENOENT" ? null : er) else options.stat(p, (er3, stats) => { if (er3) cb(er3.code === "ENOENT" ? null : er) else if (stats.isDirectory()) rmdir(p, options, er, cb) else options.unlink(p, cb) }) }) } const fixWinEPERMSync = (p, options, er) => { assert(p) assert(options) try { options.chmodSync(p, 0o666) } catch (er2) { if (er2.code === "ENOENT") return else throw er } let stats try { stats = options.statSync(p) } catch (er3) { if (er3.code === "ENOENT") return else throw er } if (stats.isDirectory()) rmdirSync(p, options, er) else options.unlinkSync(p) } const rmdir = (p, options, originalEr, cb) => { assert(p) assert(options) assert(typeof cb === 'function') // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) // if we guessed wrong, and it's not a directory, then // raise the original error. options.rmdir(p, er => { if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) rmkids(p, options, cb) else if (er && er.code === "ENOTDIR") cb(originalEr) else cb(er) }) } const rmkids = (p, options, cb) => { assert(p) assert(options) assert(typeof cb === 'function') options.readdir(p, (er, files) => { if (er) return cb(er) let n = files.length if (n === 0) return options.rmdir(p, cb) let errState files.forEach(f => { rimraf(path.join(p, f), options, er => { if (errState) return if (er) return cb(errState = er) if (--n === 0) options.rmdir(p, cb) }) }) }) } // this looks simpler, and is strictly *faster*, but will // tie up the JavaScript thread and fail on excessively // deep directory trees. const rimrafSync = (p, options) => { options = options || {} defaults(options) assert(p, 'rimraf: missing path') assert.equal(typeof p, 'string', 'rimraf: path should be a string') assert(options, 'rimraf: missing options') assert.equal(typeof options, 'object', 'rimraf: options should be object') let results if (options.disableGlob || !glob.hasMagic(p)) { results = [p] } else { try { options.lstatSync(p) results = [p] } catch (er) { results = glob.sync(p, options.glob) } } if (!results.length) return for (let i = 0; i < results.length; i++) { const p = results[i] let st try { st = options.lstatSync(p) } catch (er) { if (er.code === "ENOENT") return // Windows can EPERM on stat. Life is suffering. if (er.code === "EPERM" && isWindows) fixWinEPERMSync(p, options, er) } try { // sunos lets the root user unlink directories, which is... weird. if (st && st.isDirectory()) rmdirSync(p, options, null) else options.unlinkSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "EPERM") return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) if (er.code !== "EISDIR") throw er rmdirSync(p, options, er) } } } const rmdirSync = (p, options, originalEr) => { assert(p) assert(options) try { options.rmdirSync(p) } catch (er) { if (er.code === "ENOENT") return if (er.code === "ENOTDIR") throw originalEr if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") rmkidsSync(p, options) } } const rmkidsSync = (p, options) => { assert(p) assert(options) options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) // We only end up here once we got ENOTEMPTY at least once, and // at this point, we are guaranteed to have removed all the kids. // So, we know that it won't be ENOENT or ENOTDIR or anything else. // try really hard to delete stuff on windows, because it has a // PROFOUNDLY annoying habit of not closing handles promptly when // files are deleted, resulting in spurious ENOTEMPTY errors. const retries = isWindows ? 100 : 1 let i = 0 do { let threw = true try { const ret = options.rmdirSync(p, options) threw = false return ret } finally { if (++i < retries && threw) continue } } while (true) } module.exports = rimraf rimraf.sync = rimrafSync /***/ }), /***/ 7187: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(3057); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util.toSetString(aStr); return has.call(this._set, sStr); } }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.I = ArraySet; /***/ }), /***/ 3422: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var base64 = __webpack_require__(35); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; /***/ }), /***/ 35: /***/ ((__unused_webpack_module, exports) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ exports.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; /***/ }), /***/ 9690: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = __webpack_require__(3057); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.H = MappingList; /***/ }), /***/ 5997: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var base64VLQ = __webpack_require__(3422); var util = __webpack_require__(3057); var ArraySet = __webpack_require__(7187)/* .ArraySet */ .I; var MappingList = __webpack_require__(9690)/* .MappingList */ .H; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { // When aOriginal is truthy but has empty values for .line and .column, // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { throw new Error( 'original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.' ); } if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = '' if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ','; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; /***/ }), /***/ 3057: /***/ ((__unused_webpack_module, exports) => { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; var MAX_CACHED_INPUTS = 32; /** * Takes some function `f(input) -> result` and returns a memoized version of * `f`. * * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The * memoization is a dumb-simple, linear least-recently-used cache. */ function lruMemoize(f) { var cache = []; return function(input) { for (var i = 0; i < cache.length; i++) { if (cache[i].input === input) { var temp = cache[0]; cache[0] = cache[i]; cache[i] = temp; return cache[0].result; } } var result = f(input); cache.unshift({ input, result, }); if (cache.length > MAX_CACHED_INPUTS) { cache.pop(); } return result; }; } /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ var normalize = lruMemoize(function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); // Split the path into parts between `/` characters. This is much faster than // using `.split(/\/+/g)`. var parts = []; var start = 0; var i = 0; while (true) { start = i; i = path.indexOf("/", start); if (i === -1) { parts.push(path.slice(start)); break; } else { parts.push(path.slice(start, i)); while (i < path.length && path[i] === "/") { i++; } } } for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; }); exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || urlRegexp.test(aPath); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { var cmp cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; // aStr2 !== null } if (aStr2 === null) { return -1; // aStr1 !== null } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; /** * Strip any JSON XSSI avoidance prefix from the string (as documented * in the source maps specification), and then parse the string as * JSON. */ function parseSourceMapInput(str) { return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); } exports.parseSourceMapInput = parseSourceMapInput; /** * Compute the URL of a source given the the source root, the source's * URL, and the source map's URL. */ function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ''; if (sourceRoot) { // This follows what Chrome does. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { sourceRoot += '/'; } // The spec says: // Line 4: An optional source root, useful for relocating source // files on a server or removing repeated values in the // “sources” entry. This value is prepended to the individual // entries in the “source” field. sourceURL = sourceRoot + sourceURL; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter. This mode is still somewhat supported, which is why // this code block is conditional. However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec. This block is basically the equivalent of: // new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: // If the sources are not absolute URLs after prepending of the // “sourceRoot”, the sources are resolved relative to the // SourceMap (like resolving script src in a html document). if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { // Strip the last path component, but keep the "/". var index = parsed.path.lastIndexOf('/'); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; /***/ }), /***/ 6382: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /*! * Tmp * * Copyright (c) 2011-2017 KARASZI Istvan * * MIT Licensed */ /* * Module dependencies. */ const fs = __webpack_require__(5747); const os = __webpack_require__(2087); const path = __webpack_require__(5622); const crypto = __webpack_require__(6417); const _c = { fs: fs.constants, os: os.constants }; const rimraf = __webpack_require__(2780); /* * The working inner variables. */ const // the random characters to choose from RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', TEMPLATE_PATTERN = /XXXXXX/, DEFAULT_TRIES = 3, CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR), // constants are off on the windows platform and will not match the actual errno codes IS_WIN32 = os.platform() === 'win32', EBADF = _c.EBADF || _c.os.errno.EBADF, ENOENT = _c.ENOENT || _c.os.errno.ENOENT, DIR_MODE = 0o700 /* 448 */, FILE_MODE = 0o600 /* 384 */, EXIT = 'exit', // this will hold the objects need to be removed on exit _removeObjects = [], // API change in fs.rmdirSync leads to error when passing in a second parameter, e.g. the callback FN_RMDIR_SYNC = fs.rmdirSync.bind(fs), FN_RIMRAF_SYNC = rimraf.sync; let _gracefulCleanup = false; /** * Gets a temporary file name. * * @param {(Options|tmpNameCallback)} options options or callback * @param {?tmpNameCallback} callback the callback function */ function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; try { _assertAndSanitizeOptions(opts); } catch (err) { return cb(err); } let tries = opts.tries; (function _getUniqueName() { try { const name = _generateTmpName(opts); // check whether the path exists then retry if needed fs.stat(name, function (err) { /* istanbul ignore else */ if (!err) { /* istanbul ignore else */ if (tries-- > 0) return _getUniqueName(); return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name)); } cb(null, name); }); } catch (err) { cb(err); } }()); } /** * Synchronous version of tmpName. * * @param {Object} options * @returns {string} the generated random name * @throws {Error} if the options are invalid or could not generate a filename */ function tmpNameSync(options) { const args = _parseArguments(options), opts = args[0]; _assertAndSanitizeOptions(opts); let tries = opts.tries; do { const name = _generateTmpName(opts); try { fs.statSync(name); } catch (e) { return name; } } while (tries-- > 0); throw new Error('Could not get a unique tmp filename, max tries reached'); } /** * Creates and opens a temporary file. * * @param {(Options|null|undefined|fileCallback)} options the config options or the callback function or null or undefined * @param {?fileCallback} callback */ function file(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create and open the file fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) { /* istanbu ignore else */ if (err) return cb(err); if (opts.discardDescriptor) { return fs.close(fd, function _discardCallback(possibleErr) { // the chance of getting an error on close here is rather low and might occur in the most edgiest cases only return cb(possibleErr, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { // detachDescriptor passes the descriptor whereas discardDescriptor closes it, either way, we no longer care // about the descriptor const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; cb(null, name, fd, _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, false)); } }); }); } /** * Synchronous version of file. * * @param {Options} options * @returns {FileSyncObject} object consists of name, fd and removeCallback * @throws {Error} if cannot create a file */ function fileSync(options) { const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); /* istanbul ignore else */ if (opts.discardDescriptor) { fs.closeSync(fd); fd = undefined; } return { name: name, fd: fd, removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts, true) }; } /** * Creates a temporary directory. * * @param {(Options|dirCallback)} options the options or the callback function * @param {?dirCallback} callback */ function dir(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; // gets a temporary filename tmpName(opts, function _tmpNameCreated(err, name) { /* istanbul ignore else */ if (err) return cb(err); // create the directory fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) { /* istanbul ignore else */ if (err) return cb(err); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); }); } /** * Synchronous version of dir. * * @param {Options} options * @returns {DirSyncObject} object consists of name and removeCallback * @throws {Error} if it cannot create a directory */ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); fs.mkdirSync(name, opts.mode || DIR_MODE); return { name: name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) }; } /** * Removes files asynchronously. * * @param {Object} fdPath * @param {Function} next * @private */ function _removeFileAsync(fdPath, next) { const _handler = function (err) { if (err && !_isENOENT(err)) { // reraise any unanticipated error return next(err); } next(); }; if (0 <= fdPath[0]) fs.close(fdPath[0], function () { fs.unlink(fdPath[1], _handler); }); else fs.unlink(fdPath[1], _handler); } /** * Removes files synchronously. * * @param {Object} fdPath * @private */ function _removeFileSync(fdPath) { let rethrownException = null; try { if (0 <= fdPath[0]) fs.closeSync(fdPath[0]); } catch (e) { // reraise any unanticipated error if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { fs.unlinkSync(fdPath[1]); } catch (e) { // reraise any unanticipated error if (!_isENOENT(e)) rethrownException = e; } } if (rethrownException !== null) { throw rethrownException; } } /** * Prepares the callback for removal of the temporary file. * * Returns either a sync callback or a async callback depending on whether * fileSync or file was called, which is expressed by the sync parameter. * * @param {string} name the path of the file * @param {number} fd file descriptor * @param {Object} opts * @param {boolean} sync * @returns {fileCallback | fileCallbackSync} * @private */ function _prepareTmpFileRemoveCallback(name, fd, opts, sync) { const removeCallbackSync = _prepareRemoveCallback(_removeFileSync, [fd, name], sync); const removeCallback = _prepareRemoveCallback(_removeFileAsync, [fd, name], sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Prepares the callback for removal of the temporary directory. * * Returns either a sync callback or a async callback depending on whether * tmpFileSync or tmpFile was called, which is expressed by the sync parameter. * * @param {string} name * @param {Object} opts * @param {boolean} sync * @returns {Function} the callback * @private */ function _prepareTmpDirRemoveCallback(name, opts, sync) { const removeFunction = opts.unsafeCleanup ? rimraf : fs.rmdir.bind(fs); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); if (!opts.keep) _removeObjects.unshift(removeCallbackSync); return sync ? removeCallbackSync : removeCallback; } /** * Creates a guarded function wrapping the removeFunction call. * * The cleanup callback is save to be called multiple times. * Subsequent invocations will be ignored. * * @param {Function} removeFunction * @param {string} fileOrDirName * @param {boolean} sync * @param {cleanupCallbackSync?} cleanupCallbackSync * @returns {cleanupCallback | cleanupCallbackSync} * @private */ function _prepareRemoveCallback(removeFunction, fileOrDirName, sync, cleanupCallbackSync) { let called = false; // if sync is true, the next parameter will be ignored return function _cleanupCallback(next) { /* istanbul ignore else */ if (!called) { // remove cleanupCallback from cache const toRemove = cleanupCallbackSync || _cleanupCallback; const index = _removeObjects.indexOf(toRemove); /* istanbul ignore else */ if (index >= 0) _removeObjects.splice(index, 1); called = true; if (sync || removeFunction === FN_RMDIR_SYNC || removeFunction === FN_RIMRAF_SYNC) { return removeFunction(fileOrDirName); } else { return removeFunction(fileOrDirName, next || function() {}); } } }; } /** * The garbage collector. * * @private */ function _garbageCollector() { /* istanbul ignore else */ if (!_gracefulCleanup) return; // the function being called removes itself from _removeObjects, // loop until _removeObjects is empty while (_removeObjects.length) { try { _removeObjects[0](); } catch (e) { // already removed? } } } /** * Random name generator based on crypto. * Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript * * @param {number} howMany * @returns {string} the generated random name * @private */ function _randomChars(howMany) { let value = [], rnd = null; // make sure that we do not fail because we ran out of entropy try { rnd = crypto.randomBytes(howMany); } catch (e) { rnd = crypto.pseudoRandomBytes(howMany); } for (var i = 0; i < howMany; i++) { value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]); } return value.join(''); } /** * Helper which determines whether a string s is blank, that is undefined, or empty or null. * * @private * @param {string} s * @returns {Boolean} true whether the string s is blank, false otherwise */ function _isBlank(s) { return s === null || _isUndefined(s) || !s.trim(); } /** * Checks whether the `obj` parameter is defined or not. * * @param {Object} obj * @returns {boolean} true if the object is undefined * @private */ function _isUndefined(obj) { return typeof obj === 'undefined'; } /** * Parses the function arguments. * * This function helps to have optional arguments. * * @param {(Options|null|undefined|Function)} options * @param {?Function} callback * @returns {Array} parsed arguments * @private */ function _parseArguments(options, callback) { /* istanbul ignore else */ if (typeof options === 'function') { return [{}, options]; } /* istanbul ignore else */ if (_isUndefined(options)) { return [{}, callback]; } // copy options so we do not leak the changes we make internally const actualOptions = {}; for (const key of Object.getOwnPropertyNames(options)) { actualOptions[key] = options[key]; } return [actualOptions, callback]; } /** * Generates a new temporary name. * * @param {Object} opts * @returns {string} the new random name according to opts * @private */ function _generateTmpName(opts) { const tmpDir = opts.tmpdir; /* istanbul ignore else */ if (!_isUndefined(opts.name)) return path.join(tmpDir, opts.dir, opts.name); /* istanbul ignore else */ if (!_isUndefined(opts.template)) return path.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); // prefix and postfix const name = [ opts.prefix ? opts.prefix : 'tmp', '-', process.pid, '-', _randomChars(12), opts.postfix ? '-' + opts.postfix : '' ].join(''); return path.join(tmpDir, opts.dir, name); } /** * Asserts whether the specified options are valid, also sanitizes options and provides sane defaults for missing * options. * * @param {Options} options * @private */ function _assertAndSanitizeOptions(options) { options.tmpdir = _getTmpDir(options); const tmpDir = options.tmpdir; /* istanbul ignore else */ if (!_isUndefined(options.name)) _assertIsRelative(options.name, 'name', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.dir)) _assertIsRelative(options.dir, 'dir', tmpDir); /* istanbul ignore else */ if (!_isUndefined(options.template)) { _assertIsRelative(options.template, 'template', tmpDir); if (!options.template.match(TEMPLATE_PATTERN)) throw new Error(`Invalid template, found "${options.template}".`); } /* istanbul ignore else */ if (!_isUndefined(options.tries) && isNaN(options.tries) || options.tries < 0) throw new Error(`Invalid tries, found "${options.tries}".`); // if a name was specified we will try once options.tries = _isUndefined(options.name) ? options.tries || DEFAULT_TRIES : 1; options.keep = !!options.keep; options.detachDescriptor = !!options.detachDescriptor; options.discardDescriptor = !!options.discardDescriptor; options.unsafeCleanup = !!options.unsafeCleanup; // sanitize dir, also keep (multiple) blanks if the user, purportedly sane, requests us to options.dir = _isUndefined(options.dir) ? '' : path.relative(tmpDir, _resolvePath(options.dir, tmpDir)); options.template = _isUndefined(options.template) ? undefined : path.relative(tmpDir, _resolvePath(options.template, tmpDir)); // sanitize further if template is relative to options.dir options.template = _isBlank(options.template) ? undefined : path.relative(options.dir, options.template); // for completeness' sake only, also keep (multiple) blanks if the user, purportedly sane, requests us to options.name = _isUndefined(options.name) ? undefined : _sanitizeName(options.name); options.prefix = _isUndefined(options.prefix) ? '' : options.prefix; options.postfix = _isUndefined(options.postfix) ? '' : options.postfix; } /** * Resolve the specified path name in respect to tmpDir. * * The specified name might include relative path components, e.g. ../ * so we need to resolve in order to be sure that is is located inside tmpDir * * @param name * @param tmpDir * @returns {string} * @private */ function _resolvePath(name, tmpDir) { const sanitizedName = _sanitizeName(name); if (sanitizedName.startsWith(tmpDir)) { return path.resolve(sanitizedName); } else { return path.resolve(path.join(tmpDir, sanitizedName)); } } /** * Sanitize the specified path name by removing all quote characters. * * @param name * @returns {string} * @private */ function _sanitizeName(name) { if (_isBlank(name)) { return name; } return name.replace(/["']/g, ''); } /** * Asserts whether specified name is relative to the specified tmpDir. * * @param {string} name * @param {string} option * @param {string} tmpDir * @throws {Error} * @private */ function _assertIsRelative(name, option, tmpDir) { if (option === 'name') { // assert that name is not absolute and does not contain a path if (path.isAbsolute(name)) throw new Error(`${option} option must not contain an absolute path, found "${name}".`); // must not fail on valid . or .. or similar such constructs let basename = path.basename(name); if (basename === '..' || basename === '.' || basename !== name) throw new Error(`${option} option must not contain a path, found "${name}".`); } else { // if (option === 'dir' || option === 'template') { // assert that dir or template are relative to tmpDir if (path.isAbsolute(name) && !name.startsWith(tmpDir)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${name}".`); } let resolvedPath = _resolvePath(name, tmpDir); if (!resolvedPath.startsWith(tmpDir)) throw new Error(`${option} option must be relative to "${tmpDir}", found "${resolvedPath}".`); } } /** * Helper for testing against EBADF to compensate changes made to Node 7.x under Windows. * * @private */ function _isEBADF(error) { return _isExpectedError(error, -EBADF, 'EBADF'); } /** * Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows. * * @private */ function _isENOENT(error) { return _isExpectedError(error, -ENOENT, 'ENOENT'); } /** * Helper to determine whether the expected error code matches the actual code and errno, * which will differ between the supported node versions. * * - Node >= 7.0: * error.code {string} * error.errno {number} any numerical value will be negated * * CAVEAT * * On windows, the errno for EBADF is -4083 but os.constants.errno.EBADF is different and we must assume that ENOENT * is no different here. * * @param {SystemError} error * @param {number} errno * @param {string} code * @private */ function _isExpectedError(error, errno, code) { return IS_WIN32 ? error.code === code : error.code === code && error.errno === errno; } /** * Sets the graceful cleanup. * * If graceful cleanup is set, tmp will remove all controlled temporary objects on process exit, otherwise the * temporary objects will remain in place, waiting to be cleaned up on system restart or otherwise scheduled temporary * object removals. */ function setGracefulCleanup() { _gracefulCleanup = true; } /** * Returns the currently configured tmp dir from os.tmpdir(). * * @private * @param {?Options} options * @returns {string} the currently configured tmp dir */ function _getTmpDir(options) { return path.resolve(_sanitizeName(options && options.tmpdir || os.tmpdir())); } // Install process exit listener process.addListener(EXIT, _garbageCollector); /** * Configuration options. * * @typedef {Object} Options * @property {?boolean} keep the temporary object (file or dir) will not be garbage collected * @property {?number} tries the number of tries before give up the name generation * @property (?int) mode the access mode, defaults are 0o700 for directories and 0o600 for files * @property {?string} template the "mkstemp" like filename template * @property {?string} name fixed name relative to tmpdir or the specified dir option * @property {?string} dir tmp directory relative to the root tmp directory in use * @property {?string} prefix prefix for the generated name * @property {?string} postfix postfix for the generated name * @property {?string} tmpdir the root tmp directory which overrides the os tmpdir * @property {?boolean} unsafeCleanup recursively removes the created temporary directory, even when it's not empty * @property {?boolean} detachDescriptor detaches the file descriptor, caller is responsible for closing the file, tmp will no longer try closing the file during garbage collection * @property {?boolean} discardDescriptor discards the file descriptor (closes file, fd is -1), tmp will no longer try closing the file during garbage collection */ /** * @typedef {Object} FileSyncObject * @property {string} name the name of the file * @property {string} fd the file descriptor or -1 if the fd has been discarded * @property {fileCallback} removeCallback the callback function to remove the file */ /** * @typedef {Object} DirSyncObject * @property {string} name the name of the directory * @property {fileCallback} removeCallback the callback function to remove the directory */ /** * @callback tmpNameCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name */ /** * @callback fileCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback fileCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {number} fd the file descriptor or -1 if the fd had been discarded * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * @callback dirCallback * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallback} fn the cleanup callback function */ /** * @callback dirCallbackSync * @param {?Error} err the error object if anything goes wrong * @param {string} name the temporary file name * @param {cleanupCallbackSync} fn the cleanup callback function */ /** * Removes the temporary created file or directory. * * @callback cleanupCallback * @param {simpleCallback} [next] function to call whenever the tmp object needs to be removed */ /** * Removes the temporary created file or directory. * * @callback cleanupCallbackSync */ /** * Callback function for function composition. * @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57} * * @callback simpleCallback */ // exporting all the needed methods // evaluate _getTmpDir() lazily, mainly for simplifying testing but it also will // allow users to reconfigure the temporary directory Object.defineProperty(module.exports, "tmpdir", ({ enumerable: true, configurable: false, get: function () { return _getTmpDir(); } })); module.exports.dir = dir; module.exports.dirSync = dirSync; module.exports.file = file; module.exports.fileSync = fileSync; module.exports.tmpName = tmpName; module.exports.tmpNameSync = tmpNameSync; module.exports.setGracefulCleanup = setGracefulCleanup; /***/ }), /***/ 9878: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var punycode = __webpack_require__(4213); var mappingTable = __webpack_require__(2069); var PROCESSING_OPTIONS = { TRANSITIONAL: 0, NONTRANSITIONAL: 1 }; function normalize(str) { // fix bug in v8 return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); } function findStatus(val) { var start = 0; var end = mappingTable.length - 1; while (start <= end) { var mid = Math.floor((start + end) / 2); var target = mappingTable[mid]; if (target[0][0] <= val && target[0][1] >= val) { return target; } else if (target[0][0] > val) { end = mid - 1; } else { start = mid + 1; } } return null; } var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; function countSymbols(string) { return string // replace every surrogate pair with a BMP symbol .replace(regexAstralSymbols, '_') // then get the length .length; } function mapChars(domain_name, useSTD3, processing_option) { var hasError = false; var processed = ""; var len = countSymbols(domain_name); for (var i = 0; i < len; ++i) { var codePoint = domain_name.codePointAt(i); var status = findStatus(codePoint); switch (status[1]) { case "disallowed": hasError = true; processed += String.fromCodePoint(codePoint); break; case "ignored": break; case "mapped": processed += String.fromCodePoint.apply(String, status[2]); break; case "deviation": if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { processed += String.fromCodePoint.apply(String, status[2]); } else { processed += String.fromCodePoint(codePoint); } break; case "valid": processed += String.fromCodePoint(codePoint); break; case "disallowed_STD3_mapped": if (useSTD3) { hasError = true; processed += String.fromCodePoint(codePoint); } else { processed += String.fromCodePoint.apply(String, status[2]); } break; case "disallowed_STD3_valid": if (useSTD3) { hasError = true; } processed += String.fromCodePoint(codePoint); break; } } return { string: processed, error: hasError }; } var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; function validateLabel(label, processing_option) { if (label.substr(0, 4) === "xn--") { label = punycode.toUnicode(label); processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; } var error = false; if (normalize(label) !== label || (label[3] === "-" && label[4] === "-") || label[0] === "-" || label[label.length - 1] === "-" || label.indexOf(".") !== -1 || label.search(combiningMarksRegex) === 0) { error = true; } var len = countSymbols(label); for (var i = 0; i < len; ++i) { var status = findStatus(label.codePointAt(i)); if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && status[1] !== "valid" && status[1] !== "deviation")) { error = true; break; } } return { label: label, error: error }; } function processing(domain_name, useSTD3, processing_option) { var result = mapChars(domain_name, useSTD3, processing_option); result.string = normalize(result.string); var labels = result.string.split("."); for (var i = 0; i < labels.length; ++i) { try { var validation = validateLabel(labels[i]); labels[i] = validation.label; result.error = result.error || validation.error; } catch(e) { result.error = true; } } return { string: labels.join("."), error: result.error }; } module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { var result = processing(domain_name, useSTD3, processing_option); var labels = result.string.split("."); labels = labels.map(function(l) { try { return punycode.toASCII(l); } catch(e) { result.error = true; return l; } }); if (verifyDnsLength) { var total = labels.slice(0, labels.length - 1).join(".").length; if (total.length > 253 || total.length === 0) { result.error = true; } for (var i=0; i < labels.length; ++i) { if (labels.length > 63 || labels.length === 0) { result.error = true; break; } } } if (result.error) return null; return labels.join("."); }; module.exports.toUnicode = function(domain_name, useSTD3) { var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); return { domain: result.string, error: result.error }; }; module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; /***/ }), /***/ 9382: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(1418); /***/ }), /***/ 1418: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var net = __webpack_require__(1631); var tls = __webpack_require__(4016); var http = __webpack_require__(8605); var https = __webpack_require__(7211); var events = __webpack_require__(8614); var assert = __webpack_require__(2357); var util = __webpack_require__(1669); exports.httpOverHttp = httpOverHttp; exports.httpsOverHttp = httpsOverHttp; exports.httpOverHttps = httpOverHttps; exports.httpsOverHttps = httpsOverHttps; function httpOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; return agent; } function httpsOverHttp(options) { var agent = new TunnelingAgent(options); agent.request = http.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function httpOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; return agent; } function httpsOverHttps(options) { var agent = new TunnelingAgent(options); agent.request = https.request; agent.createSocket = createSecureSocket; agent.defaultPort = 443; return agent; } function TunnelingAgent(options) { var self = this; self.options = options || {}; self.proxyOptions = self.options.proxy || {}; self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; self.requests = []; self.sockets = []; self.on('free', function onFree(socket, host, port, localAddress) { var options = toOptions(host, port, localAddress); for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i]; if (pending.host === options.host && pending.port === options.port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1); pending.request.onSocket(socket); return; } } socket.destroy(); self.removeSocket(socket); }); } util.inherits(TunnelingAgent, events.EventEmitter); TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { var self = this; var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push(options); return; } // If we are under maxSockets create a new one. self.createSocket(options, function(socket) { socket.on('free', onFree); socket.on('close', onCloseOrRemove); socket.on('agentRemove', onCloseOrRemove); req.onSocket(socket); function onFree() { self.emit('free', socket, options); } function onCloseOrRemove(err) { self.removeSocket(socket); socket.removeListener('free', onFree); socket.removeListener('close', onCloseOrRemove); socket.removeListener('agentRemove', onCloseOrRemove); } }); }; TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this; var placeholder = {}; self.sockets.push(placeholder); var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT', path: options.host + ':' + options.port, agent: false, headers: { host: options.host + ':' + options.port } }); if (options.localAddress) { connectOptions.localAddress = options.localAddress; } if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers['Proxy-Authorization'] = 'Basic ' + new Buffer(connectOptions.proxyAuth).toString('base64'); } debug('making CONNECT request'); var connectReq = self.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; // for v0.6 connectReq.once('response', onResponse); // for v0.6 connectReq.once('upgrade', onUpgrade); // for v0.6 connectReq.once('connect', onConnect); // for v0.7 or later connectReq.once('error', onError); connectReq.end(); function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true; } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head); }); } function onConnect(res, socket, head) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { debug('tunneling socket could not be established, statusCode=%d', res.statusCode); socket.destroy(); var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } if (head.length > 0) { debug('got illegal response body from proxy'); socket.destroy(); var error = new Error('got illegal response body from proxy'); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); return; } debug('tunneling connection has established'); self.sockets[self.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack); var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message); error.code = 'ECONNRESET'; options.request.emit('error', error); self.removeSocket(placeholder); } }; TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) { return; } this.sockets.splice(pos, 1); var pending = this.requests.shift(); if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createSocket(pending, function(socket) { pending.request.onSocket(socket); }); } }; function createSecureSocket(options, cb) { var self = this; TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { var hostHeader = options.request.getHeader('host'); var tlsOptions = mergeOptions({}, self.options, { socket: socket, servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host }); // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, tlsOptions); self.sockets[self.sockets.indexOf(socket)] = secureSocket; cb(secureSocket); }); } function toOptions(host, port, localAddress) { if (typeof host === 'string') { // since v0.10 return { host: host, port: port, localAddress: localAddress }; } return host; // for v0.11 or later } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i]; if (typeof overrides === 'object') { var keys = Object.keys(overrides); for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j]; if (overrides[k] !== undefined) { target[k] = overrides[k]; } } } } return target; } var debug; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0]; } else { args.unshift('TUNNEL:'); } console.error.apply(console, args); } } else { debug = function() {}; } exports.debug = debug; // for test /***/ }), /***/ 6749: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const usm = __webpack_require__(7167); exports.implementation = class URLImpl { constructor(constructorArgs) { const url = constructorArgs[0]; const base = constructorArgs[1]; let parsedBase = null; if (base !== undefined) { parsedBase = usm.basicURLParse(base); if (parsedBase === "failure") { throw new TypeError("Invalid base URL"); } } const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); if (parsedURL === "failure") { throw new TypeError("Invalid URL"); } this._url = parsedURL; // TODO: query stuff } get href() { return usm.serializeURL(this._url); } set href(v) { const parsedURL = usm.basicURLParse(v); if (parsedURL === "failure") { throw new TypeError("Invalid URL"); } this._url = parsedURL; } get origin() { return usm.serializeURLOrigin(this._url); } get protocol() { return this._url.scheme + ":"; } set protocol(v) { usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); } get username() { return this._url.username; } set username(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setTheUsername(this._url, v); } get password() { return this._url.password; } set password(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } usm.setThePassword(this._url, v); } get host() { const url = this._url; if (url.host === null) { return ""; } if (url.port === null) { return usm.serializeHost(url.host); } return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); } set host(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); } get hostname() { if (this._url.host === null) { return ""; } return usm.serializeHost(this._url.host); } set hostname(v) { if (this._url.cannotBeABaseURL) { return; } usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); } get port() { if (this._url.port === null) { return ""; } return usm.serializeInteger(this._url.port); } set port(v) { if (usm.cannotHaveAUsernamePasswordPort(this._url)) { return; } if (v === "") { this._url.port = null; } else { usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); } } get pathname() { if (this._url.cannotBeABaseURL) { return this._url.path[0]; } if (this._url.path.length === 0) { return ""; } return "/" + this._url.path.join("/"); } set pathname(v) { if (this._url.cannotBeABaseURL) { return; } this._url.path = []; usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); } get search() { if (this._url.query === null || this._url.query === "") { return ""; } return "?" + this._url.query; } set search(v) { // TODO: query stuff const url = this._url; if (v === "") { url.query = null; return; } const input = v[0] === "?" ? v.substring(1) : v; url.query = ""; usm.basicURLParse(input, { url, stateOverride: "query" }); } get hash() { if (this._url.fragment === null || this._url.fragment === "") { return ""; } return "#" + this._url.fragment; } set hash(v) { if (v === "") { this._url.fragment = null; return; } const input = v[0] === "#" ? v.substring(1) : v; this._url.fragment = ""; usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); } toJSON() { return this.href; } }; /***/ }), /***/ 8607: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const conversions = __webpack_require__(4772); const utils = __webpack_require__(2596); const Impl = __webpack_require__(6749); const impl = utils.implSymbol; function URL(url) { if (!this || this[impl] || !(this instanceof URL)) { throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["USVString"](args[0]); if (args[1] !== undefined) { args[1] = conversions["USVString"](args[1]); } module.exports.setup(this, args); } URL.prototype.toJSON = function toJSON() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } const args = []; for (let i = 0; i < arguments.length && i < 0; ++i) { args[i] = arguments[i]; } return this[impl].toJSON.apply(this[impl], args); }; Object.defineProperty(URL.prototype, "href", { get() { return this[impl].href; }, set(V) { V = conversions["USVString"](V); this[impl].href = V; }, enumerable: true, configurable: true }); URL.prototype.toString = function () { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } return this.href; }; Object.defineProperty(URL.prototype, "origin", { get() { return this[impl].origin; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "protocol", { get() { return this[impl].protocol; }, set(V) { V = conversions["USVString"](V); this[impl].protocol = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "username", { get() { return this[impl].username; }, set(V) { V = conversions["USVString"](V); this[impl].username = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "password", { get() { return this[impl].password; }, set(V) { V = conversions["USVString"](V); this[impl].password = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "host", { get() { return this[impl].host; }, set(V) { V = conversions["USVString"](V); this[impl].host = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "hostname", { get() { return this[impl].hostname; }, set(V) { V = conversions["USVString"](V); this[impl].hostname = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "port", { get() { return this[impl].port; }, set(V) { V = conversions["USVString"](V); this[impl].port = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "pathname", { get() { return this[impl].pathname; }, set(V) { V = conversions["USVString"](V); this[impl].pathname = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "search", { get() { return this[impl].search; }, set(V) { V = conversions["USVString"](V); this[impl].search = V; }, enumerable: true, configurable: true }); Object.defineProperty(URL.prototype, "hash", { get() { return this[impl].hash; }, set(V) { V = conversions["USVString"](V); this[impl].hash = V; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(URL.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: URL, expose: { Window: { URL: URL }, Worker: { URL: URL } } }; /***/ }), /***/ 3932: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.URL = __webpack_require__(8607).interface; exports.serializeURL = __webpack_require__(7167).serializeURL; exports.serializeURLOrigin = __webpack_require__(7167).serializeURLOrigin; exports.basicURLParse = __webpack_require__(7167).basicURLParse; exports.setTheUsername = __webpack_require__(7167).setTheUsername; exports.setThePassword = __webpack_require__(7167).setThePassword; exports.serializeHost = __webpack_require__(7167).serializeHost; exports.serializeInteger = __webpack_require__(7167).serializeInteger; exports.parseURL = __webpack_require__(7167).parseURL; /***/ }), /***/ 7167: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const punycode = __webpack_require__(4213); const tr46 = __webpack_require__(9878); const specialSchemes = { ftp: 21, file: null, gopher: 70, http: 80, https: 443, ws: 80, wss: 443 }; const failure = Symbol("failure"); function countSymbols(str) { return punycode.ucs2.decode(str).length; } function at(input, idx) { const c = input[idx]; return isNaN(c) ? undefined : String.fromCodePoint(c); } function isASCIIDigit(c) { return c >= 0x30 && c <= 0x39; } function isASCIIAlpha(c) { return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); } function isASCIIAlphanumeric(c) { return isASCIIAlpha(c) || isASCIIDigit(c); } function isASCIIHex(c) { return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); } function isSingleDot(buffer) { return buffer === "." || buffer.toLowerCase() === "%2e"; } function isDoubleDot(buffer) { buffer = buffer.toLowerCase(); return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; } function isWindowsDriveLetterCodePoints(cp1, cp2) { return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); } function isWindowsDriveLetterString(string) { return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); } function isNormalizedWindowsDriveLetterString(string) { return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; } function containsForbiddenHostCodePoint(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; } function containsForbiddenHostCodePointExcludingPercent(string) { return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; } function isSpecialScheme(scheme) { return specialSchemes[scheme] !== undefined; } function isSpecial(url) { return isSpecialScheme(url.scheme); } function defaultPort(scheme) { return specialSchemes[scheme]; } function percentEncode(c) { let hex = c.toString(16).toUpperCase(); if (hex.length === 1) { hex = "0" + hex; } return "%" + hex; } function utf8PercentEncode(c) { const buf = new Buffer(c); let str = ""; for (let i = 0; i < buf.length; ++i) { str += percentEncode(buf[i]); } return str; } function utf8PercentDecode(str) { const input = new Buffer(str); const output = []; for (let i = 0; i < input.length; ++i) { if (input[i] !== 37) { output.push(input[i]); } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); i += 2; } else { output.push(input[i]); } } return new Buffer(output).toString(); } function isC0ControlPercentEncode(c) { return c <= 0x1F || c > 0x7E; } const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); function isPathPercentEncode(c) { return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); } const extraUserinfoPercentEncodeSet = new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); function isUserinfoPercentEncode(c) { return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); } function percentEncodeChar(c, encodeSetPredicate) { const cStr = String.fromCodePoint(c); if (encodeSetPredicate(c)) { return utf8PercentEncode(cStr); } return cStr; } function parseIPv4Number(input) { let R = 10; if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { input = input.substring(2); R = 16; } else if (input.length >= 2 && input.charAt(0) === "0") { input = input.substring(1); R = 8; } if (input === "") { return 0; } const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); if (regex.test(input)) { return failure; } return parseInt(input, R); } function parseIPv4(input) { const parts = input.split("."); if (parts[parts.length - 1] === "") { if (parts.length > 1) { parts.pop(); } } if (parts.length > 4) { return input; } const numbers = []; for (const part of parts) { if (part === "") { return input; } const n = parseIPv4Number(part); if (n === failure) { return input; } numbers.push(n); } for (let i = 0; i < numbers.length - 1; ++i) { if (numbers[i] > 255) { return failure; } } if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { return failure; } let ipv4 = numbers.pop(); let counter = 0; for (const n of numbers) { ipv4 += n * Math.pow(256, 3 - counter); ++counter; } return ipv4; } function serializeIPv4(address) { let output = ""; let n = address; for (let i = 1; i <= 4; ++i) { output = String(n % 256) + output; if (i !== 4) { output = "." + output; } n = Math.floor(n / 256); } return output; } function parseIPv6(input) { const address = [0, 0, 0, 0, 0, 0, 0, 0]; let pieceIndex = 0; let compress = null; let pointer = 0; input = punycode.ucs2.decode(input); if (input[pointer] === 58) { if (input[pointer + 1] !== 58) { return failure; } pointer += 2; ++pieceIndex; compress = pieceIndex; } while (pointer < input.length) { if (pieceIndex === 8) { return failure; } if (input[pointer] === 58) { if (compress !== null) { return failure; } ++pointer; ++pieceIndex; compress = pieceIndex; continue; } let value = 0; let length = 0; while (length < 4 && isASCIIHex(input[pointer])) { value = value * 0x10 + parseInt(at(input, pointer), 16); ++pointer; ++length; } if (input[pointer] === 46) { if (length === 0) { return failure; } pointer -= length; if (pieceIndex > 6) { return failure; } let numbersSeen = 0; while (input[pointer] !== undefined) { let ipv4Piece = null; if (numbersSeen > 0) { if (input[pointer] === 46 && numbersSeen < 4) { ++pointer; } else { return failure; } } if (!isASCIIDigit(input[pointer])) { return failure; } while (isASCIIDigit(input[pointer])) { const number = parseInt(at(input, pointer)); if (ipv4Piece === null) { ipv4Piece = number; } else if (ipv4Piece === 0) { return failure; } else { ipv4Piece = ipv4Piece * 10 + number; } if (ipv4Piece > 255) { return failure; } ++pointer; } address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; ++numbersSeen; if (numbersSeen === 2 || numbersSeen === 4) { ++pieceIndex; } } if (numbersSeen !== 4) { return failure; } break; } else if (input[pointer] === 58) { ++pointer; if (input[pointer] === undefined) { return failure; } } else if (input[pointer] !== undefined) { return failure; } address[pieceIndex] = value; ++pieceIndex; } if (compress !== null) { let swaps = pieceIndex - compress; pieceIndex = 7; while (pieceIndex !== 0 && swaps > 0) { const temp = address[compress + swaps - 1]; address[compress + swaps - 1] = address[pieceIndex]; address[pieceIndex] = temp; --pieceIndex; --swaps; } } else if (compress === null && pieceIndex !== 8) { return failure; } return address; } function serializeIPv6(address) { let output = ""; const seqResult = findLongestZeroSequence(address); const compress = seqResult.idx; let ignore0 = false; for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { if (ignore0 && address[pieceIndex] === 0) { continue; } else if (ignore0) { ignore0 = false; } if (compress === pieceIndex) { const separator = pieceIndex === 0 ? "::" : ":"; output += separator; ignore0 = true; continue; } output += address[pieceIndex].toString(16); if (pieceIndex !== 7) { output += ":"; } } return output; } function parseHost(input, isSpecialArg) { if (input[0] === "[") { if (input[input.length - 1] !== "]") { return failure; } return parseIPv6(input.substring(1, input.length - 1)); } if (!isSpecialArg) { return parseOpaqueHost(input); } const domain = utf8PercentDecode(input); const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); if (asciiDomain === null) { return failure; } if (containsForbiddenHostCodePoint(asciiDomain)) { return failure; } const ipv4Host = parseIPv4(asciiDomain); if (typeof ipv4Host === "number" || ipv4Host === failure) { return ipv4Host; } return asciiDomain; } function parseOpaqueHost(input) { if (containsForbiddenHostCodePointExcludingPercent(input)) { return failure; } let output = ""; const decoded = punycode.ucs2.decode(input); for (let i = 0; i < decoded.length; ++i) { output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); } return output; } function findLongestZeroSequence(arr) { let maxIdx = null; let maxLen = 1; // only find elements > 1 let currStart = null; let currLen = 0; for (let i = 0; i < arr.length; ++i) { if (arr[i] !== 0) { if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } currStart = null; currLen = 0; } else { if (currStart === null) { currStart = i; } ++currLen; } } // if trailing zeros if (currLen > maxLen) { maxIdx = currStart; maxLen = currLen; } return { idx: maxIdx, len: maxLen }; } function serializeHost(host) { if (typeof host === "number") { return serializeIPv4(host); } // IPv6 serializer if (host instanceof Array) { return "[" + serializeIPv6(host) + "]"; } return host; } function trimControlChars(url) { return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); } function trimTabAndNewline(url) { return url.replace(/\u0009|\u000A|\u000D/g, ""); } function shortenPath(url) { const path = url.path; if (path.length === 0) { return; } if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { return; } path.pop(); } function includesCredentials(url) { return url.username !== "" || url.password !== ""; } function cannotHaveAUsernamePasswordPort(url) { return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; } function isNormalizedWindowsDriveLetter(string) { return /^[A-Za-z]:$/.test(string); } function URLStateMachine(input, base, encodingOverride, url, stateOverride) { this.pointer = 0; this.input = input; this.base = base || null; this.encodingOverride = encodingOverride || "utf-8"; this.stateOverride = stateOverride; this.url = url; this.failure = false; this.parseError = false; if (!this.url) { this.url = { scheme: "", username: "", password: "", host: null, port: null, path: [], query: null, fragment: null, cannotBeABaseURL: false }; const res = trimControlChars(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; } const res = trimTabAndNewline(this.input); if (res !== this.input) { this.parseError = true; } this.input = res; this.state = stateOverride || "scheme start"; this.buffer = ""; this.atFlag = false; this.arrFlag = false; this.passwordTokenSeenFlag = false; this.input = punycode.ucs2.decode(this.input); for (; this.pointer <= this.input.length; ++this.pointer) { const c = this.input[this.pointer]; const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); // exec state machine const ret = this["parse " + this.state](c, cStr); if (!ret) { break; // terminate algorithm } else if (ret === failure) { this.failure = true; break; } } } URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { if (isASCIIAlpha(c)) { this.buffer += cStr.toLowerCase(); this.state = "scheme"; } else if (!this.stateOverride) { this.state = "no scheme"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { this.buffer += cStr.toLowerCase(); } else if (c === 58) { if (this.stateOverride) { if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { return false; } if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { return false; } if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { return false; } if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { return false; } } this.url.scheme = this.buffer; this.buffer = ""; if (this.stateOverride) { return false; } if (this.url.scheme === "file") { if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { this.parseError = true; } this.state = "file"; } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { this.state = "special relative or authority"; } else if (isSpecial(this.url)) { this.state = "special authority slashes"; } else if (this.input[this.pointer + 1] === 47) { this.state = "path or authority"; ++this.pointer; } else { this.url.cannotBeABaseURL = true; this.url.path.push(""); this.state = "cannot-be-a-base-URL path"; } } else if (!this.stateOverride) { this.buffer = ""; this.state = "no scheme"; this.pointer = -1; } else { this.parseError = true; return failure; } return true; }; URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { return failure; } else if (this.base.cannotBeABaseURL && c === 35) { this.url.scheme = this.base.scheme; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.url.cannotBeABaseURL = true; this.state = "fragment"; } else if (this.base.scheme === "file") { this.state = "file"; --this.pointer; } else { this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "relative"; --this.pointer; } return true; }; URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { if (c === 47) { this.state = "authority"; } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative"] = function parseRelative(c) { this.url.scheme = this.base.scheme; if (isNaN(c)) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 47) { this.state = "relative slash"; } else if (c === 63) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else if (isSpecial(this.url) && c === 92) { this.parseError = true; this.state = "relative slash"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.url.path = this.base.path.slice(0, this.base.path.length - 1); this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { if (isSpecial(this.url) && (c === 47 || c === 92)) { if (c === 92) { this.parseError = true; } this.state = "special authority ignore slashes"; } else if (c === 47) { this.state = "authority"; } else { this.url.username = this.base.username; this.url.password = this.base.password; this.url.host = this.base.host; this.url.port = this.base.port; this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { if (c === 47 && this.input[this.pointer + 1] === 47) { this.state = "special authority ignore slashes"; ++this.pointer; } else { this.parseError = true; this.state = "special authority ignore slashes"; --this.pointer; } return true; }; URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { if (c !== 47 && c !== 92) { this.state = "authority"; --this.pointer; } else { this.parseError = true; } return true; }; URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { if (c === 64) { this.parseError = true; if (this.atFlag) { this.buffer = "%40" + this.buffer; } this.atFlag = true; // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars const len = countSymbols(this.buffer); for (let pointer = 0; pointer < len; ++pointer) { const codePoint = this.buffer.codePointAt(pointer); if (codePoint === 58 && !this.passwordTokenSeenFlag) { this.passwordTokenSeenFlag = true; continue; } const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); if (this.passwordTokenSeenFlag) { this.url.password += encodedCodePoints; } else { this.url.username += encodedCodePoints; } } this.buffer = ""; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { if (this.atFlag && this.buffer === "") { this.parseError = true; return failure; } this.pointer -= countSymbols(this.buffer) + 1; this.buffer = ""; this.state = "host"; } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse hostname"] = URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { if (this.stateOverride && this.url.scheme === "file") { --this.pointer; this.state = "file host"; } else if (c === 58 && !this.arrFlag) { if (this.buffer === "") { this.parseError = true; return failure; } const host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "port"; if (this.stateOverride === "hostname") { return false; } } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92)) { --this.pointer; if (isSpecial(this.url) && this.buffer === "") { this.parseError = true; return failure; } else if (this.stateOverride && this.buffer === "" && (includesCredentials(this.url) || this.url.port !== null)) { this.parseError = true; return false; } const host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } this.url.host = host; this.buffer = ""; this.state = "path start"; if (this.stateOverride) { return false; } } else { if (c === 91) { this.arrFlag = true; } else if (c === 93) { this.arrFlag = false; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { if (isASCIIDigit(c)) { this.buffer += cStr; } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || (isSpecial(this.url) && c === 92) || this.stateOverride) { if (this.buffer !== "") { const port = parseInt(this.buffer); if (port > Math.pow(2, 16) - 1) { this.parseError = true; return failure; } this.url.port = port === defaultPort(this.url.scheme) ? null : port; this.buffer = ""; } if (this.stateOverride) { return false; } this.state = "path start"; --this.pointer; } else { this.parseError = true; return failure; } return true; }; const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); URLStateMachine.prototype["parse file"] = function parseFile(c) { this.url.scheme = "file"; if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file slash"; } else if (this.base !== null && this.base.scheme === "file") { if (isNaN(c)) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; } else if (c === 63) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); this.url.query = this.base.query; this.url.fragment = ""; this.state = "fragment"; } else { if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { this.url.host = this.base.host; this.url.path = this.base.path.slice(); shortenPath(this.url); } else { this.parseError = true; } this.state = "path"; --this.pointer; } } else { this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { if (c === 47 || c === 92) { if (c === 92) { this.parseError = true; } this.state = "file host"; } else { if (this.base !== null && this.base.scheme === "file") { if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { this.url.path.push(this.base.path[0]); } else { this.url.host = this.base.host; } } this.state = "path"; --this.pointer; } return true; }; URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { --this.pointer; if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { this.parseError = true; this.state = "path"; } else if (this.buffer === "") { this.url.host = ""; if (this.stateOverride) { return false; } this.state = "path start"; } else { let host = parseHost(this.buffer, isSpecial(this.url)); if (host === failure) { return failure; } if (host === "localhost") { host = ""; } this.url.host = host; if (this.stateOverride) { return false; } this.buffer = ""; this.state = "path start"; } } else { this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { if (isSpecial(this.url)) { if (c === 92) { this.parseError = true; } this.state = "path"; if (c !== 47 && c !== 92) { --this.pointer; } } else if (!this.stateOverride && c === 63) { this.url.query = ""; this.state = "query"; } else if (!this.stateOverride && c === 35) { this.url.fragment = ""; this.state = "fragment"; } else if (c !== undefined) { this.state = "path"; if (c !== 47) { --this.pointer; } } return true; }; URLStateMachine.prototype["parse path"] = function parsePath(c) { if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || (!this.stateOverride && (c === 63 || c === 35))) { if (isSpecial(this.url) && c === 92) { this.parseError = true; } if (isDoubleDot(this.buffer)) { shortenPath(this.url); if (c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } } else if (isSingleDot(this.buffer) && c !== 47 && !(isSpecial(this.url) && c === 92)) { this.url.path.push(""); } else if (!isSingleDot(this.buffer)) { if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { if (this.url.host !== "" && this.url.host !== null) { this.parseError = true; this.url.host = ""; } this.buffer = this.buffer[0] + ":"; } this.url.path.push(this.buffer); } this.buffer = ""; if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { while (this.url.path.length > 1 && this.url.path[0] === "") { this.parseError = true; this.url.path.shift(); } } if (c === 63) { this.url.query = ""; this.state = "query"; } if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += percentEncodeChar(c, isPathPercentEncode); } return true; }; URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { if (c === 63) { this.url.query = ""; this.state = "query"; } else if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } else { // TODO: Add: not a URL code point if (!isNaN(c) && c !== 37) { this.parseError = true; } if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } if (!isNaN(c)) { this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); } } return true; }; URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { if (isNaN(c) || (!this.stateOverride && c === 35)) { if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { this.encodingOverride = "utf-8"; } const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead for (let i = 0; i < buffer.length; ++i) { if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || buffer[i] === 0x3C || buffer[i] === 0x3E) { this.url.query += percentEncode(buffer[i]); } else { this.url.query += String.fromCodePoint(buffer[i]); } } this.buffer = ""; if (c === 35) { this.url.fragment = ""; this.state = "fragment"; } } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.buffer += cStr; } return true; }; URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { if (isNaN(c)) { // do nothing } else if (c === 0x0) { this.parseError = true; } else { // TODO: If c is not a URL code point and not "%", parse error. if (c === 37 && (!isASCIIHex(this.input[this.pointer + 1]) || !isASCIIHex(this.input[this.pointer + 2]))) { this.parseError = true; } this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); } return true; }; function serializeURL(url, excludeFragment) { let output = url.scheme + ":"; if (url.host !== null) { output += "//"; if (url.username !== "" || url.password !== "") { output += url.username; if (url.password !== "") { output += ":" + url.password; } output += "@"; } output += serializeHost(url.host); if (url.port !== null) { output += ":" + url.port; } } else if (url.host === null && url.scheme === "file") { output += "//"; } if (url.cannotBeABaseURL) { output += url.path[0]; } else { for (const string of url.path) { output += "/" + string; } } if (url.query !== null) { output += "?" + url.query; } if (!excludeFragment && url.fragment !== null) { output += "#" + url.fragment; } return output; } function serializeOrigin(tuple) { let result = tuple.scheme + "://"; result += serializeHost(tuple.host); if (tuple.port !== null) { result += ":" + tuple.port; } return result; } module.exports.serializeURL = serializeURL; module.exports.serializeURLOrigin = function (url) { // https://url.spec.whatwg.org/#concept-url-origin switch (url.scheme) { case "blob": try { return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); } catch (e) { // serializing an opaque origin returns "null" return "null"; } case "ftp": case "gopher": case "http": case "https": case "ws": case "wss": return serializeOrigin({ scheme: url.scheme, host: url.host, port: url.port }); case "file": // spec says "exercise to the reader", chrome says "file://" return "file://"; default: // serializing an opaque origin returns "null" return "null"; } }; module.exports.basicURLParse = function (input, options) { if (options === undefined) { options = {}; } const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); if (usm.failure) { return "failure"; } return usm.url; }; module.exports.setTheUsername = function (url, username) { url.username = ""; const decoded = punycode.ucs2.decode(username); for (let i = 0; i < decoded.length; ++i) { url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.setThePassword = function (url, password) { url.password = ""; const decoded = punycode.ucs2.decode(password); for (let i = 0; i < decoded.length; ++i) { url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); } }; module.exports.serializeHost = serializeHost; module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; module.exports.serializeInteger = function (integer) { return String(integer); }; module.exports.parseURL = function (input, options) { if (options === undefined) { options = {}; } // We don't handle blobs, so this just delegates: return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); }; /***/ }), /***/ 2596: /***/ ((module) => { "use strict"; module.exports.mixin = function mixin(target, source) { const keys = Object.getOwnPropertyNames(source); for (let i = 0; i < keys.length; ++i) { Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); } }; module.exports.wrapperSymbol = Symbol("wrapper"); module.exports.implSymbol = Symbol("impl"); module.exports.wrapperForImpl = function (impl) { return impl[module.exports.wrapperSymbol]; }; module.exports.implForWrapper = function (wrapper) { return wrapper[module.exports.implSymbol]; }; /***/ }), /***/ 4772: /***/ ((module) => { "use strict"; var conversions = {}; module.exports = conversions; function sign(x) { return x < 0 ? -1 : 1; } function evenRound(x) { // Round x to the nearest integer, choosing the even integer if it lies halfway between two. if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) return Math.floor(x); } else { return Math.round(x); } } function createNumberConversion(bitLength, typeOpts) { if (!typeOpts.unsigned) { --bitLength; } const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); const upperBound = Math.pow(2, bitLength) - 1; const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); return function(V, opts) { if (!opts) opts = {}; let x = +V; if (opts.enforceRange) { if (!Number.isFinite(x)) { throw new TypeError("Argument is not a finite number"); } x = sign(x) * Math.floor(Math.abs(x)); if (x < lowerBound || x > upperBound) { throw new TypeError("Argument is not in byte range"); } return x; } if (!isNaN(x) && opts.clamp) { x = evenRound(x); if (x < lowerBound) x = lowerBound; if (x > upperBound) x = upperBound; return x; } if (!Number.isFinite(x) || x === 0) { return 0; } x = sign(x) * Math.floor(Math.abs(x)); x = x % moduloVal; if (!typeOpts.unsigned && x >= moduloBound) { return x - moduloVal; } else if (typeOpts.unsigned) { if (x < 0) { x += moduloVal; } else if (x === -0) { // don't return negative zero return 0; } } return x; } } conversions["void"] = function () { return undefined; }; conversions["boolean"] = function (val) { return !!val; }; conversions["byte"] = createNumberConversion(8, { unsigned: false }); conversions["octet"] = createNumberConversion(8, { unsigned: true }); conversions["short"] = createNumberConversion(16, { unsigned: false }); conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); conversions["long"] = createNumberConversion(32, { unsigned: false }); conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); conversions["double"] = function (V) { const x = +V; if (!Number.isFinite(x)) { throw new TypeError("Argument is not a finite floating-point value"); } return x; }; conversions["unrestricted double"] = function (V) { const x = +V; if (isNaN(x)) { throw new TypeError("Argument is NaN"); } return x; }; // not quite valid, but good enough for JS conversions["float"] = conversions["double"]; conversions["unrestricted float"] = conversions["unrestricted double"]; conversions["DOMString"] = function (V, opts) { if (!opts) opts = {}; if (opts.treatNullAsEmptyString && V === null) { return ""; } return String(V); }; conversions["ByteString"] = function (V, opts) { const x = String(V); let c = undefined; for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { if (c > 255) { throw new TypeError("Argument is not a valid bytestring"); } } return x; }; conversions["USVString"] = function (V) { const S = String(V); const n = S.length; const U = []; for (let i = 0; i < n; ++i) { const c = S.charCodeAt(i); if (c < 0xD800 || c > 0xDFFF) { U.push(String.fromCodePoint(c)); } else if (0xDC00 <= c && c <= 0xDFFF) { U.push(String.fromCodePoint(0xFFFD)); } else { if (i === n - 1) { U.push(String.fromCodePoint(0xFFFD)); } else { const d = S.charCodeAt(i + 1); if (0xDC00 <= d && d <= 0xDFFF) { const a = c & 0x3FF; const b = d & 0x3FF; U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); ++i; } else { U.push(String.fromCodePoint(0xFFFD)); } } } } return U.join(''); }; conversions["Date"] = function (V, opts) { if (!(V instanceof Date)) { throw new TypeError("Argument is not a Date object"); } if (isNaN(V)) { return undefined; } return V; }; conversions["RegExp"] = function (V, opts) { if (!(V instanceof RegExp)) { V = new RegExp(V); } return V; }; /***/ }), /***/ 4586: /***/ ((module) => { // Returns a wrapper function that returns a wrapped callback // The wrapper function should do some stuff, and return a // presumably different callback function. // This makes sure that own properties are retained, so that // decorations and such are not lost along the way. module.exports = wrappy function wrappy (fn, cb) { if (fn && cb) return wrappy(fn)(cb) if (typeof fn !== 'function') throw new TypeError('need wrapper function') Object.keys(fn).forEach(function (k) { wrapper[k] = fn[k] }) return wrapper function wrapper() { var args = new Array(arguments.length) for (var i = 0; i < args.length; i++) { args[i] = arguments[i] } var ret = fn.apply(this, args) var cb = args[args.length-1] if (typeof ret === 'function' && ret !== cb) { Object.keys(cb).forEach(function (k) { ret[k] = cb[k] }) } return ret } } /***/ }), /***/ 8847: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; exports.__esModule = true; exports.generateContributionSnake = void 0; var github_user_contribution_1 = __webpack_require__(3775); var userContributionToGrid_1 = __webpack_require__(5740); var getBestRoute_1 = __webpack_require__(2705); var snake_1 = __webpack_require__(7087); var getPathToPose_1 = __webpack_require__(6963); var generateContributionSnake = function (userName, outputs) { return __awaiter(void 0, void 0, void 0, function () { var cells, grid, snake, chain; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log("🎣 fetching github user contribution"); return [4 /*yield*/, (0, github_user_contribution_1.getGithubUserContribution)(userName)]; case 1: cells = _a.sent(); grid = (0, userContributionToGrid_1.userContributionToGrid)(cells); snake = snake_1.snake4; console.log("📡 computing best route"); chain = (0, getBestRoute_1.getBestRoute)(grid, snake); chain.push.apply(chain, (0, getPathToPose_1.getPathToPose)(chain.slice(-1)[0], snake)); return [2 /*return*/, Promise.all(outputs.map(function (out, i) { return __awaiter(void 0, void 0, void 0, function () { var format, drawOptions, animationOptions, _a, createSvg, createGif; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!out) return [2 /*return*/]; format = out.format, drawOptions = out.drawOptions, animationOptions = out.animationOptions; _a = format; switch (_a) { case "svg": return [3 /*break*/, 1]; case "gif": return [3 /*break*/, 3]; } return [3 /*break*/, 6]; case 1: console.log("\uD83D\uDD8C creating svg (outputs[".concat(i, "])")); return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(__webpack_require__(7415)); })]; case 2: createSvg = (_b.sent()).createSvg; return [2 /*return*/, createSvg(grid, cells, chain, drawOptions, animationOptions)]; case 3: console.log("\uD83D\uDCF9 creating gif (outputs[".concat(i, "])")); return [4 /*yield*/, Promise.resolve().then(function () { return __importStar(__webpack_require__(340)); })]; case 4: createGif = (_b.sent()).createGif; return [4 /*yield*/, createGif(grid, cells, chain, drawOptions, animationOptions)]; case 5: return [2 /*return*/, _b.sent()]; case 6: return [2 /*return*/]; } }); }); }))]; } }); }); }; exports.generateContributionSnake = generateContributionSnake; /***/ }), /***/ 2178: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; exports.__esModule = true; var fs = __importStar(__webpack_require__(5747)); var path = __importStar(__webpack_require__(5622)); var core = __importStar(__webpack_require__(7117)); var generateContributionSnake_1 = __webpack_require__(8847); var outputsOptions_1 = __webpack_require__(3379); (function () { return __awaiter(void 0, void 0, void 0, function () { var userName, outputs, results_1, e_1; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 2, , 3]); userName = core.getInput("github_user_name"); outputs = (0, outputsOptions_1.parseOutputsOption)((_a = core.getMultilineInput("outputs")) !== null && _a !== void 0 ? _a : [ core.getInput("gif_out_path"), core.getInput("svg_out_path"), ]); return [4 /*yield*/, (0, generateContributionSnake_1.generateContributionSnake)(userName, outputs)]; case 1: results_1 = _b.sent(); outputs.forEach(function (out, i) { var result = results_1[i]; if ((out === null || out === void 0 ? void 0 : out.filename) && result) { console.log("\uD83D\uDCBE writing to ".concat(out === null || out === void 0 ? void 0 : out.filename)); fs.mkdirSync(path.dirname(out === null || out === void 0 ? void 0 : out.filename), { recursive: true }); fs.writeFileSync(out === null || out === void 0 ? void 0 : out.filename, result); } }); return [3 /*break*/, 3]; case 2: e_1 = _b.sent(); core.setFailed("Action failed with \"".concat(e_1.message, "\"")); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); })(); /***/ }), /***/ 3379: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; exports.__esModule = true; exports.parseEntry = exports.parseOutputsOption = void 0; var palettes_1 = __webpack_require__(3848); var parseOutputsOption = function (lines) { return lines.map(exports.parseEntry); }; exports.parseOutputsOption = parseOutputsOption; var parseEntry = function (entry) { var m = entry.trim().match(/^(.+\.(svg|gif))(\?(.*)|\s*({.*}))?$/); if (!m) return null; var filename = m[1], format = m[2], _ = m[3], q1 = m[4], q2 = m[5]; var query = q1 !== null && q1 !== void 0 ? q1 : q2; var sp = new URLSearchParams(query || ""); try { var o = JSON.parse(query); if (Array.isArray(o.color_dots)) o.color_dots = o.color_dots.join(","); if (Array.isArray(o.dark_color_dots)) o.dark_color_dots = o.dark_color_dots.join(","); sp = new URLSearchParams(o); } catch (err) { if (!(err instanceof SyntaxError)) throw err; } var drawOptions = __assign({ sizeDotBorderRadius: 2, sizeCell: 16, sizeDot: 12 }, palettes_1.palettes["default"]); var animationOptions = { step: 1, frameDuration: 100 }; { var palette = palettes_1.palettes[sp.get("palette")]; if (palette) { Object.assign(drawOptions, palette); drawOptions.dark = palette.dark && __assign({}, palette.dark); } } if (sp.has("color_snake")) drawOptions.colorSnake = sp.get("color_snake"); if (sp.has("color_dots")) { var colors = sp.get("color_dots").split(/[,;]/); drawOptions.colorDots = colors; drawOptions.colorEmpty = colors[0]; drawOptions.dark = undefined; } if (sp.has("color_dot_border")) drawOptions.colorDotBorder = sp.get("color_dot_border"); if (sp.has("dark_color_dots")) { var colors = sp.get("dark_color_dots").split(/[,;]/); drawOptions.dark = __assign(__assign({}, drawOptions.dark), { colorDots: colors, colorEmpty: colors[0] }); } if (sp.has("dark_color_dot_border") && drawOptions.dark) drawOptions.dark.colorDotBorder = sp.get("color_dot_border"); if (sp.has("dark_color_snake") && drawOptions.dark) drawOptions.dark.colorSnake = sp.get("color_snake"); return { filename: filename, format: format, drawOptions: drawOptions, animationOptions: animationOptions }; }; exports.parseEntry = parseEntry; /***/ }), /***/ 3848: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; exports.__esModule = true; exports.palettes = void 0; exports.palettes = { "github-light": { colorDotBorder: "#1b1f230a", colorDots: ["#ebedf0", "#9be9a8", "#40c463", "#30a14e", "#216e39"], colorEmpty: "#ebedf0", colorSnake: "purple" }, "github-dark": { colorDotBorder: "#1b1f230a", colorEmpty: "#161b22", colorDots: ["#161b22", "#01311f", "#034525", "#0f6d31", "#00c647"], colorSnake: "purple" } }; // aliases exports.palettes.github = __assign(__assign({}, exports.palettes["github-light"]), { dark: __assign({}, exports.palettes["github-dark"]) }); exports.palettes.default = exports.palettes["github"]; /***/ }), /***/ 5740: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __spreadArray = (this && this.__spreadArray) || function (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)); }; exports.__esModule = true; exports.userContributionToGrid = void 0; var grid_1 = __webpack_require__(2881); var userContributionToGrid = function (cells) { var width = Math.max.apply(Math, __spreadArray([0], cells.map(function (c) { return c.x; }), false)) + 1; var height = Math.max.apply(Math, __spreadArray([0], cells.map(function (c) { return c.y; }), false)) + 1; var grid = (0, grid_1.createEmptyGrid)(width, height); for (var _i = 0, cells_1 = cells; _i < cells_1.length; _i++) { var c = cells_1[_i]; if (c.level > 0) (0, grid_1.setColor)(grid, c.x, c.y, c.level); else (0, grid_1.setColorEmpty)(grid, c.x, c.y); } return grid; }; exports.userContributionToGrid = userContributionToGrid; /***/ }), /***/ 1918: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.drawGrid = void 0; var grid_1 = __webpack_require__(2881); var pathRoundedRect_1 = __webpack_require__(2356); var drawGrid = function (ctx, grid, cells, o) { var _loop_1 = function (x) { var _loop_2 = function (y) { if (!cells || cells.some(function (c) { return c.x === x && c.y === y; })) { var c = (0, grid_1.getColor)(grid, x, y); // @ts-ignore var color = !c ? o.colorEmpty : o.colorDots[c]; ctx.save(); ctx.translate(x * o.sizeCell + (o.sizeCell - o.sizeDot) / 2, y * o.sizeCell + (o.sizeCell - o.sizeDot) / 2); ctx.fillStyle = color; ctx.strokeStyle = o.colorDotBorder; ctx.lineWidth = 1; ctx.beginPath(); (0, pathRoundedRect_1.pathRoundedRect)(ctx, o.sizeDot, o.sizeDot, o.sizeDotBorderRadius); ctx.fill(); ctx.stroke(); ctx.closePath(); ctx.restore(); } }; for (var y = grid.height; y--;) { _loop_2(y); } }; for (var x = grid.width; x--;) { _loop_1(x); } }; exports.drawGrid = drawGrid; /***/ }), /***/ 7972: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.drawSnakeLerp = exports.drawSnake = void 0; var pathRoundedRect_1 = __webpack_require__(2356); var snake_1 = __webpack_require__(9347); var drawSnake = function (ctx, snake, o) { var cells = (0, snake_1.snakeToCells)(snake); for (var i = 0; i < cells.length; i++) { var u = (i + 1) * 0.6; ctx.save(); ctx.fillStyle = o.colorSnake; ctx.translate(cells[i].x * o.sizeCell + u, cells[i].y * o.sizeCell + u); ctx.beginPath(); (0, pathRoundedRect_1.pathRoundedRect)(ctx, o.sizeCell - u * 2, o.sizeCell - u * 2, (o.sizeCell - u * 2) * 0.25); ctx.fill(); ctx.restore(); } }; exports.drawSnake = drawSnake; var lerp = function (k, a, b) { return (1 - k) * a + k * b; }; var clamp = function (x, a, b) { return Math.max(a, Math.min(b, x)); }; var drawSnakeLerp = function (ctx, snake0, snake1, k, o) { var m = 0.8; var n = snake0.length / 2; for (var i = 0; i < n; i++) { var u = (i + 1) * 0.6 * (o.sizeCell / 16); var a = (1 - m) * (i / Math.max(n - 1, 1)); var ki = clamp((k - a) / m, 0, 1); var x = lerp(ki, snake0[i * 2 + 0], snake1[i * 2 + 0]) - 2; var y = lerp(ki, snake0[i * 2 + 1], snake1[i * 2 + 1]) - 2; ctx.save(); ctx.fillStyle = o.colorSnake; ctx.translate(x * o.sizeCell + u, y * o.sizeCell + u); ctx.beginPath(); (0, pathRoundedRect_1.pathRoundedRect)(ctx, o.sizeCell - u * 2, o.sizeCell - u * 2, (o.sizeCell - u * 2) * 0.25); ctx.fill(); ctx.restore(); } }; exports.drawSnakeLerp = drawSnakeLerp; /***/ }), /***/ 3071: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.getCanvasWorldSize = exports.drawLerpWorld = exports.drawWorld = exports.drawStack = void 0; var drawGrid_1 = __webpack_require__(1918); var drawSnake_1 = __webpack_require__(7972); var drawStack = function (ctx, stack, max, width, o) { ctx.save(); var m = width / max; for (var i = 0; i < stack.length; i++) { // @ts-ignore ctx.fillStyle = o.colorDots[stack[i]]; ctx.fillRect(i * m, 0, m + width * 0.005, 10); } ctx.restore(); }; exports.drawStack = drawStack; var drawWorld = function (ctx, grid, cells, snake, stack, o) { ctx.save(); ctx.translate(1 * o.sizeCell, 2 * o.sizeCell); (0, drawGrid_1.drawGrid)(ctx, grid, cells, o); (0, drawSnake_1.drawSnake)(ctx, snake, o); ctx.restore(); ctx.save(); ctx.translate(o.sizeCell, (grid.height + 4) * o.sizeCell); var max = grid.data.reduce(function (sum, x) { return sum + +!!x; }, stack.length); (0, exports.drawStack)(ctx, stack, max, grid.width * o.sizeCell, o); ctx.restore(); // ctx.save(); // ctx.translate(o.sizeCell + 100, (grid.height + 4) * o.sizeCell + 100); // ctx.scale(0.6, 0.6); // drawCircleStack(ctx, stack, o); // ctx.restore(); }; exports.drawWorld = drawWorld; var drawLerpWorld = function (ctx, grid, cells, snake0, snake1, stack, k, o) { ctx.save(); ctx.translate(1 * o.sizeCell, 2 * o.sizeCell); (0, drawGrid_1.drawGrid)(ctx, grid, cells, o); (0, drawSnake_1.drawSnakeLerp)(ctx, snake0, snake1, k, o); ctx.translate(0, (grid.height + 2) * o.sizeCell); var max = grid.data.reduce(function (sum, x) { return sum + +!!x; }, stack.length); (0, exports.drawStack)(ctx, stack, max, grid.width * o.sizeCell, o); ctx.restore(); }; exports.drawLerpWorld = drawLerpWorld; var getCanvasWorldSize = function (grid, o) { var width = o.sizeCell * (grid.width + 2); var height = o.sizeCell * (grid.height + 4) + 30; return { width: width, height: height }; }; exports.getCanvasWorldSize = getCanvasWorldSize; /***/ }), /***/ 2356: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.__esModule = true; exports.pathRoundedRect = void 0; var pathRoundedRect = function (ctx, width, height, borderRadius) { ctx.moveTo(borderRadius, 0); ctx.arcTo(width, 0, width, height, borderRadius); ctx.arcTo(width, height, 0, height, borderRadius); ctx.arcTo(0, height, 0, 0, borderRadius); ctx.arcTo(0, 0, width, 0, borderRadius); }; exports.pathRoundedRect = pathRoundedRect; /***/ }), /***/ 340: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.createGif = void 0; var fs_1 = __importDefault(__webpack_require__(5747)); var path_1 = __importDefault(__webpack_require__(5622)); var child_process_1 = __webpack_require__(3129); var canvas_1 = __webpack_require__(5338); var grid_1 = __webpack_require__(2881); var drawWorld_1 = __webpack_require__(3071); var step_1 = __webpack_require__(1412); var tmp_1 = __importDefault(__webpack_require__(6382)); var gifsicle_1 = __importDefault(__webpack_require__(3819)); // @ts-ignore var gif_encoder_2_1 = __importDefault(__webpack_require__(3561)); var withTmpDir = function (handler) { return __awaiter(void 0, void 0, void 0, function () { var _a, dir, cleanUp; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = tmp_1["default"].dirSync({ unsafeCleanup: true }), dir = _a.name, cleanUp = _a.removeCallback; _b.label = 1; case 1: _b.trys.push([1, , 3, 4]); return [4 /*yield*/, handler(dir)]; case 2: return [2 /*return*/, _b.sent()]; case 3: cleanUp(); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; var createGif = function (grid0, cells, chain, drawOptions, animationOptions) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, withTmpDir(function (dir) { return __awaiter(void 0, void 0, void 0, function () { var _a, width, height, canvas, ctx, grid, stack, encoder, i, snake0, snake1, k, outFileName, optimizedFileName; return __generator(this, function (_b) { _a = (0, drawWorld_1.getCanvasWorldSize)(grid0, drawOptions), width = _a.width, height = _a.height; canvas = (0, canvas_1.createCanvas)(width, height); ctx = canvas.getContext("2d"); grid = (0, grid_1.copyGrid)(grid0); stack = []; encoder = new gif_encoder_2_1["default"](width, height, "neuquant", true); encoder.setRepeat(0); encoder.setDelay(animationOptions.frameDuration); encoder.start(); for (i = 0; i < chain.length; i += 1) { snake0 = chain[i]; snake1 = chain[Math.min(chain.length - 1, i + 1)]; (0, step_1.step)(grid, stack, snake0); for (k = 0; k < animationOptions.step; k++) { ctx.clearRect(0, 0, width, height); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, width, height); (0, drawWorld_1.drawLerpWorld)(ctx, grid, cells, snake0, snake1, stack, k / animationOptions.step, drawOptions); encoder.addFrame(ctx); } } outFileName = path_1["default"].join(dir, "out.gif"); optimizedFileName = path_1["default"].join(dir, "out.optimized.gif"); encoder.finish(); fs_1["default"].writeFileSync(outFileName, encoder.out.getData()); (0, child_process_1.execFileSync)(gifsicle_1["default"], [ // "--optimize=3", "--color-method=diversity", "--colors=18", outFileName, ["--output", optimizedFileName], ].flat()); return [2 /*return*/, fs_1["default"].readFileSync(optimizedFileName)]; }); }); })]; }); }); }; exports.createGif = createGif; /***/ }), /***/ 6038: /***/ (function(__unused_webpack_module, exports) { "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; exports.__esModule = true; exports.formatParams = void 0; var formatParams = function (options) { if (options === void 0) { options = {}; } var sp = new URLSearchParams(); var o = __assign({}, options); if ("year" in options) { o.from = "".concat(options.year, "-01-01"); o.to = "".concat(options.year, "-12-31"); } for (var _i = 0, _a = ["from", "to"]; _i < _a.length; _i++) { var s = _a[_i]; if (o[s]) { var value = o[s]; if (value >= formatDate(new Date())) throw new Error("Cannot get contribution for a date in the future.\nPlease limit your range to the current UTC day."); sp.set(s, value); } } return sp.toString(); }; exports.formatParams = formatParams; var formatDate = function (d) { var year = d.getUTCFullYear(); var month = d.getUTCMonth() + 1; var date = d.getUTCDate(); return [ year, month.toString().padStart(2, "0"), date.toString().padStart(2, "0"), ].join("-"); }; /***/ }), /***/ 3775: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.getGithubUserContribution = void 0; var node_fetch_1 = __importDefault(__webpack_require__(2197)); var formatParams_1 = __webpack_require__(6038); /** * get the contribution grid from a github user page * * use options.from=YYYY-MM-DD options.to=YYYY-MM-DD to get the contribution grid for a specific time range * or year=2019 as an alias for from=2019-01-01 to=2019-12-31 * * otherwise return use the time range from today minus one year to today ( as seen in github profile page ) * * @param userName github user name * @param options * * @example * getGithubUserContribution("platane", { from: "2019-01-01", to: "2019-12-31" }) * getGithubUserContribution("platane", { year: 2019 }) * */ var getGithubUserContribution = function (userName, options) { if (options === void 0) { options = {}; } return __awaiter(void 0, void 0, void 0, function () { var url, res, resText; return __generator(this, function (_a) { switch (_a.label) { case 0: url = "year" in options || "from" in options || "to" in options ? "https://github.com/users/".concat(userName, "/contributions?") + (0, formatParams_1.formatParams)(options) : "https://github.com/".concat(userName); return [4 /*yield*/, (0, node_fetch_1["default"])(url)]; case 1: res = _a.sent(); if (!res.ok) throw new Error(res.statusText); return [4 /*yield*/, res.text()]; case 2: resText = _a.sent(); return [2 /*return*/, parseUserPage(resText)]; } }); }); }; exports.getGithubUserContribution = getGithubUserContribution; var parseUserPage = function (content) { // take roughly the svg block var block = content .split("class=\"js-calendar-graph-svg\"")[1] .split("")[0]; var x = 0; var lastYAttribute = 0; var rects = Array.from(block.matchAll(/]*>/g)).map(function (_a) { var m = _a[0]; var date = m.match(/data-date="([^"]+)"/)[1]; var count = +m.match(/data-count="([^"]+)"/)[1]; var level = +m.match(/data-level="([^"]+)"/)[1]; var yAttribute = +m.match(/y="([^"]+)"/)[1]; if (lastYAttribute > yAttribute) x++; lastYAttribute = yAttribute; return { date: date, count: count, level: level, x: x, yAttribute: yAttribute }; }); var yAttributes = Array.from(new Set(rects.map(function (c) { return c.yAttribute; })).keys()).sort(); var cells = rects.map(function (_a) { var yAttribute = _a.yAttribute, c = __rest(_a, ["yAttribute"]); return (__assign({ y: yAttributes.indexOf(yAttribute) }, c)); }); return cells; }; /***/ }), /***/ 5256: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __spreadArray = (this && this.__spreadArray) || function (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)); }; exports.__esModule = true; exports.getTunnellablePoints = exports.clearCleanColoredLayer = void 0; var grid_1 = __webpack_require__(2881); var snake_1 = __webpack_require__(9347); var point_1 = __webpack_require__(3627); var getBestTunnel_1 = __webpack_require__(9726); var outside_1 = __webpack_require__(4076); var clearCleanColoredLayer = function (grid, outside, snake0, color) { var snakeN = (0, snake_1.getSnakeLength)(snake0); var points = (0, exports.getTunnellablePoints)(grid, outside, snakeN, color); var chain = [snake0]; while (points.length) { var path = getPathToNextPoint(grid, chain[0], color, points); path.pop(); for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { var snake = path_1[_i]; setEmptySafe(grid, (0, snake_1.getHeadX)(snake), (0, snake_1.getHeadY)(snake)); } chain.unshift.apply(chain, path); } (0, outside_1.fillOutside)(outside, grid); chain.pop(); return chain; }; exports.clearCleanColoredLayer = clearCleanColoredLayer; var unwrap = function (m) { return !m ? [] : __spreadArray([m.snake], unwrap(m.parent), true); }; var getPathToNextPoint = function (grid, snake0, color, points) { var closeList = []; var openList = [{ snake: snake0 }]; var _loop_1 = function () { var o = openList.shift(); var x = (0, snake_1.getHeadX)(o.snake); var y = (0, snake_1.getHeadY)(o.snake); var i = points.findIndex(function (p) { return p.x === x && p.y === y; }); if (i >= 0) { points.splice(i, 1); return { value: unwrap(o) }; } var _loop_2 = function (dx, dy) { if ((0, grid_1.isInsideLarge)(grid, 2, x + dx, y + dy) && !(0, snake_1.snakeWillSelfCollide)(o.snake, dx, dy) && getColorSafe(grid, x + dx, y + dy) <= color) { var snake_2 = (0, snake_1.nextSnake)(o.snake, dx, dy); if (!closeList.some(function (s0) { return (0, snake_1.snakeEquals)(s0, snake_2); })) { closeList.push(snake_2); openList.push({ snake: snake_2, parent: o }); } } }; for (var _i = 0, around4_1 = point_1.around4; _i < around4_1.length; _i++) { var _a = around4_1[_i], dx = _a.x, dy = _a.y; _loop_2(dx, dy); } }; while (openList.length) { var state_1 = _loop_1(); if (typeof state_1 === "object") return state_1.value; } }; /** * get all cells that are tunnellable */ var getTunnellablePoints = function (grid, outside, snakeN, color) { var points = []; var _loop_3 = function (x) { var _loop_4 = function (y) { var c = (0, grid_1.getColor)(grid, x, y); if (!(0, grid_1.isEmpty)(c) && c <= color && !points.some(function (p) { return p.x === x && p.y === y; })) { var tunnel = (0, getBestTunnel_1.getBestTunnel)(grid, outside, x, y, color, snakeN); if (tunnel) for (var _i = 0, tunnel_1 = tunnel; _i < tunnel_1.length; _i++) { var p = tunnel_1[_i]; if (!isEmptySafe(grid, p.x, p.y)) points.push(p); } } }; for (var y = grid.height; y--;) { _loop_4(y); } }; for (var x = grid.width; x--;) { _loop_3(x); } return points; }; exports.getTunnellablePoints = getTunnellablePoints; var getColorSafe = function (grid, x, y) { return (0, grid_1.isInside)(grid, x, y) ? (0, grid_1.getColor)(grid, x, y) : 0; }; var setEmptySafe = function (grid, x, y) { if ((0, grid_1.isInside)(grid, x, y)) (0, grid_1.setColorEmpty)(grid, x, y); }; var isEmptySafe = function (grid, x, y) { return !(0, grid_1.isInside)(grid, x, y) && (0, grid_1.isEmpty)((0, grid_1.getColor)(grid, x, y)); }; /***/ }), /***/ 3650: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.getPriority = exports.getTunnellablePoints = exports.clearResidualColoredLayer = void 0; var grid_1 = __webpack_require__(2881); var snake_1 = __webpack_require__(9347); var getBestTunnel_1 = __webpack_require__(9726); var outside_1 = __webpack_require__(4076); var tunnel_1 = __webpack_require__(7172); var getPathTo_1 = __webpack_require__(7986); var clearResidualColoredLayer = function (grid, outside, snake0, color) { var snakeN = (0, snake_1.getSnakeLength)(snake0); var tunnels = (0, exports.getTunnellablePoints)(grid, outside, snakeN, color); // sort tunnels.sort(function (a, b) { return b.priority - a.priority; }); var chain = [snake0]; while (tunnels.length) { // get the best next tunnel var t = getNextTunnel(tunnels, chain[0]); // goes to the start of the tunnel chain.unshift.apply(chain, (0, getPathTo_1.getPathTo)(grid, chain[0], t[0].x, t[0].y)); // goes to the end of the tunnel chain.unshift.apply(chain, (0, tunnel_1.getTunnelPath)(chain[0], t)); // update grid for (var _i = 0, t_1 = t; _i < t_1.length; _i++) { var _a = t_1[_i], x = _a.x, y = _a.y; setEmptySafe(grid, x, y); } // update outside (0, outside_1.fillOutside)(outside, grid); // update tunnels for (var i = tunnels.length; i--;) if ((0, grid_1.isEmpty)((0, grid_1.getColor)(grid, tunnels[i].x, tunnels[i].y))) tunnels.splice(i, 1); else { var t_2 = tunnels[i]; var tunnel = (0, getBestTunnel_1.getBestTunnel)(grid, outside, t_2.x, t_2.y, color, snakeN); if (!tunnel) tunnels.splice(i, 1); else { t_2.tunnel = tunnel; t_2.priority = (0, exports.getPriority)(grid, color, tunnel); } } // re-sort tunnels.sort(function (a, b) { return b.priority - a.priority; }); } chain.pop(); return chain; }; exports.clearResidualColoredLayer = clearResidualColoredLayer; var getNextTunnel = function (ts, snake) { var minDistance = Infinity; var closestTunnel = null; var x = (0, snake_1.getHeadX)(snake); var y = (0, snake_1.getHeadY)(snake); var priority = ts[0].priority; for (var i = 0; ts[i] && ts[i].priority === priority; i++) { var t = ts[i].tunnel; var d = distanceSq(t[0].x, t[0].y, x, y); if (d < minDistance) { minDistance = d; closestTunnel = t; } } return closestTunnel; }; /** * get all the tunnels for all the cells accessible */ var getTunnellablePoints = function (grid, outside, snakeN, color) { var points = []; for (var x = grid.width; x--;) for (var y = grid.height; y--;) { var c = (0, grid_1.getColor)(grid, x, y); if (!(0, grid_1.isEmpty)(c) && c < color) { var tunnel = (0, getBestTunnel_1.getBestTunnel)(grid, outside, x, y, color, snakeN); if (tunnel) { var priority = (0, exports.getPriority)(grid, color, tunnel); points.push({ x: x, y: y, priority: priority, tunnel: tunnel }); } } } return points; }; exports.getTunnellablePoints = getTunnellablePoints; /** * get the score of the tunnel * prioritize tunnel with maximum color smaller than and with minimum * with some tweaks */ var getPriority = function (grid, color, tunnel) { var nColor = 0; var nLess = 0; var _loop_1 = function (i) { var _a = tunnel[i], x = _a.x, y = _a.y; var c = getColorSafe(grid, x, y); if (!(0, grid_1.isEmpty)(c) && i === tunnel.findIndex(function (p) { return p.x === x && p.y === y; })) { if (c === color) nColor += 1; else nLess += color - c; } }; for (var i = 0; i < tunnel.length; i++) { _loop_1(i); } if (nColor === 0) return 99999; return nLess / nColor; }; exports.getPriority = getPriority; var distanceSq = function (ax, ay, bx, by) { return Math.pow((ax - bx), 2) + Math.pow((ay - by), 2); }; var getColorSafe = function (grid, x, y) { return (0, grid_1.isInside)(grid, x, y) ? (0, grid_1.getColor)(grid, x, y) : 0; }; var setEmptySafe = function (grid, x, y) { if ((0, grid_1.isInside)(grid, x, y)) (0, grid_1.setColorEmpty)(grid, x, y); }; /***/ }), /***/ 2705: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.getBestRoute = void 0; var grid_1 = __webpack_require__(2881); var outside_1 = __webpack_require__(4076); var clearResidualColoredLayer_1 = __webpack_require__(3650); var clearCleanColoredLayer_1 = __webpack_require__(5256); var getBestRoute = function (grid0, snake0) { var grid = (0, grid_1.copyGrid)(grid0); var outside = (0, outside_1.createOutside)(grid); var chain = [snake0]; for (var _i = 0, _a = extractColors(grid); _i < _a.length; _i++) { var color = _a[_i]; if (color > 1) chain.unshift.apply(chain, (0, clearResidualColoredLayer_1.clearResidualColoredLayer)(grid, outside, chain[0], color)); chain.unshift.apply(chain, (0, clearCleanColoredLayer_1.clearCleanColoredLayer)(grid, outside, chain[0], color)); } return chain.reverse(); }; exports.getBestRoute = getBestRoute; var extractColors = function (grid) { // @ts-ignore var maxColor = Math.max.apply(Math, grid.data); return Array.from({ length: maxColor }, function (_, i) { return (i + 1); }); }; /***/ }), /***/ 9726: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __spreadArray = (this && this.__spreadArray) || function (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)); }; exports.__esModule = true; exports.getBestTunnel = void 0; var grid_1 = __webpack_require__(2881); var point_1 = __webpack_require__(3627); var sortPush_1 = __webpack_require__(3310); var snake_1 = __webpack_require__(9347); var outside_1 = __webpack_require__(4076); var tunnel_1 = __webpack_require__(7172); var getColorSafe = function (grid, x, y) { return (0, grid_1.isInside)(grid, x, y) ? (0, grid_1.getColor)(grid, x, y) : 0; }; var setEmptySafe = function (grid, x, y) { if ((0, grid_1.isInside)(grid, x, y)) (0, grid_1.setColorEmpty)(grid, x, y); }; var unwrap = function (m) { return !m ? [] : __spreadArray(__spreadArray([], unwrap(m.parent), true), [{ x: (0, snake_1.getHeadX)(m.snake), y: (0, snake_1.getHeadY)(m.snake) }], false); }; /** * returns the path to reach the outside which contains the least color cell */ var getSnakeEscapePath = function (grid, outside, snake0, color) { var openList = [{ snake: snake0, w: 0 }]; var closeList = []; while (openList[0]) { var o = openList.shift(); var x = (0, snake_1.getHeadX)(o.snake); var y = (0, snake_1.getHeadY)(o.snake); if ((0, outside_1.isOutside)(outside, x, y)) return unwrap(o); var _loop_1 = function (a) { var c = getColorSafe(grid, x + a.x, y + a.y); if (c <= color && !(0, snake_1.snakeWillSelfCollide)(o.snake, a.x, a.y)) { var snake_2 = (0, snake_1.nextSnake)(o.snake, a.x, a.y); if (!closeList.some(function (s0) { return (0, snake_1.snakeEquals)(s0, snake_2); })) { var w = o.w + 1 + +(c === color) * 1000; (0, sortPush_1.sortPush)(openList, { snake: snake_2, w: w, parent: o }, function (a, b) { return a.w - b.w; }); closeList.push(snake_2); } } }; for (var _i = 0, around4_1 = point_1.around4; _i < around4_1.length; _i++) { var a = around4_1[_i]; _loop_1(a); } } return null; }; /** * compute the best tunnel to get to the cell and back to the outside ( best = less usage of ) * * notice that it's one of the best tunnels, more with the same score could exist */ var getBestTunnel = function (grid, outside, x, y, color, snakeN) { var c = { x: x, y: y }; var snake0 = (0, snake_1.createSnakeFromCells)(Array.from({ length: snakeN }, function () { return c; })); var one = getSnakeEscapePath(grid, outside, snake0, color); if (!one) return null; // get the position of the snake if it was going to leave the x,y cell var snakeICells = one.slice(0, snakeN); while (snakeICells.length < snakeN) snakeICells.push(snakeICells[snakeICells.length - 1]); var snakeI = (0, snake_1.createSnakeFromCells)(snakeICells); // remove from the grid the colors that one eat var gridI = (0, grid_1.copyGrid)(grid); for (var _i = 0, one_1 = one; _i < one_1.length; _i++) { var _a = one_1[_i], x_1 = _a.x, y_1 = _a.y; setEmptySafe(gridI, x_1, y_1); } var two = getSnakeEscapePath(gridI, outside, snakeI, color); if (!two) return null; one.shift(); one.reverse(); one.push.apply(one, two); (0, tunnel_1.trimTunnelStart)(grid, one); (0, tunnel_1.trimTunnelEnd)(grid, one); return one; }; exports.getBestTunnel = getBestTunnel; /***/ }), /***/ 7986: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.getPathTo = void 0; var grid_1 = __webpack_require__(2881); var point_1 = __webpack_require__(3627); var snake_1 = __webpack_require__(9347); var sortPush_1 = __webpack_require__(3310); /** * starting from snake0, get to the cell x,y * return the snake chain (reversed) */ var getPathTo = function (grid, snake0, x, y) { var openList = [{ snake: snake0, w: 0 }]; var closeList = []; while (openList.length) { var c = openList.shift(); var cx = (0, snake_1.getHeadX)(c.snake); var cy = (0, snake_1.getHeadY)(c.snake); var _loop_1 = function (i) { var _a = point_1.around4[i], dx = _a.x, dy = _a.y; var nx = cx + dx; var ny = cy + dy; if (nx === x && ny === y) { // unwrap var path = [(0, snake_1.nextSnake)(c.snake, dx, dy)]; var e = c; while (e.parent) { path.push(e.snake); e = e.parent; } return { value: path }; } if ((0, grid_1.isInsideLarge)(grid, 2, nx, ny) && !(0, snake_1.snakeWillSelfCollide)(c.snake, dx, dy) && (!(0, grid_1.isInside)(grid, nx, ny) || (0, grid_1.isEmpty)((0, grid_1.getColor)(grid, nx, ny)))) { var nsnake_1 = (0, snake_1.nextSnake)(c.snake, dx, dy); if (!closeList.some(function (s) { return (0, snake_1.snakeEquals)(nsnake_1, s); })) { var w = c.w + 1; var h = Math.abs(nx - x) + Math.abs(ny - y); var f = w + h; var o = { snake: nsnake_1, parent: c, w: w, h: h, f: f }; (0, sortPush_1.sortPush)(openList, o, function (a, b) { return a.f - b.f; }); closeList.push(nsnake_1); } } }; for (var i = 0; i < point_1.around4.length; i++) { var state_1 = _loop_1(i); if (typeof state_1 === "object") return state_1.value; } } }; exports.getPathTo = getPathTo; /***/ }), /***/ 6963: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.getPathToPose = void 0; var snake_1 = __webpack_require__(9347); var grid_1 = __webpack_require__(2881); var tunnel_1 = __webpack_require__(7172); var point_1 = __webpack_require__(3627); var sortPush_1 = __webpack_require__(3310); var isEmptySafe = function (grid, x, y) { return !(0, grid_1.isInside)(grid, x, y) || (0, grid_1.isEmpty)((0, grid_1.getColor)(grid, x, y)); }; var getPathToPose = function (snake0, target, grid) { if ((0, snake_1.snakeEquals)(snake0, target)) return []; var targetCells = (0, snake_1.snakeToCells)(target).reverse(); var snakeN = (0, snake_1.getSnakeLength)(snake0); var box = { min: { x: Math.min((0, snake_1.getHeadX)(snake0), (0, snake_1.getHeadX)(target)) - snakeN - 1, y: Math.min((0, snake_1.getHeadY)(snake0), (0, snake_1.getHeadY)(target)) - snakeN - 1 }, max: { x: Math.max((0, snake_1.getHeadX)(snake0), (0, snake_1.getHeadX)(target)) + snakeN + 1, y: Math.max((0, snake_1.getHeadY)(snake0), (0, snake_1.getHeadY)(target)) + snakeN + 1 } }; var t0 = targetCells[0], forbidden = targetCells.slice(1); forbidden.slice(0, 3); var openList = [{ snake: snake0, w: 0 }]; var closeList = []; while (openList.length) { var o = openList.shift(); var x = (0, snake_1.getHeadX)(o.snake); var y = (0, snake_1.getHeadY)(o.snake); if (x === t0.x && y === t0.y) { var path = []; var e = o; while (e) { path.push(e.snake); e = e.parent; } path.unshift.apply(path, (0, tunnel_1.getTunnelPath)(path[0], targetCells)); path.pop(); path.reverse(); return path; } var _loop_1 = function (i) { var _a = point_1.around4[i], dx = _a.x, dy = _a.y; var nx = x + dx; var ny = y + dy; if (!(0, snake_1.snakeWillSelfCollide)(o.snake, dx, dy) && (!grid || isEmptySafe(grid, nx, ny)) && (grid ? (0, grid_1.isInsideLarge)(grid, 2, nx, ny) : box.min.x <= nx && nx <= box.max.x && box.min.y <= ny && ny <= box.max.y) && !forbidden.some(function (p) { return p.x === nx && p.y === ny; })) { var snake_2 = (0, snake_1.nextSnake)(o.snake, dx, dy); if (!closeList.some(function (s) { return (0, snake_1.snakeEquals)(snake_2, s); })) { var w = o.w + 1; var h = Math.abs(nx - x) + Math.abs(ny - y); var f = w + h; (0, sortPush_1.sortPush)(openList, { f: f, w: w, snake: snake_2, parent: o }, function (a, b) { return a.f - b.f; }); closeList.push(snake_2); } } }; for (var i = 0; i < point_1.around4.length; i++) { _loop_1(i); } } }; exports.getPathToPose = getPathToPose; /***/ }), /***/ 4076: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.isOutside = exports.fillOutside = exports.createOutside = void 0; var grid_1 = __webpack_require__(2881); var point_1 = __webpack_require__(3627); var createOutside = function (grid, color) { if (color === void 0) { color = 0; } var outside = (0, grid_1.createEmptyGrid)(grid.width, grid.height); for (var x = outside.width; x--;) for (var y = outside.height; y--;) (0, grid_1.setColor)(outside, x, y, 1); (0, exports.fillOutside)(outside, grid, color); return outside; }; exports.createOutside = createOutside; var fillOutside = function (outside, grid, color) { if (color === void 0) { color = 0; } var changed = true; while (changed) { changed = false; var _loop_1 = function (x) { var _loop_2 = function (y) { if ((0, grid_1.getColor)(grid, x, y) <= color && !(0, exports.isOutside)(outside, x, y) && point_1.around4.some(function (a) { return (0, exports.isOutside)(outside, x + a.x, y + a.y); })) { changed = true; (0, grid_1.setColorEmpty)(outside, x, y); } }; for (var y = outside.height; y--;) { _loop_2(y); } }; for (var x = outside.width; x--;) { _loop_1(x); } } return outside; }; exports.fillOutside = fillOutside; var isOutside = function (outside, x, y) { return !(0, grid_1.isInside)(outside, x, y) || (0, grid_1.isEmpty)((0, grid_1.getColor)(outside, x, y)); }; exports.isOutside = isOutside; /***/ }), /***/ 1412: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.step = void 0; var grid_1 = __webpack_require__(2881); var snake_1 = __webpack_require__(9347); var step = function (grid, stack, snake) { var x = (0, snake_1.getHeadX)(snake); var y = (0, snake_1.getHeadY)(snake); var color = (0, grid_1.getColor)(grid, x, y); if ((0, grid_1.isInside)(grid, x, y) && !(0, grid_1.isEmpty)(color)) { stack.push(color); (0, grid_1.setColorEmpty)(grid, x, y); } }; exports.step = step; /***/ }), /***/ 7172: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.trimTunnelEnd = exports.trimTunnelStart = exports.updateTunnel = exports.getTunnelPath = void 0; var grid_1 = __webpack_require__(2881); var snake_1 = __webpack_require__(9347); /** * get the sequence of snake to cross the tunnel */ var getTunnelPath = function (snake0, tunnel) { var chain = []; var snake = snake0; for (var i = 1; i < tunnel.length; i++) { var dx = tunnel[i].x - (0, snake_1.getHeadX)(snake); var dy = tunnel[i].y - (0, snake_1.getHeadY)(snake); snake = (0, snake_1.nextSnake)(snake, dx, dy); chain.unshift(snake); } return chain; }; exports.getTunnelPath = getTunnelPath; /** * assuming the grid change and the colors got deleted, update the tunnel */ var updateTunnel = function (grid, tunnel, toDelete) { var _loop_1 = function () { var _a = tunnel[0], x = _a.x, y = _a.y; if (isEmptySafe(grid, x, y) || toDelete.some(function (p) { return p.x === x && p.y === y; })) { tunnel.shift(); } else return "break"; }; while (tunnel.length) { var state_1 = _loop_1(); if (state_1 === "break") break; } var _loop_2 = function () { var _b = tunnel[tunnel.length - 1], x = _b.x, y = _b.y; if (isEmptySafe(grid, x, y) || toDelete.some(function (p) { return p.x === x && p.y === y; })) { tunnel.pop(); } else return "break"; }; while (tunnel.length) { var state_2 = _loop_2(); if (state_2 === "break") break; } }; exports.updateTunnel = updateTunnel; var isEmptySafe = function (grid, x, y) { return !(0, grid_1.isInside)(grid, x, y) || (0, grid_1.isEmpty)((0, grid_1.getColor)(grid, x, y)); }; /** * remove empty cell from start */ var trimTunnelStart = function (grid, tunnel) { while (tunnel.length) { var _a = tunnel[0], x = _a.x, y = _a.y; if (isEmptySafe(grid, x, y)) tunnel.shift(); else break; } }; exports.trimTunnelStart = trimTunnelStart; /** * remove empty cell from end */ var trimTunnelEnd = function (grid, tunnel) { var _loop_3 = function () { var i = tunnel.length - 1; var _a = tunnel[i], x = _a.x, y = _a.y; if (isEmptySafe(grid, x, y) || tunnel.findIndex(function (p) { return p.x === x && p.y === y; }) < i) tunnel.pop(); else return "break"; }; while (tunnel.length) { var state_3 = _loop_3(); if (state_3 === "break") break; } }; exports.trimTunnelEnd = trimTunnelEnd; /***/ }), /***/ 3310: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.__esModule = true; exports.sortPush = void 0; var sortPush = function (arr, x, sortFn) { var a = 0; var b = arr.length; if (arr.length === 0 || sortFn(x, arr[a]) <= 0) { arr.unshift(x); return; } while (b - a > 1) { var e_1 = Math.ceil((a + b) / 2); var s = sortFn(x, arr[e_1]); if (s === 0) a = b = e_1; else if (s > 0) a = e_1; else b = e_1; } var e = Math.ceil((a + b) / 2); arr.splice(e, 0, x); }; exports.sortPush = sortPush; /***/ }), /***/ 3580: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.createGrid = void 0; var utils_1 = __webpack_require__(5913); var percent = function (x) { return (x * 100).toFixed(2); }; var createGrid = function (cells, _a, duration) { var sizeDotBorderRadius = _a.sizeDotBorderRadius, sizeDot = _a.sizeDot, sizeCell = _a.sizeCell; var svgElements = []; var styles = [ ".c{\n shape-rendering: geometricPrecision;\n fill: var(--ce);\n stroke-width: 1px;\n stroke: var(--cb);\n animation: none ".concat(duration, "ms linear infinite;\n }"), ]; var i = 0; for (var _i = 0, cells_1 = cells; _i < cells_1.length; _i++) { var _b = cells_1[_i], x = _b.x, y = _b.y, color = _b.color, t = _b.t; var id = t && "c" + (i++).toString(36); var s = sizeCell; var d = sizeDot; var m = (s - d) / 2; if (t !== null) { var animationName = id; styles.push("@keyframes ".concat(animationName, " {") + "".concat(percent(t - 0.0001), "%{fill:var(--c").concat(color, ")}") + "".concat(percent(t + 0.0001), "%,100%{fill:var(--ce)}") + "}", ".c.".concat(id, "{fill: var(--c").concat(color, "); animation-name: ").concat(animationName, "}")); } svgElements.push((0, utils_1.h)("rect", { "class": ["c", id].filter(Boolean).join(" "), x: x * s + m, y: y * s + m, rx: sizeDotBorderRadius, ry: sizeDotBorderRadius, width: d, height: d })); } return { svgElements: svgElements, styles: styles }; }; exports.createGrid = createGrid; /***/ }), /***/ 7415: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __spreadArray = (this && this.__spreadArray) || function (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)); }; exports.__esModule = true; exports.createSvg = void 0; var grid_1 = __webpack_require__(2881); var snake_1 = __webpack_require__(9347); var snake_2 = __webpack_require__(8243); var grid_2 = __webpack_require__(3580); var stack_1 = __webpack_require__(7466); var utils_1 = __webpack_require__(5913); var csso = __importStar(__webpack_require__(1830)); var getCellsFromGrid = function (_a) { var width = _a.width, height = _a.height; return Array.from({ length: width }, function (_, x) { return Array.from({ length: height }, function (_, y) { return ({ x: x, y: y }); }); }).flat(); }; var createLivingCells = function (grid0, chain, cells) { var livingCells = (cells !== null && cells !== void 0 ? cells : getCellsFromGrid(grid0)).map(function (_a) { var x = _a.x, y = _a.y; return ({ x: x, y: y, t: null, color: (0, grid_1.getColor)(grid0, x, y) }); }); var grid = (0, grid_1.copyGrid)(grid0); var _loop_1 = function (i) { var snake = chain[i]; var x = (0, snake_1.getHeadX)(snake); var y = (0, snake_1.getHeadY)(snake); if ((0, grid_1.isInside)(grid, x, y) && !(0, grid_1.isEmpty)((0, grid_1.getColor)(grid, x, y))) { (0, grid_1.setColorEmpty)(grid, x, y); var cell = livingCells.find(function (c) { return c.x === x && c.y === y; }); cell.t = i / chain.length; } }; for (var i = 0; i < chain.length; i++) { _loop_1(i); } return livingCells; }; var createSvg = function (grid, cells, chain, drawOptions, animationOptions) { var width = (grid.width + 2) * drawOptions.sizeCell; var height = (grid.height + 5) * drawOptions.sizeCell; var duration = animationOptions.frameDuration * chain.length; var livingCells = createLivingCells(grid, chain, cells); var elements = [ (0, grid_2.createGrid)(livingCells, drawOptions, duration), (0, stack_1.createStack)(livingCells, drawOptions, grid.width * drawOptions.sizeCell, (grid.height + 2) * drawOptions.sizeCell, duration), (0, snake_2.createSnake)(chain, drawOptions, duration), ]; var viewBox = [ -drawOptions.sizeCell, -drawOptions.sizeCell * 2, width, height, ].join(" "); var style = generateColorVar(drawOptions) + elements .map(function (e) { return e.styles; }) .flat() .join("\n"); var svg = __spreadArray(__spreadArray([ (0, utils_1.h)("svg", { viewBox: viewBox, width: width, height: height, xmlns: "http://www.w3.org/2000/svg" }).replace("/>", ">"), "", "Generated with https://github.com/Platane/snk", "", "" ], elements.map(function (e) { return e.svgElements; }).flat(), true), [ "", ], false).join(""); return optimizeSvg(svg); }; exports.createSvg = createSvg; var optimizeCss = function (css) { return csso.minify(css).css; }; var optimizeSvg = function (svg) { return svg; }; var generateColorVar = function (drawOptions) { return "\n :root {\n --cb: ".concat(drawOptions.colorDotBorder, ";\n --cs: ").concat(drawOptions.colorSnake, ";\n --ce: ").concat(drawOptions.colorEmpty, ";\n ").concat(Object.entries(drawOptions.colorDots) .map(function (_a) { var i = _a[0], color = _a[1]; return "--c".concat(i, ":").concat(color, ";"); }) .join(""), "\n }\n ") + (drawOptions.dark ? "\n @media (prefers-color-scheme: dark) {\n :root {\n --cb: ".concat(drawOptions.dark.colorDotBorder || drawOptions.colorDotBorder, ";\n --cs: ").concat(drawOptions.dark.colorSnake || drawOptions.colorSnake, ";\n --ce: ").concat(drawOptions.dark.colorEmpty, ";\n ").concat(Object.entries(drawOptions.dark.colorDots) .map(function (_a) { var i = _a[0], color = _a[1]; return "--c".concat(i, ":").concat(color, ";"); }) .join(""), "\n }\n }\n") : ""); }; /***/ }), /***/ 8243: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __spreadArray = (this && this.__spreadArray) || function (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)); }; exports.__esModule = true; exports.createSnake = void 0; var snake_1 = __webpack_require__(9347); var utils_1 = __webpack_require__(5913); var percent = function (x) { return (x * 100).toFixed(2); }; var lerp = function (k, a, b) { return (1 - k) * a + k * b; }; var createSnake = function (chain, _a, duration) { var sizeCell = _a.sizeCell, sizeDot = _a.sizeDot; var snakeN = chain[0] ? (0, snake_1.getSnakeLength)(chain[0]) : 0; var snakeParts = Array.from({ length: snakeN }, function () { return []; }); for (var _i = 0, chain_1 = chain; _i < chain_1.length; _i++) { var snake = chain_1[_i]; var cells = (0, snake_1.snakeToCells)(snake); for (var i = cells.length; i--;) snakeParts[i].push(cells[i]); } var svgElements = snakeParts.map(function (_, i, _a) { var length = _a.length; // compute snake part size var dMin = sizeDot * 0.8; var dMax = sizeCell * 0.9; var iMax = Math.min(4, length); var u = Math.pow((1 - Math.min(i, iMax) / iMax), 2); var s = lerp(u, dMin, dMax); var m = (sizeCell - s) / 2; var r = Math.min(4.5, (4 * s) / sizeDot); return (0, utils_1.h)("rect", { "class": "s s".concat(i), x: m.toFixed(1), y: m.toFixed(1), width: s.toFixed(1), height: s.toFixed(1), rx: r.toFixed(1), ry: r.toFixed(1) }); }); var transform = function (_a) { var x = _a.x, y = _a.y; return "transform:translate(".concat(x * sizeCell, "px,").concat(y * sizeCell, "px)"); }; var styles = __spreadArray([ ".s{ \n shape-rendering:geometricPrecision;\n fill:var(--cs);\n animation: none linear ".concat(duration, "ms infinite\n }") ], snakeParts.map(function (positions, i) { var id = "s".concat(i); var animationName = id; return [ "@keyframes ".concat(animationName, " {") + removeInterpolatedPositions(positions.map(function (tr, i, _a) { var length = _a.length; return (__assign(__assign({}, tr), { t: i / length })); })) .map(function (p) { return "".concat(percent(p.t), "%{").concat(transform(p), "}"); }) .join("") + "}", ".s.".concat(id, "{").concat(transform(positions[0]), ";animation-name: ").concat(animationName, "}"), ]; }), true).flat(); return { svgElements: svgElements, styles: styles }; }; exports.createSnake = createSnake; var removeInterpolatedPositions = function (arr) { return arr.filter(function (u, i, arr) { if (i - 1 < 0 || i + 1 >= arr.length) return true; var a = arr[i - 1]; var b = arr[i + 1]; var ex = (a.x + b.x) / 2; var ey = (a.y + b.y) / 2; // return true; return !(Math.abs(ex - u.x) < 0.01 && Math.abs(ey - u.y) < 0.01); }); }; /***/ }), /***/ 7466: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __spreadArray = (this && this.__spreadArray) || function (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)); }; exports.__esModule = true; exports.createStack = void 0; var utils_1 = __webpack_require__(5913); var percent = function (x) { return (x * 100).toFixed(2); }; var createStack = function (cells, _a, width, y, duration) { var sizeDot = _a.sizeDot; var svgElements = []; var styles = [ ".u{ \n transform-origin: 0 0;\n transform: scale(0,1);\n animation: none linear ".concat(duration, "ms infinite;\n }"), ]; var stack = cells .slice() .filter(function (a) { return a.t !== null; }) .sort(function (a, b) { return a.t - b.t; }); var blocks = []; stack.forEach(function (_a) { var color = _a.color, t = _a.t; var latest = blocks[blocks.length - 1]; if ((latest === null || latest === void 0 ? void 0 : latest.color) === color) latest.ts.push(t); else blocks.push({ color: color, ts: [t] }); }); var m = width / stack.length; var i = 0; var nx = 0; for (var _i = 0, blocks_1 = blocks; _i < blocks_1.length; _i++) { var _b = blocks_1[_i], color = _b.color, ts = _b.ts; var id = "u" + (i++).toString(36); var animationName = id; var x = (nx * m).toFixed(1); nx += ts.length; svgElements.push((0, utils_1.h)("rect", { "class": "u ".concat(id), height: sizeDot, width: (ts.length * m + 0.6).toFixed(1), x: x, y: y })); styles.push("@keyframes ".concat(animationName, " {") + __spreadArray(__spreadArray([], ts.map(function (t, i, _a) { var length = _a.length; return [ { scale: i / length, t: t - 0.0001 }, { scale: (i + 1) / length, t: t + 0.0001 }, ]; }), true), [ [{ scale: 1, t: 1 }], ], false).flat() .map(function (_a) { var scale = _a.scale, t = _a.t; return "".concat(percent(t), "%{transform:scale(").concat(scale.toFixed(2), ",1)}"); }) .join("\n") + "}", ".u.".concat(id, "{fill:var(--c").concat(color, ");animation-name:").concat(animationName, ";transform-origin:").concat(x, "px 0}")); } return { svgElements: svgElements, styles: styles }; }; exports.createStack = createStack; /***/ }), /***/ 5913: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.__esModule = true; exports.toAttribute = exports.h = void 0; var h = function (element, attributes) { return "<".concat(element, " ").concat((0, exports.toAttribute)(attributes), "/>"); }; exports.h = h; var toAttribute = function (o) { return Object.entries(o) .filter(function (_a) { var value = _a[1]; return value !== null; }) .map(function (_a) { var name = _a[0], value = _a[1]; return "".concat(name, "=\"").concat(value, "\""); }) .join(" "); }; exports.toAttribute = toAttribute; /***/ }), /***/ 7087: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; exports.__esModule = true; exports.snake9 = exports.snake5 = exports.snake4 = exports.snake3 = exports.snake1 = void 0; var snake_1 = __webpack_require__(9347); var create = function (length) { return (0, snake_1.createSnakeFromCells)(Array.from({ length: length }, function (_, i) { return ({ x: i, y: -1 }); })); }; exports.snake1 = create(1); exports.snake3 = create(3); exports.snake4 = create(4); exports.snake5 = create(5); exports.snake9 = create(9); /***/ }), /***/ 2881: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.__esModule = true; exports.createEmptyGrid = exports.gridEquals = exports.isGridEmpty = exports.setColorEmpty = exports.setColor = exports.isEmpty = exports.getColor = exports.copyGrid = exports.isInsideLarge = exports.isInside = void 0; var isInside = function (grid, x, y) { return x >= 0 && y >= 0 && x < grid.width && y < grid.height; }; exports.isInside = isInside; var isInsideLarge = function (grid, m, x, y) { return x >= -m && y >= -m && x < grid.width + m && y < grid.height + m; }; exports.isInsideLarge = isInsideLarge; var copyGrid = function (_a) { var width = _a.width, height = _a.height, data = _a.data; return ({ width: width, height: height, data: Uint8Array.from(data) }); }; exports.copyGrid = copyGrid; var getIndex = function (grid, x, y) { return x * grid.height + y; }; var getColor = function (grid, x, y) { return grid.data[getIndex(grid, x, y)]; }; exports.getColor = getColor; var isEmpty = function (color) { return color === 0; }; exports.isEmpty = isEmpty; var setColor = function (grid, x, y, color) { grid.data[getIndex(grid, x, y)] = color || 0; }; exports.setColor = setColor; var setColorEmpty = function (grid, x, y) { (0, exports.setColor)(grid, x, y, 0); }; exports.setColorEmpty = setColorEmpty; /** * return true if the grid is empty */ var isGridEmpty = function (grid) { return grid.data.every(function (x) { return x === 0; }); }; exports.isGridEmpty = isGridEmpty; var gridEquals = function (a, b) { return a.data.every(function (_, i) { return a.data[i] === b.data[i]; }); }; exports.gridEquals = gridEquals; var createEmptyGrid = function (width, height) { return ({ width: width, height: height, data: new Uint8Array(width * height) }); }; exports.createEmptyGrid = createEmptyGrid; /***/ }), /***/ 3627: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.__esModule = true; exports.pointEquals = exports.around4 = void 0; exports.around4 = [ { x: 1, y: 0 }, { x: 0, y: -1 }, { x: -1, y: 0 }, { x: 0, y: 1 }, ]; var pointEquals = function (a, b) { return a.x === b.x && a.y === b.y; }; exports.pointEquals = pointEquals; /***/ }), /***/ 9347: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.__esModule = true; exports.createSnakeFromCells = exports.snakeToCells = exports.snakeWillSelfCollide = exports.nextSnake = exports.snakeEquals = exports.copySnake = exports.getSnakeLength = exports.getHeadY = exports.getHeadX = void 0; var getHeadX = function (snake) { return snake[0] - 2; }; exports.getHeadX = getHeadX; var getHeadY = function (snake) { return snake[1] - 2; }; exports.getHeadY = getHeadY; var getSnakeLength = function (snake) { return snake.length / 2; }; exports.getSnakeLength = getSnakeLength; var copySnake = function (snake) { return snake.slice(); }; exports.copySnake = copySnake; var snakeEquals = function (a, b) { for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; return true; }; exports.snakeEquals = snakeEquals; /** * return a copy of the next snake, considering that dx, dy is the direction */ var nextSnake = function (snake, dx, dy) { var copy = new Uint8Array(snake.length); for (var i = 2; i < snake.length; i++) copy[i] = snake[i - 2]; copy[0] = snake[0] + dx; copy[1] = snake[1] + dy; return copy; }; exports.nextSnake = nextSnake; /** * return true if the next snake will collide with itself */ var snakeWillSelfCollide = function (snake, dx, dy) { var nx = snake[0] + dx; var ny = snake[1] + dy; for (var i = 2; i < snake.length - 2; i += 2) if (snake[i + 0] === nx && snake[i + 1] === ny) return true; return false; }; exports.snakeWillSelfCollide = snakeWillSelfCollide; var snakeToCells = function (snake) { return Array.from({ length: snake.length / 2 }, function (_, i) { return ({ x: snake[i * 2 + 0] - 2, y: snake[i * 2 + 1] - 2 }); }); }; exports.snakeToCells = snakeToCells; var createSnakeFromCells = function (points) { var snake = new Uint8Array(points.length * 2); for (var i = points.length; i--;) { snake[i * 2 + 0] = points[i].x + 2; snake[i * 2 + 1] = points[i].y + 2; } return snake; }; exports.createSnakeFromCells = createSnakeFromCells; /***/ }), /***/ 9609: /***/ ((module) => { module.exports = eval("require")("encoding"); /***/ }), /***/ 8348: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const List = __webpack_require__(2080); function createConvertor(walk) { return { fromPlainObject: function(ast) { walk(ast, { enter: function(node) { if (node.children && node.children instanceof List.List === false) { node.children = new List.List().fromArray(node.children); } } }); return ast; }, toPlainObject: function(ast) { walk(ast, { leave: function(node) { if (node.children && node.children instanceof List.List) { node.children = node.children.toArray(); } } }); return ast; } }; } exports.createConvertor = createConvertor; /***/ }), /***/ 8237: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const patch = __webpack_require__(8663); module.exports = patch; /***/ }), /***/ 4743: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const dataPatch = __webpack_require__(8237); const mdnAtrules = __webpack_require__(658); const mdnProperties = __webpack_require__(9149); const mdnSyntaxes = __webpack_require__(2368); const extendSyntax = /^\s*\|\s*/; function preprocessAtrules(dict) { const result = Object.create(null); for (const atruleName in dict) { const atrule = dict[atruleName]; let descriptors = null; if (atrule.descriptors) { descriptors = Object.create(null); for (const descriptor in atrule.descriptors) { descriptors[descriptor] = atrule.descriptors[descriptor].syntax; } } result[atruleName.substr(1)] = { prelude: atrule.syntax.trim().match(/^@\S+\s+([^;\{]*)/)[1].trim() || null, descriptors }; } return result; } function patchDictionary(dict, patchDict) { const result = {}; // copy all syntaxes for an original dict for (const key in dict) { result[key] = dict[key].syntax || dict[key]; } // apply a patch for (const key in patchDict) { if (key in dict) { if (patchDict[key].syntax) { result[key] = extendSyntax.test(patchDict[key].syntax) ? result[key] + ' ' + patchDict[key].syntax.trim() : patchDict[key].syntax; } else { delete result[key]; } } else { if (patchDict[key].syntax) { result[key] = patchDict[key].syntax.replace(extendSyntax, ''); } } } return result; } function patchAtrules(dict, patchDict) { const result = {}; // copy all syntaxes for an original dict for (const key in dict) { const patchDescriptors = (patchDict[key] && patchDict[key].descriptors) || null; result[key] = { prelude: key in patchDict && 'prelude' in patchDict[key] ? patchDict[key].prelude : dict[key].prelude || null, descriptors: patchDictionary(dict[key].descriptors || {}, patchDescriptors || {}) }; } // apply a patch for (const key in patchDict) { if (!hasOwnProperty.call(dict, key)) { result[key] = { prelude: patchDict[key].prelude || null, descriptors: patchDict[key].descriptors && patchDictionary({}, patchDict[key].descriptors) }; } } return result; } const definitions = { types: patchDictionary(mdnSyntaxes, dataPatch.syntaxes), atrules: patchAtrules(preprocessAtrules(mdnAtrules), dataPatch.atrules), properties: patchDictionary(mdnProperties, dataPatch.properties) }; module.exports = definitions; /***/ }), /***/ 3921: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const createCustomError = __webpack_require__(7324); function SyntaxError(message, input, offset) { return Object.assign(createCustomError.createCustomError('SyntaxError', message), { input, offset, rawMessage: message, message: message + '\n' + ' ' + input + '\n' + '--' + new Array((offset || input.length) + 1).join('-') + '^' }); } exports.SyntaxError = SyntaxError; /***/ }), /***/ 9931: /***/ ((__unused_webpack_module, exports) => { "use strict"; function noop(value) { return value; } function generateMultiplier(multiplier) { const { min, max, comma } = multiplier; if (min === 0 && max === 0) { return '*'; } if (min === 0 && max === 1) { return '?'; } if (min === 1 && max === 0) { return comma ? '#' : '+'; } if (min === 1 && max === 1) { return ''; } return ( (comma ? '#' : '') + (min === max ? '{' + min + '}' : '{' + min + ',' + (max !== 0 ? max : '') + '}' ) ); } function generateTypeOpts(node) { switch (node.type) { case 'Range': return ( ' [' + (node.min === null ? '-∞' : node.min) + ',' + (node.max === null ? '∞' : node.max) + ']' ); default: throw new Error('Unknown node type `' + node.type + '`'); } } function generateSequence(node, decorate, forceBraces, compact) { const combinator = node.combinator === ' ' || compact ? node.combinator : ' ' + node.combinator + ' '; const result = node.terms .map(term => internalGenerate(term, decorate, forceBraces, compact)) .join(combinator); if (node.explicit || forceBraces) { return (compact || result[0] === ',' ? '[' : '[ ') + result + (compact ? ']' : ' ]'); } return result; } function internalGenerate(node, decorate, forceBraces, compact) { let result; switch (node.type) { case 'Group': result = generateSequence(node, decorate, forceBraces, compact) + (node.disallowEmpty ? '!' : ''); break; case 'Multiplier': // return since node is a composition return ( internalGenerate(node.term, decorate, forceBraces, compact) + decorate(generateMultiplier(node), node) ); case 'Type': result = '<' + node.name + (node.opts ? decorate(generateTypeOpts(node.opts), node.opts) : '') + '>'; break; case 'Property': result = '<\'' + node.name + '\'>'; break; case 'Keyword': result = node.name; break; case 'AtKeyword': result = '@' + node.name; break; case 'Function': result = node.name + '('; break; case 'String': case 'Token': result = node.value; break; case 'Comma': result = ','; break; default: throw new Error('Unknown node type `' + node.type + '`'); } return decorate(result, node); } function generate(node, options) { let decorate = noop; let forceBraces = false; let compact = false; if (typeof options === 'function') { decorate = options; } else if (options) { forceBraces = Boolean(options.forceBraces); compact = Boolean(options.compact); if (typeof options.decorate === 'function') { decorate = options.decorate; } } return internalGenerate(node, decorate, forceBraces, compact); } exports.generate = generate; /***/ }), /***/ 7: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const _SyntaxError = __webpack_require__(3921); const generate = __webpack_require__(9931); const parse = __webpack_require__(8544); const walk = __webpack_require__(2388); exports.SyntaxError = _SyntaxError.SyntaxError; exports.generate = generate.generate; exports.parse = parse.parse; exports.walk = walk.walk; /***/ }), /***/ 8544: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const tokenizer = __webpack_require__(1627); const TAB = 9; const N = 10; const F = 12; const R = 13; const SPACE = 32; const EXCLAMATIONMARK = 33; // ! const NUMBERSIGN = 35; // # const AMPERSAND = 38; // & const APOSTROPHE = 39; // ' const LEFTPARENTHESIS = 40; // ( const RIGHTPARENTHESIS = 41; // ) const ASTERISK = 42; // * const PLUSSIGN = 43; // + const COMMA = 44; // , const HYPERMINUS = 45; // - const LESSTHANSIGN = 60; // < const GREATERTHANSIGN = 62; // > const QUESTIONMARK = 63; // ? const COMMERCIALAT = 64; // @ const LEFTSQUAREBRACKET = 91; // [ const RIGHTSQUAREBRACKET = 93; // ] const LEFTCURLYBRACKET = 123; // { const VERTICALLINE = 124; // | const RIGHTCURLYBRACKET = 125; // } const INFINITY = 8734; // ∞ const NAME_CHAR = new Uint8Array(128).map((_, idx) => /[a-zA-Z0-9\-]/.test(String.fromCharCode(idx)) ? 1 : 0 ); const COMBINATOR_PRECEDENCE = { ' ': 1, '&&': 2, '||': 3, '|': 4 }; function scanSpaces(tokenizer) { return tokenizer.substringToPos( tokenizer.findWsEnd(tokenizer.pos) ); } function scanWord(tokenizer) { let end = tokenizer.pos; for (; end < tokenizer.str.length; end++) { const code = tokenizer.str.charCodeAt(end); if (code >= 128 || NAME_CHAR[code] === 0) { break; } } if (tokenizer.pos === end) { tokenizer.error('Expect a keyword'); } return tokenizer.substringToPos(end); } function scanNumber(tokenizer) { let end = tokenizer.pos; for (; end < tokenizer.str.length; end++) { const code = tokenizer.str.charCodeAt(end); if (code < 48 || code > 57) { break; } } if (tokenizer.pos === end) { tokenizer.error('Expect a number'); } return tokenizer.substringToPos(end); } function scanString(tokenizer) { const end = tokenizer.str.indexOf('\'', tokenizer.pos + 1); if (end === -1) { tokenizer.pos = tokenizer.str.length; tokenizer.error('Expect an apostrophe'); } return tokenizer.substringToPos(end + 1); } function readMultiplierRange(tokenizer) { let min = null; let max = null; tokenizer.eat(LEFTCURLYBRACKET); min = scanNumber(tokenizer); if (tokenizer.charCode() === COMMA) { tokenizer.pos++; if (tokenizer.charCode() !== RIGHTCURLYBRACKET) { max = scanNumber(tokenizer); } } else { max = min; } tokenizer.eat(RIGHTCURLYBRACKET); return { min: Number(min), max: max ? Number(max) : 0 }; } function readMultiplier(tokenizer) { let range = null; let comma = false; switch (tokenizer.charCode()) { case ASTERISK: tokenizer.pos++; range = { min: 0, max: 0 }; break; case PLUSSIGN: tokenizer.pos++; range = { min: 1, max: 0 }; break; case QUESTIONMARK: tokenizer.pos++; range = { min: 0, max: 1 }; break; case NUMBERSIGN: tokenizer.pos++; comma = true; if (tokenizer.charCode() === LEFTCURLYBRACKET) { range = readMultiplierRange(tokenizer); } else { range = { min: 1, max: 0 }; } break; case LEFTCURLYBRACKET: range = readMultiplierRange(tokenizer); break; default: return null; } return { type: 'Multiplier', comma, min: range.min, max: range.max, term: null }; } function maybeMultiplied(tokenizer, node) { const multiplier = readMultiplier(tokenizer); if (multiplier !== null) { multiplier.term = node; return multiplier; } return node; } function maybeToken(tokenizer) { const ch = tokenizer.peek(); if (ch === '') { return null; } return { type: 'Token', value: ch }; } function readProperty(tokenizer) { let name; tokenizer.eat(LESSTHANSIGN); tokenizer.eat(APOSTROPHE); name = scanWord(tokenizer); tokenizer.eat(APOSTROPHE); tokenizer.eat(GREATERTHANSIGN); return maybeMultiplied(tokenizer, { type: 'Property', name }); } // https://drafts.csswg.org/css-values-3/#numeric-ranges // 4.1. Range Restrictions and Range Definition Notation // // Range restrictions can be annotated in the numeric type notation using CSS bracketed // range notation—[min,max]—within the angle brackets, after the identifying keyword, // indicating a closed range between (and including) min and max. // For example, indicates an integer between 0 and 10, inclusive. function readTypeRange(tokenizer) { // use null for Infinity to make AST format JSON serializable/deserializable let min = null; // -Infinity let max = null; // Infinity let sign = 1; tokenizer.eat(LEFTSQUAREBRACKET); if (tokenizer.charCode() === HYPERMINUS) { tokenizer.peek(); sign = -1; } if (sign == -1 && tokenizer.charCode() === INFINITY) { tokenizer.peek(); } else { min = sign * Number(scanNumber(tokenizer)); } scanSpaces(tokenizer); tokenizer.eat(COMMA); scanSpaces(tokenizer); if (tokenizer.charCode() === INFINITY) { tokenizer.peek(); } else { sign = 1; if (tokenizer.charCode() === HYPERMINUS) { tokenizer.peek(); sign = -1; } max = sign * Number(scanNumber(tokenizer)); } tokenizer.eat(RIGHTSQUAREBRACKET); // If no range is indicated, either by using the bracketed range notation // or in the property description, then [−∞,∞] is assumed. if (min === null && max === null) { return null; } return { type: 'Range', min, max }; } function readType(tokenizer) { let name; let opts = null; tokenizer.eat(LESSTHANSIGN); name = scanWord(tokenizer); if (tokenizer.charCode() === LEFTPARENTHESIS && tokenizer.nextCharCode() === RIGHTPARENTHESIS) { tokenizer.pos += 2; name += '()'; } if (tokenizer.charCodeAt(tokenizer.findWsEnd(tokenizer.pos)) === LEFTSQUAREBRACKET) { scanSpaces(tokenizer); opts = readTypeRange(tokenizer); } tokenizer.eat(GREATERTHANSIGN); return maybeMultiplied(tokenizer, { type: 'Type', name, opts }); } function readKeywordOrFunction(tokenizer) { const name = scanWord(tokenizer); if (tokenizer.charCode() === LEFTPARENTHESIS) { tokenizer.pos++; return { type: 'Function', name }; } return maybeMultiplied(tokenizer, { type: 'Keyword', name }); } function regroupTerms(terms, combinators) { function createGroup(terms, combinator) { return { type: 'Group', terms, combinator, disallowEmpty: false, explicit: false }; } let combinator; combinators = Object.keys(combinators) .sort((a, b) => COMBINATOR_PRECEDENCE[a] - COMBINATOR_PRECEDENCE[b]); while (combinators.length > 0) { combinator = combinators.shift(); let i = 0; let subgroupStart = 0; for (; i < terms.length; i++) { const term = terms[i]; if (term.type === 'Combinator') { if (term.value === combinator) { if (subgroupStart === -1) { subgroupStart = i - 1; } terms.splice(i, 1); i--; } else { if (subgroupStart !== -1 && i - subgroupStart > 1) { terms.splice( subgroupStart, i - subgroupStart, createGroup(terms.slice(subgroupStart, i), combinator) ); i = subgroupStart + 1; } subgroupStart = -1; } } } if (subgroupStart !== -1 && combinators.length) { terms.splice( subgroupStart, i - subgroupStart, createGroup(terms.slice(subgroupStart, i), combinator) ); } } return combinator; } function readImplicitGroup(tokenizer) { const terms = []; const combinators = {}; let token; let prevToken = null; let prevTokenPos = tokenizer.pos; while (token = peek(tokenizer)) { if (token.type !== 'Spaces') { if (token.type === 'Combinator') { // check for combinator in group beginning and double combinator sequence if (prevToken === null || prevToken.type === 'Combinator') { tokenizer.pos = prevTokenPos; tokenizer.error('Unexpected combinator'); } combinators[token.value] = true; } else if (prevToken !== null && prevToken.type !== 'Combinator') { combinators[' '] = true; // a b terms.push({ type: 'Combinator', value: ' ' }); } terms.push(token); prevToken = token; prevTokenPos = tokenizer.pos; } } // check for combinator in group ending if (prevToken !== null && prevToken.type === 'Combinator') { tokenizer.pos -= prevTokenPos; tokenizer.error('Unexpected combinator'); } return { type: 'Group', terms, combinator: regroupTerms(terms, combinators) || ' ', disallowEmpty: false, explicit: false }; } function readGroup(tokenizer) { let result; tokenizer.eat(LEFTSQUAREBRACKET); result = readImplicitGroup(tokenizer); tokenizer.eat(RIGHTSQUAREBRACKET); result.explicit = true; if (tokenizer.charCode() === EXCLAMATIONMARK) { tokenizer.pos++; result.disallowEmpty = true; } return result; } function peek(tokenizer) { let code = tokenizer.charCode(); if (code < 128 && NAME_CHAR[code] === 1) { return readKeywordOrFunction(tokenizer); } switch (code) { case RIGHTSQUAREBRACKET: // don't eat, stop scan a group break; case LEFTSQUAREBRACKET: return maybeMultiplied(tokenizer, readGroup(tokenizer)); case LESSTHANSIGN: return tokenizer.nextCharCode() === APOSTROPHE ? readProperty(tokenizer) : readType(tokenizer); case VERTICALLINE: return { type: 'Combinator', value: tokenizer.substringToPos( tokenizer.pos + (tokenizer.nextCharCode() === VERTICALLINE ? 2 : 1) ) }; case AMPERSAND: tokenizer.pos++; tokenizer.eat(AMPERSAND); return { type: 'Combinator', value: '&&' }; case COMMA: tokenizer.pos++; return { type: 'Comma' }; case APOSTROPHE: return maybeMultiplied(tokenizer, { type: 'String', value: scanString(tokenizer) }); case SPACE: case TAB: case N: case R: case F: return { type: 'Spaces', value: scanSpaces(tokenizer) }; case COMMERCIALAT: code = tokenizer.nextCharCode(); if (code < 128 && NAME_CHAR[code] === 1) { tokenizer.pos++; return { type: 'AtKeyword', name: scanWord(tokenizer) }; } return maybeToken(tokenizer); case ASTERISK: case PLUSSIGN: case QUESTIONMARK: case NUMBERSIGN: case EXCLAMATIONMARK: // prohibited tokens (used as a multiplier start) break; case LEFTCURLYBRACKET: // LEFTCURLYBRACKET is allowed since mdn/data uses it w/o quoting // check next char isn't a number, because it's likely a disjoined multiplier code = tokenizer.nextCharCode(); if (code < 48 || code > 57) { return maybeToken(tokenizer); } break; default: return maybeToken(tokenizer); } } function parse(source) { const tokenizer$1 = new tokenizer.Tokenizer(source); const result = readImplicitGroup(tokenizer$1); if (tokenizer$1.pos !== source.length) { tokenizer$1.error('Unexpected input'); } // reduce redundant groups with single group term if (result.terms.length === 1 && result.terms[0].type === 'Group') { return result.terms[0]; } return result; } exports.parse = parse; /***/ }), /***/ 1627: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const _SyntaxError = __webpack_require__(3921); const TAB = 9; const N = 10; const F = 12; const R = 13; const SPACE = 32; class Tokenizer { constructor(str) { this.str = str; this.pos = 0; } charCodeAt(pos) { return pos < this.str.length ? this.str.charCodeAt(pos) : 0; } charCode() { return this.charCodeAt(this.pos); } nextCharCode() { return this.charCodeAt(this.pos + 1); } nextNonWsCode(pos) { return this.charCodeAt(this.findWsEnd(pos)); } findWsEnd(pos) { for (; pos < this.str.length; pos++) { const code = this.str.charCodeAt(pos); if (code !== R && code !== N && code !== F && code !== SPACE && code !== TAB) { break; } } return pos; } substringToPos(end) { return this.str.substring(this.pos, this.pos = end); } eat(code) { if (this.charCode() !== code) { this.error('Expect `' + String.fromCharCode(code) + '`'); } this.pos++; } peek() { return this.pos < this.str.length ? this.str.charAt(this.pos++) : ''; } error(message) { throw new _SyntaxError.SyntaxError(message, this.str, this.pos); } } exports.Tokenizer = Tokenizer; /***/ }), /***/ 2388: /***/ ((__unused_webpack_module, exports) => { "use strict"; const noop = function() {}; function ensureFunction(value) { return typeof value === 'function' ? value : noop; } function walk(node, options, context) { function walk(node) { enter.call(context, node); switch (node.type) { case 'Group': node.terms.forEach(walk); break; case 'Multiplier': walk(node.term); break; case 'Type': case 'Property': case 'Keyword': case 'AtKeyword': case 'Function': case 'String': case 'Token': case 'Comma': break; default: throw new Error('Unknown type: ' + node.type); } leave.call(context, node); } let enter = noop; let leave = noop; if (typeof options === 'function') { enter = options; } else if (options) { enter = ensureFunction(options.enter); leave = ensureFunction(options.leave); } if (enter === noop && leave === noop) { throw new Error('Neither `enter` nor `leave` walker handler is set or both aren\'t a function'); } walk(node); } exports.walk = walk; /***/ }), /***/ 9074: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const index = __webpack_require__(338); const sourceMap = __webpack_require__(4553); const tokenBefore = __webpack_require__(7284); const types = __webpack_require__(4764); const REVERSESOLIDUS = 0x005c; // U+005C REVERSE SOLIDUS (\) function processChildren(node, delimeter) { if (typeof delimeter === 'function') { let prev = null; node.children.forEach(node => { if (prev !== null) { delimeter.call(this, prev); } this.node(node); prev = node; }); return; } node.children.forEach(this.node, this); } function processChunk(chunk) { index.tokenize(chunk, (type, start, end) => { this.token(type, chunk.slice(start, end)); }); } function createGenerator(config) { const types$1 = new Map(); for (let name in config.node) { types$1.set(name, config.node[name].generate); } return function(node, options) { let buffer = ''; let prevCode = 0; let handlers = { node(node) { if (types$1.has(node.type)) { types$1.get(node.type).call(publicApi, node); } else { throw new Error('Unknown node type: ' + node.type); } }, tokenBefore: tokenBefore.safe, token(type, value) { prevCode = this.tokenBefore(prevCode, type, value); this.emit(value, type, false); if (type === types.Delim && value.charCodeAt(0) === REVERSESOLIDUS) { this.emit('\n', types.WhiteSpace, true); } }, emit(value) { buffer += value; }, result() { return buffer; } }; if (options) { if (typeof options.decorator === 'function') { handlers = options.decorator(handlers); } if (options.sourceMap) { handlers = sourceMap.generateSourceMap(handlers); } if (options.mode in tokenBefore) { handlers.tokenBefore = tokenBefore[options.mode]; } } const publicApi = { node: (node) => handlers.node(node), children: processChildren, token: (type, value) => handlers.token(type, value), tokenize: processChunk }; handlers.node(node); return handlers.result(); }; } exports.createGenerator = createGenerator; /***/ }), /***/ 4553: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const sourceMapGenerator_js = __webpack_require__(5997); const trackNodes = new Set(['Atrule', 'Selector', 'Declaration']); function generateSourceMap(handlers) { const map = new sourceMapGenerator_js.SourceMapGenerator(); const generated = { line: 1, column: 0 }; const original = { line: 0, // should be zero to add first mapping column: 0 }; const activatedGenerated = { line: 1, column: 0 }; const activatedMapping = { generated: activatedGenerated }; let line = 1; let column = 0; let sourceMappingActive = false; const origHandlersNode = handlers.node; handlers.node = function(node) { if (node.loc && node.loc.start && trackNodes.has(node.type)) { const nodeLine = node.loc.start.line; const nodeColumn = node.loc.start.column - 1; if (original.line !== nodeLine || original.column !== nodeColumn) { original.line = nodeLine; original.column = nodeColumn; generated.line = line; generated.column = column; if (sourceMappingActive) { sourceMappingActive = false; if (generated.line !== activatedGenerated.line || generated.column !== activatedGenerated.column) { map.addMapping(activatedMapping); } } sourceMappingActive = true; map.addMapping({ source: node.loc.source, original, generated }); } } origHandlersNode.call(this, node); if (sourceMappingActive && trackNodes.has(node.type)) { activatedGenerated.line = line; activatedGenerated.column = column; } }; const origHandlersEmit = handlers.emit; handlers.emit = function(value, type, auto) { for (let i = 0; i < value.length; i++) { if (value.charCodeAt(i) === 10) { // \n line++; column = 0; } else { column++; } } origHandlersEmit(value, type, auto); }; const origHandlersResult = handlers.result; handlers.result = function() { if (sourceMappingActive) { map.addMapping(activatedMapping); } return { css: origHandlersResult(), map }; }; return handlers; } exports.generateSourceMap = generateSourceMap; /***/ }), /***/ 7284: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const types = __webpack_require__(4764); __webpack_require__(7154); const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) const code = (type, value) => { if (type === types.Delim) { type = value; } if (typeof type === 'string') { const charCode = type.charCodeAt(0); return charCode > 0x7F ? 0x8000 : charCode << 8; } return type; }; // https://www.w3.org/TR/css-syntax-3/#serialization // The only requirement for serialization is that it must "round-trip" with parsing, // that is, parsing the stylesheet must produce the same data structures as parsing, // serializing, and parsing again, except for consecutive s, // which may be collapsed into a single token. const specPairs = [ [types.Ident, types.Ident], [types.Ident, types.Function], [types.Ident, types.Url], [types.Ident, types.BadUrl], [types.Ident, '-'], [types.Ident, types.Number], [types.Ident, types.Percentage], [types.Ident, types.Dimension], [types.Ident, types.CDC], [types.Ident, types.LeftParenthesis], [types.AtKeyword, types.Ident], [types.AtKeyword, types.Function], [types.AtKeyword, types.Url], [types.AtKeyword, types.BadUrl], [types.AtKeyword, '-'], [types.AtKeyword, types.Number], [types.AtKeyword, types.Percentage], [types.AtKeyword, types.Dimension], [types.AtKeyword, types.CDC], [types.Hash, types.Ident], [types.Hash, types.Function], [types.Hash, types.Url], [types.Hash, types.BadUrl], [types.Hash, '-'], [types.Hash, types.Number], [types.Hash, types.Percentage], [types.Hash, types.Dimension], [types.Hash, types.CDC], [types.Dimension, types.Ident], [types.Dimension, types.Function], [types.Dimension, types.Url], [types.Dimension, types.BadUrl], [types.Dimension, '-'], [types.Dimension, types.Number], [types.Dimension, types.Percentage], [types.Dimension, types.Dimension], [types.Dimension, types.CDC], ['#', types.Ident], ['#', types.Function], ['#', types.Url], ['#', types.BadUrl], ['#', '-'], ['#', types.Number], ['#', types.Percentage], ['#', types.Dimension], ['#', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 ['-', types.Ident], ['-', types.Function], ['-', types.Url], ['-', types.BadUrl], ['-', '-'], ['-', types.Number], ['-', types.Percentage], ['-', types.Dimension], ['-', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 [types.Number, types.Ident], [types.Number, types.Function], [types.Number, types.Url], [types.Number, types.BadUrl], [types.Number, types.Number], [types.Number, types.Percentage], [types.Number, types.Dimension], [types.Number, '%'], [types.Number, types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 ['@', types.Ident], ['@', types.Function], ['@', types.Url], ['@', types.BadUrl], ['@', '-'], ['@', types.CDC], // https://github.com/w3c/csswg-drafts/pull/6874 ['.', types.Number], ['.', types.Percentage], ['.', types.Dimension], ['+', types.Number], ['+', types.Percentage], ['+', types.Dimension], ['/', '*'] ]; // validate with scripts/generate-safe const safePairs = specPairs.concat([ [types.Ident, types.Hash], [types.Dimension, types.Hash], [types.Hash, types.Hash], [types.AtKeyword, types.LeftParenthesis], [types.AtKeyword, types.String], [types.AtKeyword, types.Colon], [types.Percentage, types.Percentage], [types.Percentage, types.Dimension], [types.Percentage, types.Function], [types.Percentage, '-'], [types.RightParenthesis, types.Ident], [types.RightParenthesis, types.Function], [types.RightParenthesis, types.Percentage], [types.RightParenthesis, types.Dimension], [types.RightParenthesis, types.Hash], [types.RightParenthesis, '-'] ]); function createMap(pairs) { const isWhiteSpaceRequired = new Set( pairs.map(([prev, next]) => (code(prev) << 16 | code(next))) ); return function(prevCode, type, value) { const nextCode = code(type, value); const nextCharCode = value.charCodeAt(0); const emitWs = (nextCharCode === HYPHENMINUS && type !== types.Ident && type !== types.Function && type !== types.CDC) || (nextCharCode === PLUSSIGN) ? isWhiteSpaceRequired.has(prevCode << 16 | nextCharCode << 8) : isWhiteSpaceRequired.has(prevCode << 16 | nextCode); if (emitWs) { this.emit(' ', types.WhiteSpace, true); } return nextCode; }; } const spec = createMap(specPairs); const safe = createMap(safePairs); exports.safe = safe; exports.spec = spec; /***/ }), /***/ 3889: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const index$1 = __webpack_require__(4393); const version = __webpack_require__(9909); const create = __webpack_require__(3547); const List = __webpack_require__(2080); const Lexer = __webpack_require__(2636); const types = __webpack_require__(4764); __webpack_require__(7154); const names = __webpack_require__(7169); const TokenStream = __webpack_require__(7989); const index = __webpack_require__(7); const clone = __webpack_require__(6315); const names$1 = __webpack_require__(2543); const ident = __webpack_require__(8866); const string = __webpack_require__(1705); const url = __webpack_require__(213); const { tokenize, parse, generate, lexer, createLexer, walk, find, findLast, findAll, toPlainObject, fromPlainObject, fork } = index$1; exports.version = version.version; exports.createSyntax = create; exports.List = List.List; exports.Lexer = Lexer.Lexer; exports.tokenTypes = types; exports.tokenNames = names; exports.TokenStream = TokenStream.TokenStream; exports.definitionSyntax = index; exports.clone = clone.clone; exports.isCustomProperty = names$1.isCustomProperty; exports.keyword = names$1.keyword; exports.property = names$1.property; exports.vendorPrefix = names$1.vendorPrefix; exports.ident = ident; exports.string = string; exports.url = url; exports.createLexer = createLexer; exports.find = find; exports.findAll = findAll; exports.findLast = findLast; exports.fork = fork; exports.fromPlainObject = fromPlainObject; exports.generate = generate; exports.lexer = lexer; exports.parse = parse; exports.toPlainObject = toPlainObject; exports.tokenize = tokenize; exports.walk = walk; /***/ }), /***/ 2636: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const error = __webpack_require__(1345); const names = __webpack_require__(2543); const generic = __webpack_require__(8148); const generate = __webpack_require__(9931); const parse = __webpack_require__(8544); const walk = __webpack_require__(2388); const prepareTokens = __webpack_require__(7889); const matchGraph = __webpack_require__(4352); const match = __webpack_require__(3474); const trace = __webpack_require__(7991); const search = __webpack_require__(8152); const structure = __webpack_require__(91); const cssWideKeywords = matchGraph.buildMatchGraph('inherit | initial | unset'); const cssWideKeywordsWithExpression = matchGraph.buildMatchGraph('inherit | initial | unset | <-ms-legacy-expression>'); function dumpMapSyntax(map, compact, syntaxAsAst) { const result = {}; for (const name in map) { if (map[name].syntax) { result[name] = syntaxAsAst ? map[name].syntax : generate.generate(map[name].syntax, { compact }); } } return result; } function dumpAtruleMapSyntax(map, compact, syntaxAsAst) { const result = {}; for (const [name, atrule] of Object.entries(map)) { result[name] = { prelude: atrule.prelude && ( syntaxAsAst ? atrule.prelude.syntax : generate.generate(atrule.prelude.syntax, { compact }) ), descriptors: atrule.descriptors && dumpMapSyntax(atrule.descriptors, compact, syntaxAsAst) }; } return result; } function valueHasVar(tokens) { for (let i = 0; i < tokens.length; i++) { if (tokens[i].value.toLowerCase() === 'var(') { return true; } } return false; } function buildMatchResult(matched, error, iterations) { return { matched, iterations, error, ...trace }; } function matchSyntax(lexer, syntax, value, useCommon) { const tokens = prepareTokens(value, lexer.syntax); let result; if (valueHasVar(tokens)) { return buildMatchResult(null, new Error('Matching for a tree with var() is not supported')); } if (useCommon) { result = match.matchAsTree(tokens, lexer.valueCommonSyntax, lexer); } if (!useCommon || !result.match) { result = match.matchAsTree(tokens, syntax.match, lexer); if (!result.match) { return buildMatchResult( null, new error.SyntaxMatchError(result.reason, syntax.syntax, value, result), result.iterations ); } } return buildMatchResult(result.match, null, result.iterations); } class Lexer { constructor(config, syntax, structure$1) { this.valueCommonSyntax = cssWideKeywords; this.syntax = syntax; this.generic = false; this.atrules = Object.create(null); this.properties = Object.create(null); this.types = Object.create(null); this.structure = structure$1 || structure.getStructureFromConfig(config); if (config) { if (config.types) { for (const name in config.types) { this.addType_(name, config.types[name]); } } if (config.generic) { this.generic = true; for (const name in generic) { this.addType_(name, generic[name]); } } if (config.atrules) { for (const name in config.atrules) { this.addAtrule_(name, config.atrules[name]); } } if (config.properties) { for (const name in config.properties) { this.addProperty_(name, config.properties[name]); } } } } checkStructure(ast) { function collectWarning(node, message) { warns.push({ node, message }); } const structure = this.structure; const warns = []; this.syntax.walk(ast, function(node) { if (structure.hasOwnProperty(node.type)) { structure[node.type].check(node, collectWarning); } else { collectWarning(node, 'Unknown node type `' + node.type + '`'); } }); return warns.length ? warns : false; } createDescriptor(syntax, type, name, parent = null) { const ref = { type, name }; const descriptor = { type, name, parent, serializable: typeof syntax === 'string' || (syntax && typeof syntax.type === 'string'), syntax: null, match: null }; if (typeof syntax === 'function') { descriptor.match = matchGraph.buildMatchGraph(syntax, ref); } else { if (typeof syntax === 'string') { // lazy parsing on first access Object.defineProperty(descriptor, 'syntax', { get() { Object.defineProperty(descriptor, 'syntax', { value: parse.parse(syntax) }); return descriptor.syntax; } }); } else { descriptor.syntax = syntax; } // lazy graph build on first access Object.defineProperty(descriptor, 'match', { get() { Object.defineProperty(descriptor, 'match', { value: matchGraph.buildMatchGraph(descriptor.syntax, ref) }); return descriptor.match; } }); } return descriptor; } addAtrule_(name, syntax) { if (!syntax) { return; } this.atrules[name] = { type: 'Atrule', name: name, prelude: syntax.prelude ? this.createDescriptor(syntax.prelude, 'AtrulePrelude', name) : null, descriptors: syntax.descriptors ? Object.keys(syntax.descriptors).reduce( (map, descName) => { map[descName] = this.createDescriptor(syntax.descriptors[descName], 'AtruleDescriptor', descName, name); return map; }, Object.create(null) ) : null }; } addProperty_(name, syntax) { if (!syntax) { return; } this.properties[name] = this.createDescriptor(syntax, 'Property', name); } addType_(name, syntax) { if (!syntax) { return; } this.types[name] = this.createDescriptor(syntax, 'Type', name); if (syntax === generic['-ms-legacy-expression']) { this.valueCommonSyntax = cssWideKeywordsWithExpression; } } checkAtruleName(atruleName) { if (!this.getAtrule(atruleName)) { return new error.SyntaxReferenceError('Unknown at-rule', '@' + atruleName); } } checkAtrulePrelude(atruleName, prelude) { const error = this.checkAtruleName(atruleName); if (error) { return error; } const atrule = this.getAtrule(atruleName); if (!atrule.prelude && prelude) { return new SyntaxError('At-rule `@' + atruleName + '` should not contain a prelude'); } if (atrule.prelude && !prelude) { return new SyntaxError('At-rule `@' + atruleName + '` should contain a prelude'); } } checkAtruleDescriptorName(atruleName, descriptorName) { const error$1 = this.checkAtruleName(atruleName); if (error$1) { return error$1; } const atrule = this.getAtrule(atruleName); const descriptor = names.keyword(descriptorName); if (!atrule.descriptors) { return new SyntaxError('At-rule `@' + atruleName + '` has no known descriptors'); } if (!atrule.descriptors[descriptor.name] && !atrule.descriptors[descriptor.basename]) { return new error.SyntaxReferenceError('Unknown at-rule descriptor', descriptorName); } } checkPropertyName(propertyName) { if (!this.getProperty(propertyName)) { return new error.SyntaxReferenceError('Unknown property', propertyName); } } matchAtrulePrelude(atruleName, prelude) { const error = this.checkAtrulePrelude(atruleName, prelude); if (error) { return buildMatchResult(null, error); } if (!prelude) { return buildMatchResult(null, null); } return matchSyntax(this, this.getAtrule(atruleName).prelude, prelude, false); } matchAtruleDescriptor(atruleName, descriptorName, value) { const error = this.checkAtruleDescriptorName(atruleName, descriptorName); if (error) { return buildMatchResult(null, error); } const atrule = this.getAtrule(atruleName); const descriptor = names.keyword(descriptorName); return matchSyntax(this, atrule.descriptors[descriptor.name] || atrule.descriptors[descriptor.basename], value, false); } matchDeclaration(node) { if (node.type !== 'Declaration') { return buildMatchResult(null, new Error('Not a Declaration node')); } return this.matchProperty(node.property, node.value); } matchProperty(propertyName, value) { // don't match syntax for a custom property at the moment if (names.property(propertyName).custom) { return buildMatchResult(null, new Error('Lexer matching doesn\'t applicable for custom properties')); } const error = this.checkPropertyName(propertyName); if (error) { return buildMatchResult(null, error); } return matchSyntax(this, this.getProperty(propertyName), value, true); } matchType(typeName, value) { const typeSyntax = this.getType(typeName); if (!typeSyntax) { return buildMatchResult(null, new error.SyntaxReferenceError('Unknown type', typeName)); } return matchSyntax(this, typeSyntax, value, false); } match(syntax, value) { if (typeof syntax !== 'string' && (!syntax || !syntax.type)) { return buildMatchResult(null, new error.SyntaxReferenceError('Bad syntax')); } if (typeof syntax === 'string' || !syntax.match) { syntax = this.createDescriptor(syntax, 'Type', 'anonymous'); } return matchSyntax(this, syntax, value, false); } findValueFragments(propertyName, value, type, name) { return search.matchFragments(this, value, this.matchProperty(propertyName, value), type, name); } findDeclarationValueFragments(declaration, type, name) { return search.matchFragments(this, declaration.value, this.matchDeclaration(declaration), type, name); } findAllFragments(ast, type, name) { const result = []; this.syntax.walk(ast, { visit: 'Declaration', enter: (declaration) => { result.push.apply(result, this.findDeclarationValueFragments(declaration, type, name)); } }); return result; } getAtrule(atruleName, fallbackBasename = true) { const atrule = names.keyword(atruleName); const atruleEntry = atrule.vendor && fallbackBasename ? this.atrules[atrule.name] || this.atrules[atrule.basename] : this.atrules[atrule.name]; return atruleEntry || null; } getAtrulePrelude(atruleName, fallbackBasename = true) { const atrule = this.getAtrule(atruleName, fallbackBasename); return atrule && atrule.prelude || null; } getAtruleDescriptor(atruleName, name) { return this.atrules.hasOwnProperty(atruleName) && this.atrules.declarators ? this.atrules[atruleName].declarators[name] || null : null; } getProperty(propertyName, fallbackBasename = true) { const property = names.property(propertyName); const propertyEntry = property.vendor && fallbackBasename ? this.properties[property.name] || this.properties[property.basename] : this.properties[property.name]; return propertyEntry || null; } getType(name) { return hasOwnProperty.call(this.types, name) ? this.types[name] : null; } validate() { function validate(syntax, name, broken, descriptor) { if (broken.has(name)) { return broken.get(name); } broken.set(name, false); if (descriptor.syntax !== null) { walk.walk(descriptor.syntax, function(node) { if (node.type !== 'Type' && node.type !== 'Property') { return; } const map = node.type === 'Type' ? syntax.types : syntax.properties; const brokenMap = node.type === 'Type' ? brokenTypes : brokenProperties; if (!hasOwnProperty.call(map, node.name) || validate(syntax, node.name, brokenMap, map[node.name])) { broken.set(name, true); } }, this); } } let brokenTypes = new Map(); let brokenProperties = new Map(); for (const key in this.types) { validate(this, key, brokenTypes, this.types[key]); } for (const key in this.properties) { validate(this, key, brokenProperties, this.properties[key]); } brokenTypes = [...brokenTypes.keys()].filter(name => brokenTypes.get(name)); brokenProperties = [...brokenProperties.keys()].filter(name => brokenProperties.get(name)); if (brokenTypes.length || brokenProperties.length) { return { types: brokenTypes, properties: brokenProperties }; } return null; } dump(syntaxAsAst, pretty) { return { generic: this.generic, types: dumpMapSyntax(this.types, !pretty, syntaxAsAst), properties: dumpMapSyntax(this.properties, !pretty, syntaxAsAst), atrules: dumpAtruleMapSyntax(this.atrules, !pretty, syntaxAsAst) }; } toString() { return JSON.stringify(this.dump()); } } exports.Lexer = Lexer; /***/ }), /***/ 1345: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; const createCustomError = __webpack_require__(7324); const generate = __webpack_require__(9931); const defaultLoc = { offset: 0, line: 1, column: 1 }; function locateMismatch(matchResult, node) { const tokens = matchResult.tokens; const longestMatch = matchResult.longestMatch; const mismatchNode = longestMatch < tokens.length ? tokens[longestMatch].node || null : null; const badNode = mismatchNode !== node ? mismatchNode : null; let mismatchOffset = 0; let mismatchLength = 0; let entries = 0; let css = ''; let start; let end; for (let i = 0; i < tokens.length; i++) { const token = tokens[i].value; if (i === longestMatch) { mismatchLength = token.length; mismatchOffset = css.length; } if (badNode !== null && tokens[i].node === badNode) { if (i <= longestMatch) { entries++; } else { entries = 0; } } css += token; } if (longestMatch === tokens.length || entries > 1) { // last start = fromLoc(badNode || node, 'end') || buildLoc(defaultLoc, css); end = buildLoc(start); } else { start = fromLoc(badNode, 'start') || buildLoc(fromLoc(node, 'start') || defaultLoc, css.slice(0, mismatchOffset)); end = fromLoc(badNode, 'end') || buildLoc(start, css.substr(mismatchOffset, mismatchLength)); } return { css, mismatchOffset, mismatchLength, start, end }; } function fromLoc(node, point) { const value = node && node.loc && node.loc[point]; if (value) { return 'line' in value ? buildLoc(value) : value; } return null; } function buildLoc({ offset, line, column }, extra) { const loc = { offset, line, column }; if (extra) { const lines = extra.split(/\n|\r\n?|\f/); loc.offset += extra.length; loc.line += lines.length - 1; loc.column = lines.length === 1 ? loc.column + extra.length : lines.pop().length + 1; } return loc; } const SyntaxReferenceError = function(type, referenceName) { const error = createCustomError.createCustomError( 'SyntaxReferenceError', type + (referenceName ? ' `' + referenceName + '`' : '') ); error.reference = referenceName; return error; }; const SyntaxMatchError = function(message, syntax, node, matchResult) { const error = createCustomError.createCustomError('SyntaxMatchError', message); const { css, mismatchOffset, mismatchLength, start, end } = locateMismatch(matchResult, node); error.rawMessage = message; error.syntax = syntax ? generate.generate(syntax) : ''; error.css = css; error.mismatchOffset = mismatchOffset; error.mismatchLength = mismatchLength; error.message = message + '\n' + ' syntax: ' + error.syntax + '\n' + ' value: ' + (css || '') + '\n' + ' --------' + new Array(error.mismatchOffset + 1).join('-') + '^'; Object.assign(error, start); error.loc = { source: (node && node.loc && node.loc.source) || '', start, end }; return error; }; exports.SyntaxMatchError = SyntaxMatchError; exports.SyntaxReferenceError = SyntaxReferenceError; /***/ }), /***/ 5865: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const types = __webpack_require__(4764); const charCodeDefinitions = __webpack_require__(7154); const utils = __webpack_require__(9708); const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) const N = 0x006E; // U+006E LATIN SMALL LETTER N (n) const DISALLOW_SIGN = true; const ALLOW_SIGN = false; function isDelim(token, code) { return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code; } function skipSC(token, offset, getNextToken) { while (token !== null && (token.type === types.WhiteSpace || token.type === types.Comment)) { token = getNextToken(++offset); } return offset; } function checkInteger(token, valueOffset, disallowSign, offset) { if (!token) { return 0; } const code = token.value.charCodeAt(valueOffset); if (code === PLUSSIGN || code === HYPHENMINUS) { if (disallowSign) { // Number sign is not allowed return 0; } valueOffset++; } for (; valueOffset < token.value.length; valueOffset++) { if (!charCodeDefinitions.isDigit(token.value.charCodeAt(valueOffset))) { // Integer is expected return 0; } } return offset + 1; } // ... // ... ['+' | '-'] function consumeB(token, offset_, getNextToken) { let sign = false; let offset = skipSC(token, offset_, getNextToken); token = getNextToken(offset); if (token === null) { return offset_; } if (token.type !== types.Number) { if (isDelim(token, PLUSSIGN) || isDelim(token, HYPHENMINUS)) { sign = true; offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); if (token === null || token.type !== types.Number) { return 0; } } else { return offset_; } } if (!sign) { const code = token.value.charCodeAt(0); if (code !== PLUSSIGN && code !== HYPHENMINUS) { // Number sign is expected return 0; } } return checkInteger(token, sign ? 0 : 1, sign, offset); } // An+B microsyntax https://www.w3.org/TR/css-syntax-3/#anb function anPlusB(token, getNextToken) { /* eslint-disable brace-style*/ let offset = 0; if (!token) { return 0; } // if (token.type === types.Number) { return checkInteger(token, 0, ALLOW_SIGN, offset); // b } // -n // -n // -n ['+' | '-'] // -n- // else if (token.type === types.Ident && token.value.charCodeAt(0) === HYPHENMINUS) { // expect 1st char is N if (!utils.cmpChar(token.value, 1, N)) { return 0; } switch (token.value.length) { // -n // -n // -n ['+' | '-'] case 2: return consumeB(getNextToken(++offset), offset, getNextToken); // -n- case 3: if (token.value.charCodeAt(2) !== HYPHENMINUS) { return 0; } offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); return checkInteger(token, 0, DISALLOW_SIGN, offset); // default: if (token.value.charCodeAt(2) !== HYPHENMINUS) { return 0; } return checkInteger(token, 3, DISALLOW_SIGN, offset); } } // '+'? n // '+'? n // '+'? n ['+' | '-'] // '+'? n- // '+'? else if (token.type === types.Ident || (isDelim(token, PLUSSIGN) && getNextToken(offset + 1).type === types.Ident)) { // just ignore a plus if (token.type !== types.Ident) { token = getNextToken(++offset); } if (token === null || !utils.cmpChar(token.value, 0, N)) { return 0; } switch (token.value.length) { // '+'? n // '+'? n // '+'? n ['+' | '-'] case 1: return consumeB(getNextToken(++offset), offset, getNextToken); // '+'? n- case 2: if (token.value.charCodeAt(1) !== HYPHENMINUS) { return 0; } offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); return checkInteger(token, 0, DISALLOW_SIGN, offset); // '+'? default: if (token.value.charCodeAt(1) !== HYPHENMINUS) { return 0; } return checkInteger(token, 2, DISALLOW_SIGN, offset); } } // // // // // ['+' | '-'] else if (token.type === types.Dimension) { let code = token.value.charCodeAt(0); let sign = code === PLUSSIGN || code === HYPHENMINUS ? 1 : 0; let i = sign; for (; i < token.value.length; i++) { if (!charCodeDefinitions.isDigit(token.value.charCodeAt(i))) { break; } } if (i === sign) { // Integer is expected return 0; } if (!utils.cmpChar(token.value, i, N)) { return 0; } // // // ['+' | '-'] if (i + 1 === token.value.length) { return consumeB(getNextToken(++offset), offset, getNextToken); } else { if (token.value.charCodeAt(i + 1) !== HYPHENMINUS) { return 0; } // if (i + 2 === token.value.length) { offset = skipSC(getNextToken(++offset), offset, getNextToken); token = getNextToken(offset); return checkInteger(token, 0, DISALLOW_SIGN, offset); } // else { return checkInteger(token, i + 2, DISALLOW_SIGN, offset); } } } return 0; } module.exports = anPlusB; /***/ }), /***/ 6664: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const types = __webpack_require__(4764); const charCodeDefinitions = __webpack_require__(7154); const utils = __webpack_require__(9708); const PLUSSIGN = 0x002B; // U+002B PLUS SIGN (+) const HYPHENMINUS = 0x002D; // U+002D HYPHEN-MINUS (-) const QUESTIONMARK = 0x003F; // U+003F QUESTION MARK (?) const U = 0x0075; // U+0075 LATIN SMALL LETTER U (u) function isDelim(token, code) { return token !== null && token.type === types.Delim && token.value.charCodeAt(0) === code; } function startsWith(token, code) { return token.value.charCodeAt(0) === code; } function hexSequence(token, offset, allowDash) { let hexlen = 0; for (let pos = offset; pos < token.value.length; pos++) { const code = token.value.charCodeAt(pos); if (code === HYPHENMINUS && allowDash && hexlen !== 0) { hexSequence(token, offset + hexlen + 1, false); return 6; // dissallow following question marks } if (!charCodeDefinitions.isHexDigit(code)) { return 0; // not a hex digit } if (++hexlen > 6) { return 0; // too many hex digits } } return hexlen; } function withQuestionMarkSequence(consumed, length, getNextToken) { if (!consumed) { return 0; // nothing consumed } while (isDelim(getNextToken(length), QUESTIONMARK)) { if (++consumed > 6) { return 0; // too many question marks } length++; } return length; } // https://drafts.csswg.org/css-syntax/#urange // Informally, the production has three forms: // U+0001 // Defines a range consisting of a single code point, in this case the code point "1". // U+0001-00ff // Defines a range of codepoints between the first and the second value, in this case // the range between "1" and "ff" (255 in decimal) inclusive. // U+00?? // Defines a range of codepoints where the "?" characters range over all hex digits, // in this case defining the same as the value U+0000-00ff. // In each form, a maximum of 6 digits is allowed for each hexadecimal number (if you treat "?" as a hexadecimal digit). // // = // u '+' '?'* | // u '?'* | // u '?'* | // u | // u | // u '+' '?'+ function urange(token, getNextToken) { let length = 0; // should start with `u` or `U` if (token === null || token.type !== types.Ident || !utils.cmpChar(token.value, 0, U)) { return 0; } token = getNextToken(++length); if (token === null) { return 0; } // u '+' '?'* // u '+' '?'+ if (isDelim(token, PLUSSIGN)) { token = getNextToken(++length); if (token === null) { return 0; } if (token.type === types.Ident) { // u '+' '?'* return withQuestionMarkSequence(hexSequence(token, 0, true), ++length, getNextToken); } if (isDelim(token, QUESTIONMARK)) { // u '+' '?'+ return withQuestionMarkSequence(1, ++length, getNextToken); } // Hex digit or question mark is expected return 0; } // u '?'* // u // u if (token.type === types.Number) { const consumedHexLength = hexSequence(token, 1, true); if (consumedHexLength === 0) { return 0; } token = getNextToken(++length); if (token === null) { // u return length; } if (token.type === types.Dimension || token.type === types.Number) { // u // u if (!startsWith(token, HYPHENMINUS) || !hexSequence(token, 1, false)) { return 0; } return length + 1; } // u '?'* return withQuestionMarkSequence(consumedHexLength, length, getNextToken); } // u '?'* if (token.type === types.Dimension) { return withQuestionMarkSequence(hexSequence(token, 1, true), ++length, getNextToken); } return 0; } module.exports = urange; /***/ }), /***/ 8148: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; const genericAnPlusB = __webpack_require__(5865); const genericUrange = __webpack_require__(6664); const types = __webpack_require__(4764); const charCodeDefinitions = __webpack_require__(7154); const utils = __webpack_require__(9708); const cssWideKeywords = ['unset', 'initial', 'inherit']; const calcFunctionNames = ['calc(', '-moz-calc(', '-webkit-calc(']; const balancePair = new Map([ [types.Function, types.RightParenthesis], [types.LeftParenthesis, types.RightParenthesis], [types.LeftSquareBracket, types.RightSquareBracket], [types.LeftCurlyBracket, types.RightCurlyBracket] ]); // units const LENGTH = [ // https://www.w3.org/TR/css-values-3/#lengths 'px', 'mm', 'cm', 'in', 'pt', 'pc', 'q', // absolute length units 'em', 'ex', 'ch', 'rem', // relative length units 'vh', 'vw', 'vmin', 'vmax', 'vm' // viewport-percentage lengths ]; const ANGLE = ['deg', 'grad', 'rad', 'turn']; // https://www.w3.org/TR/css-values-3/#angles const TIME = ['s', 'ms']; // https://www.w3.org/TR/css-values-3/#time const FREQUENCY = ['hz', 'khz']; // https://www.w3.org/TR/css-values-3/#frequency const RESOLUTION = ['dpi', 'dpcm', 'dppx', 'x']; // https://www.w3.org/TR/css-values-3/#resolution const FLEX = ['fr']; // https://drafts.csswg.org/css-grid/#fr-unit const DECIBEL = ['db']; // https://www.w3.org/TR/css3-speech/#mixing-props-voice-volume const SEMITONES = ['st']; // https://www.w3.org/TR/css3-speech/#voice-props-voice-pitch // safe char code getter function charCodeAt(str, index) { return index < str.length ? str.charCodeAt(index) : 0; } function eqStr(actual, expected) { return utils.cmpStr(actual, 0, actual.length, expected); } function eqStrAny(actual, expected) { for (let i = 0; i < expected.length; i++) { if (eqStr(actual, expected[i])) { return true; } } return false; } // IE postfix hack, i.e. 123\0 or 123px\9 function isPostfixIeHack(str, offset) { if (offset !== str.length - 2) { return false; } return ( charCodeAt(str, offset) === 0x005C && // U+005C REVERSE SOLIDUS (\) charCodeDefinitions.isDigit(charCodeAt(str, offset + 1)) ); } function outOfRange(opts, value, numEnd) { if (opts && opts.type === 'Range') { const num = Number( numEnd !== undefined && numEnd !== value.length ? value.substr(0, numEnd) : value ); if (isNaN(num)) { return true; } if (opts.min !== null && num < opts.min) { return true; } if (opts.max !== null && num > opts.max) { return true; } } return false; } function consumeFunction(token, getNextToken) { let balanceCloseType = 0; let balanceStash = []; let length = 0; // balanced token consuming scan: do { switch (token.type) { case types.RightCurlyBracket: case types.RightParenthesis: case types.RightSquareBracket: if (token.type !== balanceCloseType) { break scan; } balanceCloseType = balanceStash.pop(); if (balanceStash.length === 0) { length++; break scan; } break; case types.Function: case types.LeftParenthesis: case types.LeftSquareBracket: case types.LeftCurlyBracket: balanceStash.push(balanceCloseType); balanceCloseType = balancePair.get(token.type); break; } length++; } while (token = getNextToken(length)); return length; } // TODO: implement // can be used wherever , , ,