/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 7351: /***/ (function(__unused_webpack_module, exports, __nccwpck_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(__nccwpck_require__(2037)); const utils_1 = __nccwpck_require__(5278); /** * 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 /***/ }), /***/ 2186: /***/ (function(__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(7351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); const os = __importStar(__nccwpck_require__(2037)); const path = __importStar(__nccwpck_require__(1017)); const oidc_utils_1 = __nccwpck_require__(8041); /** * 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) { return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } 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.issueFileCommand('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 !== ''); if (options && options.trimWhitespace === false) { return inputs; } return inputs.map(input => input.trim()); } 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) { const filePath = process.env['GITHUB_OUTPUT'] || ''; if (filePath) { return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); } process.stdout.write(os.EOL); command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(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) { const filePath = process.env['GITHUB_STATE'] || ''; if (filePath) { return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); } command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(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; /** * Summary exports */ var summary_1 = __nccwpck_require__(1327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ var summary_2 = __nccwpck_require__(1327); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports */ var path_utils_1 = __nccwpck_require__(2981); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); //# sourceMappingURL=core.js.map /***/ }), /***/ 717: /***/ (function(__unused_webpack_module, exports, __nccwpck_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.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(__nccwpck_require__(7147)); const os = __importStar(__nccwpck_require__(2037)); const uuid_1 = __nccwpck_require__(5840); const utils_1 = __nccwpck_require__(5278); function issueFileCommand(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.issueFileCommand = issueFileCommand; function prepareKeyValueMessage(key, value) { const delimiter = `ghadelimiter_${uuid_1.v4()}`; const convertedValue = utils_1.toCommandValue(value); // These should realistically never happen, but just in case someone finds a // way to exploit uuid generation let's not allow keys or values that contain // the delimiter. if (key.includes(delimiter)) { throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } if (convertedValue.includes(delimiter)) { throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; } exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), /***/ 8041: /***/ (function(__unused_webpack_module, exports, __nccwpck_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 = __nccwpck_require__(6255); const auth_1 = __nccwpck_require__(5526); const core_1 = __nccwpck_require__(2186); 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 /***/ }), /***/ 2981: /***/ (function(__unused_webpack_module, exports, __nccwpck_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.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; const path = __importStar(__nccwpck_require__(1017)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. * * @param pth. Path to transform. * @return string Posix path. */ function toPosixPath(pth) { return pth.replace(/[\\]/g, '/'); } exports.toPosixPath = toPosixPath; /** * toWin32Path converts the given path to the win32 form. On Linux, / will be * replaced with \\. * * @param pth. Path to transform. * @return string Win32 path. */ function toWin32Path(pth) { return pth.replace(/[/]/g, '\\'); } exports.toWin32Path = toWin32Path; /** * toPlatformPath converts the given path to a platform-specific path. It does * this by replacing instances of / and \ with the platform-specific path * separator. * * @param pth The path to platformize. * @return string The platform-specific path. */ function toPlatformPath(pth) { return pth.replace(/[/\\]/g, path.sep); } exports.toPlatformPath = toPlatformPath; //# sourceMappingURL=path-utils.js.map /***/ }), /***/ 1327: /***/ (function(__unused_webpack_module, exports, __nccwpck_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.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; const os_1 = __nccwpck_require__(2037); const fs_1 = __nccwpck_require__(7147); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; class Summary { constructor() { this._buffer = ''; } /** * Finds the summary file path from the environment, rejects if env var is not found or file does not exist * Also checks r/w permissions. * * @returns step summary file path */ filePath() { return __awaiter(this, void 0, void 0, function* () { if (this._filePath) { return this._filePath; } const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; if (!pathFromEnv) { throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); } try { yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); } catch (_a) { throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); } this._filePath = pathFromEnv; return this._filePath; }); } /** * Wraps content in an HTML tag, adding any HTML attributes * * @param {string} tag HTML tag to wrap * @param {string | null} content content within the tag * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add * * @returns {string} content wrapped in HTML element */ wrap(tag, content, attrs = {}) { const htmlAttrs = Object.entries(attrs) .map(([key, value]) => ` ${key}="${value}"`) .join(''); if (!content) { return `<${tag}${htmlAttrs}>`; } return `<${tag}${htmlAttrs}>${content}`; } /** * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. * * @param {SummaryWriteOptions} [options] (optional) options for write operation * * @returns {Promise} summary instance */ write(options) { return __awaiter(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); const writeFunc = overwrite ? writeFile : appendFile; yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); return this.emptyBuffer(); }); } /** * Clears the summary buffer and wipes the summary file * * @returns {Summary} summary instance */ clear() { return __awaiter(this, void 0, void 0, function* () { return this.emptyBuffer().write({ overwrite: true }); }); } /** * Returns the current summary buffer as a string * * @returns {string} string of summary buffer */ stringify() { return this._buffer; } /** * If the summary buffer is empty * * @returns {boolen} true if the buffer is empty */ isEmptyBuffer() { return this._buffer.length === 0; } /** * Resets the summary buffer without writing to summary file * * @returns {Summary} summary instance */ emptyBuffer() { this._buffer = ''; return this; } /** * Adds raw text to the summary buffer * * @param {string} text content to add * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) * * @returns {Summary} summary instance */ addRaw(text, addEOL = false) { this._buffer += text; return addEOL ? this.addEOL() : this; } /** * Adds the operating system-specific end-of-line marker to the buffer * * @returns {Summary} summary instance */ addEOL() { return this.addRaw(os_1.EOL); } /** * Adds an HTML codeblock to the summary buffer * * @param {string} code content to render within fenced code block * @param {string} lang (optional) language to syntax highlight code * * @returns {Summary} summary instance */ addCodeBlock(code, lang) { const attrs = Object.assign({}, (lang && { lang })); const element = this.wrap('pre', this.wrap('code', code), attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML list to the summary buffer * * @param {string[]} items list of items to render * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) * * @returns {Summary} summary instance */ addList(items, ordered = false) { const tag = ordered ? 'ol' : 'ul'; const listItems = items.map(item => this.wrap('li', item)).join(''); const element = this.wrap(tag, listItems); return this.addRaw(element).addEOL(); } /** * Adds an HTML table to the summary buffer * * @param {SummaryTableCell[]} rows table rows * * @returns {Summary} summary instance */ addTable(rows) { const tableBody = rows .map(row => { const cells = row .map(cell => { if (typeof cell === 'string') { return this.wrap('td', cell); } const { header, data, colspan, rowspan } = cell; const tag = header ? 'th' : 'td'; const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); return this.wrap(tag, data, attrs); }) .join(''); return this.wrap('tr', cells); }) .join(''); const element = this.wrap('table', tableBody); return this.addRaw(element).addEOL(); } /** * Adds a collapsable HTML details element to the summary buffer * * @param {string} label text for the closed state * @param {string} content collapsable content * * @returns {Summary} summary instance */ addDetails(label, content) { const element = this.wrap('details', this.wrap('summary', label) + content); return this.addRaw(element).addEOL(); } /** * Adds an HTML image tag to the summary buffer * * @param {string} src path to the image you to embed * @param {string} alt text description of the image * @param {SummaryImageOptions} options (optional) addition image attributes * * @returns {Summary} summary instance */ addImage(src, alt, options) { const { width, height } = options || {}; const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); return this.addRaw(element).addEOL(); } /** * Adds an HTML section heading element * * @param {string} text heading text * @param {number | string} [level=1] (optional) the heading level, default: 1 * * @returns {Summary} summary instance */ addHeading(text, level) { const tag = `h${level}`; const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) ? tag : 'h1'; const element = this.wrap(allowedTag, text); return this.addRaw(element).addEOL(); } /** * Adds an HTML thematic break (
) to the summary buffer * * @returns {Summary} summary instance */ addSeparator() { const element = this.wrap('hr', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML line break (
) to the summary buffer * * @returns {Summary} summary instance */ addBreak() { const element = this.wrap('br', null); return this.addRaw(element).addEOL(); } /** * Adds an HTML blockquote to the summary buffer * * @param {string} text quote text * @param {string} cite (optional) citation url * * @returns {Summary} summary instance */ addQuote(text, cite) { const attrs = Object.assign({}, (cite && { cite })); const element = this.wrap('blockquote', text, attrs); return this.addRaw(element).addEOL(); } /** * Adds an HTML anchor tag to the summary buffer * * @param {string} text link text/content * @param {string} href hyperlink * * @returns {Summary} summary instance */ addLink(text, href) { const element = this.wrap('a', text, { href }); return this.addRaw(element).addEOL(); } } const _summary = new Summary(); /** * @deprecated use `core.summary` */ exports.markdownSummary = _summary; exports.summary = _summary; //# sourceMappingURL=summary.js.map /***/ }), /***/ 5278: /***/ ((__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 /***/ }), /***/ 5526: /***/ (function(__unused_webpack_module, exports) { "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.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; class BasicCredentialHandler { constructor(username, password) { this.username = username; this.password = password; } prepareRequest(options) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } 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) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Bearer ${this.token}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } 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) { if (!options.headers) { throw Error('The request has no headers'); } options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; } // This handler cannot handle 401 canHandleAuthentication() { return false; } handleAuthentication() { return __awaiter(this, void 0, void 0, function* () { throw new Error('not implemented'); }); } } exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; //# sourceMappingURL=auth.js.map /***/ }), /***/ 6255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; /* eslint-disable @typescript-eslint/no-explicit-any */ 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.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; const http = __importStar(__nccwpck_require__(3685)); const https = __importStar(__nccwpck_require__(5687)); const pm = __importStar(__nccwpck_require__(9835)); const tunnel = __importStar(__nccwpck_require__(4294)); 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) { const 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 __awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { 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) { const 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 __awaiter(this, void 0, void 0, function* () { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); }); } get(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('GET', requestUrl, null, additionalHeaders || {}); }); } del(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('DELETE', requestUrl, null, additionalHeaders || {}); }); } post(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('POST', requestUrl, data, additionalHeaders || {}); }); } patch(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PATCH', requestUrl, data, additionalHeaders || {}); }); } put(requestUrl, data, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('PUT', requestUrl, data, additionalHeaders || {}); }); } head(requestUrl, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { return this.request('HEAD', requestUrl, null, additionalHeaders || {}); }); } sendStream(verb, requestUrl, stream, additionalHeaders) { return __awaiter(this, void 0, void 0, function* () { 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 */ getJson(requestUrl, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); const res = yield this.get(requestUrl, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } postJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const 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); const res = yield this.post(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } putJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const 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); const res = yield this.put(requestUrl, data, additionalHeaders); return this._processResponse(res, this.requestOptions); }); } patchJson(requestUrl, obj, additionalHeaders = {}) { return __awaiter(this, void 0, void 0, function* () { const 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); const res = yield 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 */ request(verb, requestUrl, data, headers) { return __awaiter(this, void 0, void 0, function* () { if (this._disposed) { throw new Error('Client has already been disposed.'); } const parsedUrl = new URL(requestUrl); let info = this._prepareRequest(verb, parsedUrl, headers); // Only perform retries on reads since writes may not be idempotent. const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) ? this._maxRetries + 1 : 1; let numTries = 0; let response; do { response = yield this.requestRaw(info, data); // Check if it's an authentication challenge if (response && response.message && response.message.statusCode === HttpCodes.Unauthorized) { let authenticationHandler; for (const handler of this.handlers) { if (handler.canHandleAuthentication(response)) { authenticationHandler = handler; 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 (response.message.statusCode && HttpRedirectCodes.includes(response.message.statusCode) && this._allowRedirects && redirectsRemaining > 0) { const redirectUrl = response.message.headers['location']; if (!redirectUrl) { // if there's no location to redirect to, we won't break; } const 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. yield response.readBody(); // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (const 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 = yield this.requestRaw(info, data); redirectsRemaining--; } if (!response.message.statusCode || !HttpResponseRetryCodes.includes(response.message.statusCode)) { // If not a retry code, return immediately instead of retrying return response; } numTries += 1; if (numTries < maxTries) { yield response.readBody(); yield this._performExponentialBackoff(numTries); } } while (numTries < maxTries); 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 __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { function callbackForResult(err, res) { if (err) { reject(err); } else if (!res) { // If `err` is not passed, then `res` must be passed. reject(new Error('Unknown error')); } else { resolve(res); } } this.requestRawWithCallback(info, data, callbackForResult); }); }); } /** * Raw request with callback. * @param info * @param data * @param onResult */ requestRawWithCallback(info, data, onResult) { if (typeof data === 'string') { if (!info.options.headers) { info.options.headers = {}; } info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); } let callbackCalled = false; function handleResult(err, res) { if (!callbackCalled) { callbackCalled = true; onResult(err, res); } } const req = info.httpModule.request(info.options, (msg) => { const res = new HttpClientResponse(msg); handleResult(undefined, res); }); let socket; 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}`)); }); req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err); }); 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) { const 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) { for (const handler of this.handlers) { handler.prepareRequest(info.options); } } return info; } _mergeHeaders(headers) { if (this.requestOptions && this.requestOptions.headers) { return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); } return lowercaseKeys(headers || {}); } _getExistingOrDefaultHeader(additionalHeaders, header, _default) { let clientHeader; if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; } return additionalHeaders[header] || clientHeader || _default; } _getAgent(parsedUrl) { let agent; const proxyUrl = pm.getProxyUrl(parsedUrl); const 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; } // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. if (proxyUrl && proxyUrl.hostname) { const agentOptions = { maxSockets, keepAlive: this._keepAlive, proxy: Object.assign(Object.assign({}, ((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 }; 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) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); return new Promise(resolve => setTimeout(() => resolve(), ms)); }); } _processResponse(res, options) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const statusCode = res.message.statusCode || 0; const response = { statusCode, result: null, headers: {} }; // not found leads to null obj returned if (statusCode === HttpCodes.NotFound) { resolve(response); } // get the result from the body function dateTimeDeserializer(key, value) { if (typeof value === 'string') { const a = new Date(value); if (!isNaN(a.valueOf())) { return a; } } return value; } let obj; let contents; try { contents = yield res.readBody(); if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, 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})`; } const err = new HttpClientError(msg, statusCode); err.result = response.result; reject(err); } else { resolve(response); } })); }); } } exports.HttpClient = HttpClient; const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); //# sourceMappingURL=index.js.map /***/ }), /***/ 9835: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.checkBypass = exports.getProxyUrl = void 0; function getProxyUrl(reqUrl) { const usingSsl = reqUrl.protocol === 'https:'; if (checkBypass(reqUrl)) { return undefined; } const proxyVar = (() => { if (usingSsl) { return process.env['https_proxy'] || process.env['HTTPS_PROXY']; } else { return process.env['http_proxy'] || process.env['HTTP_PROXY']; } })(); if (proxyVar) { return new URL(proxyVar); } else { return undefined; } } exports.getProxyUrl = getProxyUrl; function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } const 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 const upperReqHosts = [reqUrl.hostname.toUpperCase()]; if (typeof reqPort === 'number') { upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } // Compare request host against noproxy for (const 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; //# sourceMappingURL=proxy.js.map /***/ }), /***/ 3803: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = __nccwpck_require__(7147); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; /***/ }), /***/ 8838: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); const SUPPORTED_MAJOR_VERSION = 10; const SUPPORTED_MINOR_VERSION = 10; const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; /** * IS `true` for Node.js 10.10 and greater. */ exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; /***/ }), /***/ 5667: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.scandirSync = exports.scandir = void 0; const async = __nccwpck_require__(4507); const sync = __nccwpck_require__(9560); const settings_1 = __nccwpck_require__(8662); exports.Settings = settings_1.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.scandir = scandir; function scandirSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.scandirSync = scandirSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } /***/ }), /***/ 4507: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; const fsStat = __nccwpck_require__(109); const rpl = __nccwpck_require__(5288); const constants_1 = __nccwpck_require__(8838); const utils = __nccwpck_require__(6297); const common = __nccwpck_require__(3847); function read(directory, settings, callback) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { readdirWithFileTypes(directory, settings, callback); return; } readdir(directory, settings, callback); } exports.read = read; function readdirWithFileTypes(directory, settings, callback) { settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { if (readdirError !== null) { callFailureCallback(callback, readdirError); return; } const entries = dirents.map((dirent) => ({ dirent, name: dirent.name, path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) })); if (!settings.followSymbolicLinks) { callSuccessCallback(callback, entries); return; } const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); rpl(tasks, (rplError, rplEntries) => { if (rplError !== null) { callFailureCallback(callback, rplError); return; } callSuccessCallback(callback, rplEntries); }); }); } exports.readdirWithFileTypes = readdirWithFileTypes; function makeRplTaskEntry(entry, settings) { return (done) => { if (!entry.dirent.isSymbolicLink()) { done(null, entry); return; } settings.fs.stat(entry.path, (statError, stats) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { done(statError); return; } done(null, entry); return; } entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); done(null, entry); }); }; } function readdir(directory, settings, callback) { settings.fs.readdir(directory, (readdirError, names) => { if (readdirError !== null) { callFailureCallback(callback, readdirError); return; } const tasks = names.map((name) => { const path = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); return (done) => { fsStat.stat(path, settings.fsStatSettings, (error, stats) => { if (error !== null) { done(error); return; } const entry = { name, path, dirent: utils.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } done(null, entry); }); }; }); rpl(tasks, (rplError, entries) => { if (rplError !== null) { callFailureCallback(callback, rplError); return; } callSuccessCallback(callback, entries); }); }); } exports.readdir = readdir; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, result) { callback(null, result); } /***/ }), /***/ 3847: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPathSegments = void 0; function joinPathSegments(a, b, separator) { /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } exports.joinPathSegments = joinPathSegments; /***/ }), /***/ 9560: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; const fsStat = __nccwpck_require__(109); const constants_1 = __nccwpck_require__(8838); const utils = __nccwpck_require__(6297); const common = __nccwpck_require__(3847); function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { return readdirWithFileTypes(directory, settings); } return readdir(directory, settings); } exports.read = read; function readdirWithFileTypes(directory, settings) { const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); return dirents.map((dirent) => { const entry = { dirent, name: dirent.name, path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) }; if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { try { const stats = settings.fs.statSync(entry.path); entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); } catch (error) { if (settings.throwErrorOnBrokenSymbolicLink) { throw error; } } } return entry; }); } exports.readdirWithFileTypes = readdirWithFileTypes; function readdir(directory, settings) { const names = settings.fs.readdirSync(directory); return names.map((name) => { const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); const stats = fsStat.statSync(entryPath, settings.fsStatSettings); const entry = { name, path: entryPath, dirent: utils.fs.createDirentFromStats(name, stats) }; if (settings.stats) { entry.stats = stats; } return entry; }); } exports.readdir = readdir; /***/ }), /***/ 8662: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(1017); const fsStat = __nccwpck_require__(109); const fs = __nccwpck_require__(3803); class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); this.fs = fs.createFileSystemAdapter(this._options.fs); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); this.stats = this._getValue(this._options.stats, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); this.fsStatSettings = new fsStat.Settings({ followSymbolicLink: this.followSymbolicLinks, fs: this.fs, throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports["default"] = Settings; /***/ }), /***/ 883: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } exports.createDirentFromStats = createDirentFromStats; /***/ }), /***/ 6297: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fs = void 0; const fs = __nccwpck_require__(883); exports.fs = fs; /***/ }), /***/ 2987: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; const fs = __nccwpck_require__(7147); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, lstatSync: fs.lstatSync, statSync: fs.statSync }; function createFileSystemAdapter(fsMethods) { if (fsMethods === undefined) { return exports.FILE_SYSTEM_ADAPTER; } return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } exports.createFileSystemAdapter = createFileSystemAdapter; /***/ }), /***/ 109: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.statSync = exports.stat = exports.Settings = void 0; const async = __nccwpck_require__(4147); const sync = __nccwpck_require__(4527); const settings_1 = __nccwpck_require__(2410); exports.Settings = settings_1.default; function stat(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { async.read(path, getSettings(), optionsOrSettingsOrCallback); return; } async.read(path, getSettings(optionsOrSettingsOrCallback), callback); } exports.stat = stat; function statSync(path, optionsOrSettings) { const settings = getSettings(optionsOrSettings); return sync.read(path, settings); } exports.statSync = statSync; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } /***/ }), /***/ 4147: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.read = void 0; function read(path, settings, callback) { settings.fs.lstat(path, (lstatError, lstat) => { if (lstatError !== null) { callFailureCallback(callback, lstatError); return; } if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { callSuccessCallback(callback, lstat); return; } settings.fs.stat(path, (statError, stat) => { if (statError !== null) { if (settings.throwErrorOnBrokenSymbolicLink) { callFailureCallback(callback, statError); return; } callSuccessCallback(callback, lstat); return; } if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } callSuccessCallback(callback, stat); }); }); } exports.read = read; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, result) { callback(null, result); } /***/ }), /***/ 4527: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.read = void 0; function read(path, settings) { const lstat = settings.fs.lstatSync(path); if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { return lstat; } try { const stat = settings.fs.statSync(path); if (settings.markSymbolicLink) { stat.isSymbolicLink = () => true; } return stat; } catch (error) { if (!settings.throwErrorOnBrokenSymbolicLink) { return lstat; } throw error; } } exports.read = read; /***/ }), /***/ 2410: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fs = __nccwpck_require__(2987); class Settings { constructor(_options = {}) { this._options = _options; this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); this.fs = fs.createFileSystemAdapter(this._options.fs); this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports["default"] = Settings; /***/ }), /***/ 6026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; const async_1 = __nccwpck_require__(7523); const stream_1 = __nccwpck_require__(6737); const sync_1 = __nccwpck_require__(3068); const settings_1 = __nccwpck_require__(141); exports.Settings = settings_1.default; function walk(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); return; } new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); } exports.walk = walk; function walkSync(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new sync_1.default(directory, settings); return provider.read(); } exports.walkSync = walkSync; function walkStream(directory, optionsOrSettings) { const settings = getSettings(optionsOrSettings); const provider = new stream_1.default(directory, settings); return provider.read(); } exports.walkStream = walkStream; function getSettings(settingsOrOptions = {}) { if (settingsOrOptions instanceof settings_1.default) { return settingsOrOptions; } return new settings_1.default(settingsOrOptions); } /***/ }), /***/ 7523: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const async_1 = __nccwpck_require__(7664); class AsyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1.default(this._root, this._settings); this._storage = []; } read(callback) { this._reader.onError((error) => { callFailureCallback(callback, error); }); this._reader.onEntry((entry) => { this._storage.push(entry); }); this._reader.onEnd(() => { callSuccessCallback(callback, this._storage); }); this._reader.read(); } } exports["default"] = AsyncProvider; function callFailureCallback(callback, error) { callback(error); } function callSuccessCallback(callback, entries) { callback(null, entries); } /***/ }), /***/ 6737: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __nccwpck_require__(2781); const async_1 = __nccwpck_require__(7664); class StreamProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new async_1.default(this._root, this._settings); this._stream = new stream_1.Readable({ objectMode: true, read: () => { }, destroy: () => { if (!this._reader.isDestroyed) { this._reader.destroy(); } } }); } read() { this._reader.onError((error) => { this._stream.emit('error', error); }); this._reader.onEntry((entry) => { this._stream.push(entry); }); this._reader.onEnd(() => { this._stream.push(null); }); this._reader.read(); return this._stream; } } exports["default"] = StreamProvider; /***/ }), /***/ 3068: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const sync_1 = __nccwpck_require__(3595); class SyncProvider { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._reader = new sync_1.default(this._root, this._settings); } read() { return this._reader.read(); } } exports["default"] = SyncProvider; /***/ }), /***/ 7664: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const events_1 = __nccwpck_require__(2361); const fsScandir = __nccwpck_require__(5667); const fastq = __nccwpck_require__(7340); const common = __nccwpck_require__(7988); const reader_1 = __nccwpck_require__(8311); class AsyncReader extends reader_1.default { constructor(_root, _settings) { super(_root, _settings); this._settings = _settings; this._scandir = fsScandir.scandir; this._emitter = new events_1.EventEmitter(); this._queue = fastq(this._worker.bind(this), this._settings.concurrency); this._isFatalError = false; this._isDestroyed = false; this._queue.drain = () => { if (!this._isFatalError) { this._emitter.emit('end'); } }; } read() { this._isFatalError = false; this._isDestroyed = false; setImmediate(() => { this._pushToQueue(this._root, this._settings.basePath); }); return this._emitter; } get isDestroyed() { return this._isDestroyed; } destroy() { if (this._isDestroyed) { throw new Error('The reader is already destroyed'); } this._isDestroyed = true; this._queue.killAndDrain(); } onEntry(callback) { this._emitter.on('entry', callback); } onError(callback) { this._emitter.once('error', callback); } onEnd(callback) { this._emitter.once('end', callback); } _pushToQueue(directory, base) { const queueItem = { directory, base }; this._queue.push(queueItem, (error) => { if (error !== null) { this._handleError(error); } }); } _worker(item, done) { this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { if (error !== null) { done(error, undefined); return; } for (const entry of entries) { this._handleEntry(entry, item.base); } done(null, undefined); }); } _handleError(error) { if (this._isDestroyed || !common.isFatalError(this._settings, error)) { return; } this._isFatalError = true; this._isDestroyed = true; this._emitter.emit('error', error); } _handleEntry(entry, base) { if (this._isDestroyed || this._isFatalError) { return; } const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._emitEntry(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _emitEntry(entry) { this._emitter.emit('entry', entry); } } exports["default"] = AsyncReader; /***/ }), /***/ 7988: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = void 0; function isFatalError(settings, error) { if (settings.errorFilter === null) { return true; } return !settings.errorFilter(error); } exports.isFatalError = isFatalError; function isAppliedFilter(filter, value) { return filter === null || filter(value); } exports.isAppliedFilter = isAppliedFilter; function replacePathSegmentSeparator(filepath, separator) { return filepath.split(/[/\\]/).join(separator); } exports.replacePathSegmentSeparator = replacePathSegmentSeparator; function joinPathSegments(a, b, separator) { if (a === '') { return b; } /** * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). */ if (a.endsWith(separator)) { return a + b; } return a + separator + b; } exports.joinPathSegments = joinPathSegments; /***/ }), /***/ 8311: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const common = __nccwpck_require__(7988); class Reader { constructor(_root, _settings) { this._root = _root; this._settings = _settings; this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); } } exports["default"] = Reader; /***/ }), /***/ 3595: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsScandir = __nccwpck_require__(5667); const common = __nccwpck_require__(7988); const reader_1 = __nccwpck_require__(8311); class SyncReader extends reader_1.default { constructor() { super(...arguments); this._scandir = fsScandir.scandirSync; this._storage = []; this._queue = new Set(); } read() { this._pushToQueue(this._root, this._settings.basePath); this._handleQueue(); return this._storage; } _pushToQueue(directory, base) { this._queue.add({ directory, base }); } _handleQueue() { for (const item of this._queue.values()) { this._handleDirectory(item.directory, item.base); } } _handleDirectory(directory, base) { try { const entries = this._scandir(directory, this._settings.fsScandirSettings); for (const entry of entries) { this._handleEntry(entry, base); } } catch (error) { this._handleError(error); } } _handleError(error) { if (!common.isFatalError(this._settings, error)) { return; } throw error; } _handleEntry(entry, base) { const fullpath = entry.path; if (base !== undefined) { entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } if (common.isAppliedFilter(this._settings.entryFilter, entry)) { this._pushToStorage(entry); } if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } } _pushToStorage(entry) { this._storage.push(entry); } } exports["default"] = SyncReader; /***/ }), /***/ 141: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(1017); const fsScandir = __nccwpck_require__(5667); class Settings { constructor(_options = {}) { this._options = _options; this.basePath = this._getValue(this._options.basePath, undefined); this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); this.deepFilter = this._getValue(this._options.deepFilter, null); this.entryFilter = this._getValue(this._options.entryFilter, null); this.errorFilter = this._getValue(this._options.errorFilter, null); this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path.sep); this.fsScandirSettings = new fsScandir.Settings({ followSymbolicLinks: this._options.followSymbolicLinks, fs: this._options.fs, pathSegmentSeparator: this._options.pathSegmentSeparator, stats: this._options.stats, throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink }); } _getValue(option, value) { return option !== null && option !== void 0 ? option : value; } } exports["default"] = Settings; /***/ }), /***/ 610: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const stringify = __nccwpck_require__(8750); const compile = __nccwpck_require__(9434); const expand = __nccwpck_require__(5873); const parse = __nccwpck_require__(6477); /** * Expand the given pattern or create a regex-compatible string. * * ```js * const braces = require('braces'); * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] * ``` * @param {String} `str` * @param {Object} `options` * @return {String} * @api public */ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { for (let pattern of input) { let result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { output.push(result); } } } else { output = [].concat(braces.create(input, options)); } if (options && options.expand === true && options.nodupes === true) { output = [...new Set(output)]; } return output; }; /** * Parse the given `str` with the given `options`. * * ```js * // braces.parse(pattern, [, options]); * const ast = braces.parse('a/{b,c}/d'); * console.log(ast); * ``` * @param {String} pattern Brace pattern to parse * @param {Object} options * @return {Object} Returns an AST * @api public */ braces.parse = (input, options = {}) => parse(input, options); /** * Creates a braces string from an AST, or an AST node. * * ```js * const braces = require('braces'); * let ast = braces.parse('foo/{a,b}/bar'); * console.log(stringify(ast.nodes[2])); //=> '{a,b}' * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.stringify = (input, options = {}) => { if (typeof input === 'string') { return stringify(braces.parse(input, options), options); } return stringify(input, options); }; /** * Compiles a brace pattern into a regex-compatible, optimized string. * This method is called by the main [braces](#braces) function by default. * * ```js * const braces = require('braces'); * console.log(braces.compile('a/{b,c}/d')); * //=> ['a/(b|c)/d'] * ``` * @param {String} `input` Brace pattern or AST. * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.compile = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } return compile(input, options); }; /** * Expands a brace pattern into an array. This method is called by the * main [braces](#braces) function when `options.expand` is true. Before * using this method it's recommended that you read the [performance notes](#performance)) * and advantages of using [.compile](#compile) instead. * * ```js * const braces = require('braces'); * console.log(braces.expand('a/{b,c}/d')); * //=> ['a/b/d', 'a/c/d']; * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.expand = (input, options = {}) => { if (typeof input === 'string') { input = braces.parse(input, options); } let result = expand(input, options); // filter out empty strings if specified if (options.noempty === true) { result = result.filter(Boolean); } // filter out duplicates if specified if (options.nodupes === true) { result = [...new Set(result)]; } return result; }; /** * Processes a brace pattern and returns either an expanded array * (if `options.expand` is true), a highly optimized regex-compatible string. * This method is called by the main [braces](#braces) function. * * ```js * const braces = require('braces'); * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' * ``` * @param {String} `pattern` Brace pattern * @param {Object} `options` * @return {Array} Returns an array of expanded values. * @api public */ braces.create = (input, options = {}) => { if (input === '' || input.length < 3) { return [input]; } return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; /** * Expose "braces" */ module.exports = braces; /***/ }), /***/ 9434: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const fill = __nccwpck_require__(6330); const utils = __nccwpck_require__(5207); const compile = (ast, options = {}) => { let walk = (node, parent = {}) => { let invalidBlock = utils.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let invalid = invalidBlock === true || invalidNode === true; let prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } if (node.isClose === true) { return prefix + node.value; } if (node.type === 'open') { return invalid ? (prefix + node.value) : '('; } if (node.type === 'close') { return invalid ? (prefix + node.value) : ')'; } if (node.type === 'comma') { return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); } if (node.value) { return node.value; } if (node.nodes && node.ranges > 0) { let args = utils.reduce(node.nodes); let range = fill(...args, { ...options, wrap: false, toRegex: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; } } if (node.nodes) { for (let child of node.nodes) { output += walk(child, node); } } return output; }; return walk(ast); }; module.exports = compile; /***/ }), /***/ 4600: /***/ ((module) => { "use strict"; module.exports = { MAX_LENGTH: 1024 * 64, // Digits CHAR_0: '0', /* 0 */ CHAR_9: '9', /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 'A', /* A */ CHAR_LOWERCASE_A: 'a', /* a */ CHAR_UPPERCASE_Z: 'Z', /* Z */ CHAR_LOWERCASE_Z: 'z', /* z */ CHAR_LEFT_PARENTHESES: '(', /* ( */ CHAR_RIGHT_PARENTHESES: ')', /* ) */ CHAR_ASTERISK: '*', /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: '&', /* & */ CHAR_AT: '@', /* @ */ CHAR_BACKSLASH: '\\', /* \ */ CHAR_BACKTICK: '`', /* ` */ CHAR_CARRIAGE_RETURN: '\r', /* \r */ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ CHAR_COLON: ':', /* : */ CHAR_COMMA: ',', /* , */ CHAR_DOLLAR: '$', /* . */ CHAR_DOT: '.', /* . */ CHAR_DOUBLE_QUOTE: '"', /* " */ CHAR_EQUAL: '=', /* = */ CHAR_EXCLAMATION_MARK: '!', /* ! */ CHAR_FORM_FEED: '\f', /* \f */ CHAR_FORWARD_SLASH: '/', /* / */ CHAR_HASH: '#', /* # */ CHAR_HYPHEN_MINUS: '-', /* - */ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ CHAR_LEFT_CURLY_BRACE: '{', /* { */ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ CHAR_LINE_FEED: '\n', /* \n */ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ CHAR_PERCENT: '%', /* % */ CHAR_PLUS: '+', /* + */ CHAR_QUESTION_MARK: '?', /* ? */ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ CHAR_RIGHT_CURLY_BRACE: '}', /* } */ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ CHAR_SEMICOLON: ';', /* ; */ CHAR_SINGLE_QUOTE: '\'', /* ' */ CHAR_SPACE: ' ', /* */ CHAR_TAB: '\t', /* \t */ CHAR_UNDERSCORE: '_', /* _ */ CHAR_VERTICAL_LINE: '|', /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ }; /***/ }), /***/ 5873: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const fill = __nccwpck_require__(6330); const stringify = __nccwpck_require__(8750); const utils = __nccwpck_require__(5207); const append = (queue = '', stash = '', enclose = false) => { let result = []; queue = [].concat(queue); stash = [].concat(stash); if (!stash.length) return queue; if (!queue.length) { return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; } for (let item of queue) { if (Array.isArray(item)) { for (let value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); } } } return utils.flatten(result); }; const expand = (ast, options = {}) => { let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; let walk = (node, parent = {}) => { node.queue = []; let p = parent; let q = parent.queue; while (p.type !== 'brace' && p.type !== 'root' && p.parent) { p = p.parent; q = p.queue; } if (node.invalid || node.dollar) { q.push(append(q.pop(), stringify(node, options))); return; } if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { q.push(append(q.pop(), ['{}'])); return; } if (node.nodes && node.ranges > 0) { let args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); } let range = fill(...args, options); if (range.length === 0) { range = stringify(node, options); } q.push(append(q.pop(), range)); node.nodes = []; return; } let enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; while (block.type !== 'brace' && block.type !== 'root' && block.parent) { block = block.parent; queue = block.queue; } for (let i = 0; i < node.nodes.length; i++) { let child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); queue.push(''); continue; } if (child.type === 'close') { q.push(append(q.pop(), queue, enclose)); continue; } if (child.value && child.type !== 'open') { queue.push(append(queue.pop(), child.value)); continue; } if (child.nodes) { walk(child, node); } } return queue; }; return utils.flatten(walk(ast)); }; module.exports = expand; /***/ }), /***/ 6477: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const stringify = __nccwpck_require__(8750); /** * Constants */ const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = __nccwpck_require__(4600); /** * parse */ const parse = (input, options = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } let opts = options || {}; let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } let ast = { type: 'root', input, nodes: [] }; let stack = [ast]; let block = ast; let prev = ast; let brackets = 0; let length = input.length; let index = 0; let depth = 0; let value; let memo = {}; /** * Helpers */ const advance = () => input[index++]; const push = node => { if (node.type === 'text' && prev.type === 'dot') { prev.type = 'text'; } if (prev && prev.type === 'text' && node.type === 'text') { prev.value += node.value; return; } block.nodes.push(node); node.parent = block; node.prev = prev; prev = node; return node; }; push({ type: 'bos' }); while (index < length) { block = stack[stack.length - 1]; value = advance(); /** * Invalid chars */ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } /** * Escaped chars */ if (value === CHAR_BACKSLASH) { push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); continue; } /** * Right square bracket (literal): ']' */ if (value === CHAR_RIGHT_SQUARE_BRACKET) { push({ type: 'text', value: '\\' + value }); continue; } /** * Left square bracket: '[' */ if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; let closed = true; let next; while (index < length && (next = advance())) { value += next; if (next === CHAR_LEFT_SQUARE_BRACKET) { brackets++; continue; } if (next === CHAR_BACKSLASH) { value += advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { brackets--; if (brackets === 0) { break; } } } push({ type: 'text', value }); continue; } /** * Parentheses */ if (value === CHAR_LEFT_PARENTHESES) { block = push({ type: 'paren', nodes: [] }); stack.push(block); push({ type: 'text', value }); continue; } if (value === CHAR_RIGHT_PARENTHESES) { if (block.type !== 'paren') { push({ type: 'text', value }); continue; } block = stack.pop(); push({ type: 'text', value }); block = stack[stack.length - 1]; continue; } /** * Quotes: '|"|` */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { let open = value; let next; if (options.keepQuotes !== true) { value = ''; } while (index < length && (next = advance())) { if (next === CHAR_BACKSLASH) { value += next + advance(); continue; } if (next === open) { if (options.keepQuotes === true) value += next; break; } value += next; } push({ type: 'text', value }); continue; } /** * Left curly brace: '{' */ if (value === CHAR_LEFT_CURLY_BRACE) { depth++; let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; let brace = { type: 'brace', open: true, close: false, dollar, depth, commas: 0, ranges: 0, nodes: [] }; block = push(brace); stack.push(block); push({ type: 'open', value }); continue; } /** * Right curly brace: '}' */ if (value === CHAR_RIGHT_CURLY_BRACE) { if (block.type !== 'brace') { push({ type: 'text', value }); continue; } let type = 'close'; block = stack.pop(); block.close = true; push({ type, value }); depth--; block = stack[stack.length - 1]; continue; } /** * Comma: ',' */ if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; let open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify(block) }]; } push({ type: 'comma', value }); block.commas++; continue; } /** * Dot: '.' */ if (value === CHAR_DOT && depth > 0 && block.commas === 0) { let siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); continue; } if (prev.type === 'dot') { block.range = []; prev.value += value; prev.type = 'range'; if (block.nodes.length !== 3 && block.nodes.length !== 5) { block.invalid = true; block.ranges = 0; prev.type = 'text'; continue; } block.ranges++; block.args = []; continue; } if (prev.type === 'range') { siblings.pop(); let before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; continue; } push({ type: 'dot', value }); continue; } /** * Text */ push({ type: 'text', value }); } // Mark imbalanced braces and brackets as invalid do { block = stack.pop(); if (block.type !== 'root') { block.nodes.forEach(node => { if (!node.nodes) { if (node.type === 'open') node.isOpen = true; if (node.type === 'close') node.isClose = true; if (!node.nodes) node.type = 'text'; node.invalid = true; } }); // get the location of the block on parent.nodes (block's siblings) let parent = stack[stack.length - 1]; let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } } while (stack.length > 0); push({ type: 'eos' }); return ast; }; module.exports = parse; /***/ }), /***/ 8750: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const utils = __nccwpck_require__(5207); module.exports = (ast, options = {}) => { let stringify = (node, parent = {}) => { let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); let invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { return '\\' + node.value; } return node.value; } if (node.value) { return node.value; } if (node.nodes) { for (let child of node.nodes) { output += stringify(child); } } return output; }; return stringify(ast); }; /***/ }), /***/ 5207: /***/ ((__unused_webpack_module, exports) => { "use strict"; exports.isInteger = num => { if (typeof num === 'number') { return Number.isInteger(num); } if (typeof num === 'string' && num.trim() !== '') { return Number.isInteger(Number(num)); } return false; }; /** * Find a node of the given type */ exports.find = (node, type) => node.nodes.find(node => node.type === type); /** * Find a node of the given type */ exports.exceedsLimit = (min, max, step = 1, limit) => { if (limit === false) return false; if (!exports.isInteger(min) || !exports.isInteger(max)) return false; return ((Number(max) - Number(min)) / Number(step)) >= limit; }; /** * Escape the given node with '\\' before node.value */ exports.escapeNode = (block, n = 0, type) => { let node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { if (node.escaped !== true) { node.value = '\\' + node.value; node.escaped = true; } } }; /** * Returns true if the given brace node should be enclosed in literal braces */ exports.encloseBrace = node => { if (node.type !== 'brace') return false; if ((node.commas >> 0 + node.ranges >> 0) === 0) { node.invalid = true; return true; } return false; }; /** * Returns true if a brace node is invalid. */ exports.isInvalidBrace = block => { if (block.type !== 'brace') return false; if (block.invalid === true || block.dollar) return true; if ((block.commas >> 0 + block.ranges >> 0) === 0) { block.invalid = true; return true; } if (block.open !== true || block.close !== true) { block.invalid = true; return true; } return false; }; /** * Returns true if a node is an open or close node */ exports.isOpenOrClose = node => { if (node.type === 'open' || node.type === 'close') { return true; } return node.open === true || node.close === true; }; /** * Reduce an array of text nodes. */ exports.reduce = nodes => nodes.reduce((acc, node) => { if (node.type === 'text') acc.push(node.value); if (node.type === 'range') node.type = 'text'; return acc; }, []); /** * Flatten an array */ exports.flatten = (...args) => { const result = []; const flat = arr => { for (let i = 0; i < arr.length; i++) { let ele = arr[i]; Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); } return result; }; flat(args); return result; }; /***/ }), /***/ 2738: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(1017); const pathType = __nccwpck_require__(3433); const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; const getPath = (filepath, cwd) => { const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; return path.isAbsolute(pth) ? pth : path.join(cwd, pth); }; const addExtensions = (file, extensions) => { if (path.extname(file)) { return `**/${file}`; } return `**/${file}.${getExtensions(extensions)}`; }; const getGlob = (directory, options) => { if (options.files && !Array.isArray(options.files)) { throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); } if (options.extensions && !Array.isArray(options.extensions)) { throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); } if (options.files && options.extensions) { return options.files.map(x => path.posix.join(directory, addExtensions(x, options.extensions))); } if (options.files) { return options.files.map(x => path.posix.join(directory, `**/${x}`)); } if (options.extensions) { return [path.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; } return [path.posix.join(directory, '**')]; }; module.exports = async (input, options) => { options = { cwd: process.cwd(), ...options }; if (typeof options.cwd !== 'string') { throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); } const globs = await Promise.all([].concat(input).map(async x => { const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); return isDirectory ? getGlob(x, options) : x; })); return [].concat.apply([], globs); // eslint-disable-line prefer-spread }; module.exports.sync = (input, options) => { options = { cwd: process.cwd(), ...options }; if (typeof options.cwd !== 'string') { throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); } const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); return [].concat.apply([], globs); // eslint-disable-line prefer-spread }; /***/ }), /***/ 3664: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const taskManager = __nccwpck_require__(2708); const patternManager = __nccwpck_require__(8306); const async_1 = __nccwpck_require__(5679); const stream_1 = __nccwpck_require__(4630); const sync_1 = __nccwpck_require__(2405); const settings_1 = __nccwpck_require__(952); const utils = __nccwpck_require__(5444); async function FastGlob(source, options) { assertPatternsInput(source); const works = getWorks(source, async_1.default, options); const result = await Promise.all(works); return utils.array.flatten(result); } // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { function sync(source, options) { assertPatternsInput(source); const works = getWorks(source, sync_1.default, options); return utils.array.flatten(works); } FastGlob.sync = sync; function stream(source, options) { assertPatternsInput(source); const works = getWorks(source, stream_1.default, options); /** * The stream returned by the provider cannot work with an asynchronous iterator. * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. * This affects performance (+25%). I don't see best solution right now. */ return utils.stream.merge(works); } FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput(source); const patterns = patternManager.transform([].concat(source)); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } FastGlob.generateTasks = generateTasks; function isDynamicPattern(source, options) { assertPatternsInput(source); const settings = new settings_1.default(options); return utils.pattern.isDynamicPattern(source, settings); } FastGlob.isDynamicPattern = isDynamicPattern; function escapePath(source) { assertPatternsInput(source); return utils.path.escape(source); } FastGlob.escapePath = escapePath; })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { const patterns = patternManager.transform([].concat(source)); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); return tasks.map(provider.read, provider); } function assertPatternsInput(input) { const source = [].concat(input); const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); if (!isValidSource) { throw new TypeError('Patterns must be a string (non empty) or an array of strings'); } } module.exports = FastGlob; /***/ }), /***/ 8306: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.removeDuplicateSlashes = exports.transform = void 0; /** * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. * The latter is due to the presence of the device path at the beginning of the UNC path. * @todo rewrite to negative lookbehind with the next major release. */ const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; function transform(patterns) { return patterns.map((pattern) => removeDuplicateSlashes(pattern)); } exports.transform = transform; /** * This package only works with forward slashes as a path separator. * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. */ function removeDuplicateSlashes(pattern) { return pattern.replace(DOUBLE_SLASH_RE, '/'); } exports.removeDuplicateSlashes = removeDuplicateSlashes; /***/ }), /***/ 2708: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; const utils = __nccwpck_require__(5444); function generate(patterns, settings) { const positivePatterns = getPositivePatterns(patterns); const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); return staticTasks.concat(dynamicTasks); } exports.generate = generate; /** * Returns tasks grouped by basic pattern directories. * * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. * This is necessary because directory traversal starts at the base directory and goes deeper. */ function convertPatternsToTasks(positive, negative, dynamic) { const tasks = []; const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); /* * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. */ if ('.' in insideCurrentDirectoryGroup) { tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); } else { tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); } return tasks; } exports.convertPatternsToTasks = convertPatternsToTasks; function getPositivePatterns(patterns) { return utils.pattern.getPositivePatterns(patterns); } exports.getPositivePatterns = getPositivePatterns; function getNegativePatternsAsPositive(patterns, ignore) { const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); const positive = negative.map(utils.pattern.convertToPositivePattern); return positive; } exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; function groupPatternsByBaseDirectory(patterns) { const group = {}; return patterns.reduce((collection, pattern) => { const base = utils.pattern.getBaseDirectory(pattern); if (base in collection) { collection[base].push(pattern); } else { collection[base] = [pattern]; } return collection; }, group); } exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; function convertPatternGroupsToTasks(positive, negative, dynamic) { return Object.keys(positive).map((base) => { return convertPatternGroupToTask(base, positive[base], negative, dynamic); }); } exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; function convertPatternGroupToTask(base, positive, negative, dynamic) { return { dynamic, positive, negative, base, patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) }; } exports.convertPatternGroupToTask = convertPatternGroupToTask; /***/ }), /***/ 5679: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const async_1 = __nccwpck_require__(7747); const provider_1 = __nccwpck_require__(257); class ProviderAsync extends provider_1.default { constructor() { super(...arguments); this._reader = new async_1.default(this._settings); } async read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = await this.api(root, task, options); return entries.map((entry) => options.transform(entry)); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } exports["default"] = ProviderAsync; /***/ }), /***/ 6983: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(5444); const partial_1 = __nccwpck_require__(5295); class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; } getFilter(basePath, positive, negative) { const matcher = this._getMatcher(positive); const negativeRe = this._getNegativePatternsRe(negative); return (entry) => this._filter(basePath, entry, matcher, negativeRe); } _getMatcher(patterns) { return new partial_1.default(patterns, this._settings, this._micromatchOptions); } _getNegativePatternsRe(patterns) { const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); } _filter(basePath, entry, matcher, negativeRe) { if (this._isSkippedByDeep(basePath, entry.path)) { return false; } if (this._isSkippedSymbolicLink(entry)) { return false; } const filepath = utils.path.removeLeadingDotSegment(entry.path); if (this._isSkippedByPositivePatterns(filepath, matcher)) { return false; } return this._isSkippedByNegativePatterns(filepath, negativeRe); } _isSkippedByDeep(basePath, entryPath) { /** * Avoid unnecessary depth calculations when it doesn't matter. */ if (this._settings.deep === Infinity) { return false; } return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; } _getEntryLevel(basePath, entryPath) { const entryPathDepth = entryPath.split('/').length; if (basePath === '') { return entryPathDepth; } const basePathDepth = basePath.split('/').length; return entryPathDepth - basePathDepth; } _isSkippedSymbolicLink(entry) { return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); } _isSkippedByPositivePatterns(entryPath, matcher) { return !this._settings.baseNameMatch && !matcher.match(entryPath); } _isSkippedByNegativePatterns(entryPath, patternsRe) { return !utils.pattern.matchAny(entryPath, patternsRe); } } exports["default"] = DeepFilter; /***/ }), /***/ 1343: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(5444); class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; this._micromatchOptions = _micromatchOptions; this.index = new Map(); } getFilter(positive, negative) { const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions); return (entry) => this._filter(entry, positiveRe, negativeRe); } _filter(entry, positiveRe, negativeRe) { if (this._settings.unique && this._isDuplicateEntry(entry)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { return false; } const filepath = this._settings.baseNameMatch ? entry.name : entry.path; const isDirectory = entry.dirent.isDirectory(); const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(entry.path, negativeRe, isDirectory); if (this._settings.unique && isMatched) { this._createIndexRecord(entry); } return isMatched; } _isDuplicateEntry(entry) { return this.index.has(entry.path); } _createIndexRecord(entry) { this.index.set(entry.path, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); } _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { if (!this._settings.absolute) { return false; } const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); return utils.pattern.matchAny(fullpath, patternsRe); } _isMatchToPatterns(entryPath, patternsRe, isDirectory) { const filepath = utils.path.removeLeadingDotSegment(entryPath); // Trying to match files and directories by patterns. const isMatched = utils.pattern.matchAny(filepath, patternsRe); // A pattern with a trailling slash can be used for directory matching. // To apply such pattern, we need to add a tralling slash to the path. if (!isMatched && isDirectory) { return utils.pattern.matchAny(filepath + '/', patternsRe); } return isMatched; } } exports["default"] = EntryFilter; /***/ }), /***/ 6654: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(5444); class ErrorFilter { constructor(_settings) { this._settings = _settings; } getFilter() { return (error) => this._isNonFatalError(error); } _isNonFatalError(error) { return utils.errno.isEnoentCodeError(error) || this._settings.suppressErrors; } } exports["default"] = ErrorFilter; /***/ }), /***/ 2576: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(5444); class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; this._settings = _settings; this._micromatchOptions = _micromatchOptions; this._storage = []; this._fillStorage(); } _fillStorage() { /** * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). * So, before expand patterns with brace expansion into separated patterns. */ const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns); for (const pattern of patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ complete: sections.length <= 1, pattern, segments, sections }); } } _getPatternSegments(pattern) { const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); return parts.map((part) => { const dynamic = utils.pattern.isDynamicPattern(part, this._settings); if (!dynamic) { return { dynamic: false, pattern: part }; } return { dynamic: true, pattern: part, patternRe: utils.pattern.makeRe(part, this._micromatchOptions) }; }); } _splitSegmentsIntoSections(segments) { return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); } } exports["default"] = Matcher; /***/ }), /***/ 5295: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const matcher_1 = __nccwpck_require__(2576); class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); const levels = parts.length; const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); for (const pattern of patterns) { const section = pattern.sections[0]; /** * In this case, the pattern has a globstar and we must read all directories unconditionally, * but only if the level has reached the end of the first group. * * fixtures/{a,b}/** * ^ true/false ^ always true */ if (!pattern.complete && levels > section.length) { return true; } const match = parts.every((part, index) => { const segment = pattern.segments[index]; if (segment.dynamic && segment.patternRe.test(part)) { return true; } if (!segment.dynamic && segment.pattern === part) { return true; } return false; }); if (match) { return true; } } return false; } } exports["default"] = PartialMatcher; /***/ }), /***/ 257: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(1017); const deep_1 = __nccwpck_require__(6983); const entry_1 = __nccwpck_require__(1343); const error_1 = __nccwpck_require__(6654); const entry_2 = __nccwpck_require__(4029); class Provider { constructor(_settings) { this._settings = _settings; this.errorFilter = new error_1.default(this._settings); this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); this.entryTransformer = new entry_2.default(this._settings); } _getRootDirectory(task) { return path.resolve(this._settings.cwd, task.base); } _getReaderOptions(task) { const basePath = task.base === '.' ? '' : task.base; return { basePath, pathSegmentSeparator: '/', concurrency: this._settings.concurrency, deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), entryFilter: this.entryFilter.getFilter(task.positive, task.negative), errorFilter: this.errorFilter.getFilter(), followSymbolicLinks: this._settings.followSymbolicLinks, fs: this._settings.fs, stats: this._settings.stats, throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, transform: this.entryTransformer.getTransformer() }; } _getMicromatchOptions() { return { dot: this._settings.dot, matchBase: this._settings.baseNameMatch, nobrace: !this._settings.braceExpansion, nocase: !this._settings.caseSensitiveMatch, noext: !this._settings.extglob, noglobstar: !this._settings.globstar, posix: true, strictSlashes: false }; } } exports["default"] = Provider; /***/ }), /***/ 4630: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __nccwpck_require__(2781); const stream_2 = __nccwpck_require__(2083); const provider_1 = __nccwpck_require__(257); class ProviderStream extends provider_1.default { constructor() { super(...arguments); this._reader = new stream_2.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const source = this.api(root, task, options); const destination = new stream_1.Readable({ objectMode: true, read: () => { } }); source .once('error', (error) => destination.emit('error', error)) .on('data', (entry) => destination.emit('data', options.transform(entry))) .once('end', () => destination.emit('end')); destination .once('close', () => source.destroy()); return destination; } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } exports["default"] = ProviderStream; /***/ }), /***/ 2405: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const sync_1 = __nccwpck_require__(6234); const provider_1 = __nccwpck_require__(257); class ProviderSync extends provider_1.default { constructor() { super(...arguments); this._reader = new sync_1.default(this._settings); } read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); const entries = this.api(root, task, options); return entries.map(options.transform); } api(root, task, options) { if (task.dynamic) { return this._reader.dynamic(root, options); } return this._reader.static(task.patterns, options); } } exports["default"] = ProviderSync; /***/ }), /***/ 4029: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const utils = __nccwpck_require__(5444); class EntryTransformer { constructor(_settings) { this._settings = _settings; } getTransformer() { return (entry) => this._transform(entry); } _transform(entry) { let filepath = entry.path; if (this._settings.absolute) { filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); filepath = utils.path.unixify(filepath); } if (this._settings.markDirectories && entry.dirent.isDirectory()) { filepath += '/'; } if (!this._settings.objectMode) { return filepath; } return Object.assign(Object.assign({}, entry), { path: filepath }); } } exports["default"] = EntryTransformer; /***/ }), /***/ 7747: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsWalk = __nccwpck_require__(6026); const reader_1 = __nccwpck_require__(5582); const stream_1 = __nccwpck_require__(2083); class ReaderAsync extends reader_1.default { constructor() { super(...arguments); this._walkAsync = fsWalk.walk; this._readerStream = new stream_1.default(this._settings); } dynamic(root, options) { return new Promise((resolve, reject) => { this._walkAsync(root, options, (error, entries) => { if (error === null) { resolve(entries); } else { reject(error); } }); }); } async static(patterns, options) { const entries = []; const stream = this._readerStream.static(patterns, options); // After #235, replace it with an asynchronous iterator. return new Promise((resolve, reject) => { stream.once('error', reject); stream.on('data', (entry) => entries.push(entry)); stream.once('end', () => resolve(entries)); }); } } exports["default"] = ReaderAsync; /***/ }), /***/ 5582: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const path = __nccwpck_require__(1017); const fsStat = __nccwpck_require__(109); const utils = __nccwpck_require__(5444); class Reader { constructor(_settings) { this._settings = _settings; this._fsStatSettings = new fsStat.Settings({ followSymbolicLink: this._settings.followSymbolicLinks, fs: this._settings.fs, throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks }); } _getFullEntryPath(filepath) { return path.resolve(this._settings.cwd, filepath); } _makeEntry(stats, pattern) { const entry = { name: pattern, path: pattern, dirent: utils.fs.createDirentFromStats(pattern, stats) }; if (this._settings.stats) { entry.stats = stats; } return entry; } _isFatalError(error) { return !utils.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; } } exports["default"] = Reader; /***/ }), /***/ 2083: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const stream_1 = __nccwpck_require__(2781); const fsStat = __nccwpck_require__(109); const fsWalk = __nccwpck_require__(6026); const reader_1 = __nccwpck_require__(5582); class ReaderStream extends reader_1.default { constructor() { super(...arguments); this._walkStream = fsWalk.walkStream; this._stat = fsStat.stat; } dynamic(root, options) { return this._walkStream(root, options); } static(patterns, options) { const filepaths = patterns.map(this._getFullEntryPath, this); const stream = new stream_1.PassThrough({ objectMode: true }); stream._write = (index, _enc, done) => { return this._getEntry(filepaths[index], patterns[index], options) .then((entry) => { if (entry !== null && options.entryFilter(entry)) { stream.push(entry); } if (index === filepaths.length - 1) { stream.end(); } done(); }) .catch(done); }; for (let i = 0; i < filepaths.length; i++) { stream.write(i); } return stream; } _getEntry(filepath, pattern, options) { return this._getStat(filepath) .then((stats) => this._makeEntry(stats, pattern)) .catch((error) => { if (options.errorFilter(error)) { return null; } throw error; }); } _getStat(filepath) { return new Promise((resolve, reject) => { this._stat(filepath, this._fsStatSettings, (error, stats) => { return error === null ? resolve(stats) : reject(error); }); }); } } exports["default"] = ReaderStream; /***/ }), /***/ 6234: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); const fsStat = __nccwpck_require__(109); const fsWalk = __nccwpck_require__(6026); const reader_1 = __nccwpck_require__(5582); class ReaderSync extends reader_1.default { constructor() { super(...arguments); this._walkSync = fsWalk.walkSync; this._statSync = fsStat.statSync; } dynamic(root, options) { return this._walkSync(root, options); } static(patterns, options) { const entries = []; for (const pattern of patterns) { const filepath = this._getFullEntryPath(pattern); const entry = this._getEntry(filepath, pattern, options); if (entry === null || !options.entryFilter(entry)) { continue; } entries.push(entry); } return entries; } _getEntry(filepath, pattern, options) { try { const stats = this._getStat(filepath); return this._makeEntry(stats, pattern); } catch (error) { if (options.errorFilter(error)) { return null; } throw error; } } _getStat(filepath) { return this._statSync(filepath, this._fsStatSettings); } } exports["default"] = ReaderSync; /***/ }), /***/ 952: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; const fs = __nccwpck_require__(7147); const os = __nccwpck_require__(2037); /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 */ const CPU_COUNT = Math.max(os.cpus().length, 1); exports.DEFAULT_FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, lstatSync: fs.lstatSync, stat: fs.stat, statSync: fs.statSync, readdir: fs.readdir, readdirSync: fs.readdirSync }; class Settings { constructor(_options = {}) { this._options = _options; this.absolute = this._getValue(this._options.absolute, false); this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); this.braceExpansion = this._getValue(this._options.braceExpansion, true); this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); this.cwd = this._getValue(this._options.cwd, process.cwd()); this.deep = this._getValue(this._options.deep, Infinity); this.dot = this._getValue(this._options.dot, false); this.extglob = this._getValue(this._options.extglob, true); this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); this.fs = this._getFileSystemMethods(this._options.fs); this.globstar = this._getValue(this._options.globstar, true); this.ignore = this._getValue(this._options.ignore, []); this.markDirectories = this._getValue(this._options.markDirectories, false); this.objectMode = this._getValue(this._options.objectMode, false); this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); this.onlyFiles = this._getValue(this._options.onlyFiles, true); this.stats = this._getValue(this._options.stats, false); this.suppressErrors = this._getValue(this._options.suppressErrors, false); this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); this.unique = this._getValue(this._options.unique, true); if (this.onlyDirectories) { this.onlyFiles = false; } if (this.stats) { this.objectMode = true; } } _getValue(option, value) { return option === undefined ? value : option; } _getFileSystemMethods(methods = {}) { return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); } } exports["default"] = Settings; /***/ }), /***/ 5325: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.splitWhen = exports.flatten = void 0; function flatten(items) { return items.reduce((collection, item) => [].concat(collection, item), []); } exports.flatten = flatten; function splitWhen(items, predicate) { const result = [[]]; let groupIndex = 0; for (const item of items) { if (predicate(item)) { groupIndex++; result[groupIndex] = []; } else { result[groupIndex].push(item); } } return result; } exports.splitWhen = splitWhen; /***/ }), /***/ 1230: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isEnoentCodeError = void 0; function isEnoentCodeError(error) { return error.code === 'ENOENT'; } exports.isEnoentCodeError = isEnoentCodeError; /***/ }), /***/ 7543: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDirentFromStats = void 0; class DirentFromStats { constructor(name, stats) { this.name = name; this.isBlockDevice = stats.isBlockDevice.bind(stats); this.isCharacterDevice = stats.isCharacterDevice.bind(stats); this.isDirectory = stats.isDirectory.bind(stats); this.isFIFO = stats.isFIFO.bind(stats); this.isFile = stats.isFile.bind(stats); this.isSocket = stats.isSocket.bind(stats); this.isSymbolicLink = stats.isSymbolicLink.bind(stats); } } function createDirentFromStats(name, stats) { return new DirentFromStats(name, stats); } exports.createDirentFromStats = createDirentFromStats; /***/ }), /***/ 5444: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; const array = __nccwpck_require__(5325); exports.array = array; const errno = __nccwpck_require__(1230); exports.errno = errno; const fs = __nccwpck_require__(7543); exports.fs = fs; const path = __nccwpck_require__(3873); exports.path = path; const pattern = __nccwpck_require__(1221); exports.pattern = pattern; const stream = __nccwpck_require__(8382); exports.stream = stream; const string = __nccwpck_require__(2203); exports.string = string; /***/ }), /***/ 3873: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; const path = __nccwpck_require__(1017); const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; /** * Designed to work only with simple paths: `dir\\file`. */ function unixify(filepath) { return filepath.replace(/\\/g, '/'); } exports.unixify = unixify; function makeAbsolute(cwd, filepath) { return path.resolve(cwd, filepath); } exports.makeAbsolute = makeAbsolute; function escape(pattern) { return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); } exports.escape = escape; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with if (entry.charAt(0) === '.') { const secondCharactery = entry.charAt(1); if (secondCharactery === '/' || secondCharactery === '\\') { return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } } return entry; } exports.removeLeadingDotSegment = removeLeadingDotSegment; /***/ }), /***/ 1221: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; const path = __nccwpck_require__(1017); const globParent = __nccwpck_require__(4655); const micromatch = __nccwpck_require__(6228); const GLOBSTAR = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } exports.isStaticPattern = isStaticPattern; function isDynamicPattern(pattern, options = {}) { /** * A special case with an empty string is necessary for matching patterns that start with a forward slash. * An empty string cannot be a dynamic pattern. * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. */ if (pattern === '') { return false; } /** * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check * filepath directly (without read directory). */ if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { return true; } if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { return true; } if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { return true; } if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { return true; } return false; } exports.isDynamicPattern = isDynamicPattern; function hasBraceExpansion(pattern) { const openingBraceIndex = pattern.indexOf('{'); if (openingBraceIndex === -1) { return false; } const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); if (closingBraceIndex === -1) { return false; } const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); } function convertToPositivePattern(pattern) { return isNegativePattern(pattern) ? pattern.slice(1) : pattern; } exports.convertToPositivePattern = convertToPositivePattern; function convertToNegativePattern(pattern) { return '!' + pattern; } exports.convertToNegativePattern = convertToNegativePattern; function isNegativePattern(pattern) { return pattern.startsWith('!') && pattern[1] !== '('; } exports.isNegativePattern = isNegativePattern; function isPositivePattern(pattern) { return !isNegativePattern(pattern); } exports.isPositivePattern = isPositivePattern; function getNegativePatterns(patterns) { return patterns.filter(isNegativePattern); } exports.getNegativePatterns = getNegativePatterns; function getPositivePatterns(patterns) { return patterns.filter(isPositivePattern); } exports.getPositivePatterns = getPositivePatterns; /** * Returns patterns that can be applied inside the current directory. * * @example * // ['./*', '*', 'a/*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsInsideCurrentDirectory(patterns) { return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); } exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; /** * Returns patterns to be expanded relative to (outside) the current directory. * * @example * // ['../*', './../*'] * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) */ function getPatternsOutsideCurrentDirectory(patterns) { return patterns.filter(isPatternRelatedToParentDirectory); } exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; function isPatternRelatedToParentDirectory(pattern) { return pattern.startsWith('..') || pattern.startsWith('./..'); } exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; function getBaseDirectory(pattern) { return globParent(pattern, { flipBackslashes: false }); } exports.getBaseDirectory = getBaseDirectory; function hasGlobStar(pattern) { return pattern.includes(GLOBSTAR); } exports.hasGlobStar = hasGlobStar; function endsWithSlashGlobStar(pattern) { return pattern.endsWith('/' + GLOBSTAR); } exports.endsWithSlashGlobStar = endsWithSlashGlobStar; function isAffectDepthOfReadingPattern(pattern) { const basename = path.basename(pattern); return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); } exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; function expandPatternsWithBraceExpansion(patterns) { return patterns.reduce((collection, pattern) => { return collection.concat(expandBraceExpansion(pattern)); }, []); } exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { return micromatch.braces(pattern, { expand: true, nodupes: true }); } exports.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); /** * The scan method returns an empty array in some cases. * See micromatch/picomatch#58 for more details. */ if (parts.length === 0) { parts = [pattern]; } /** * The scan method does not return an empty part for the pattern with a forward slash. * This is another part of micromatch/picomatch#58. */ if (parts[0].startsWith('/')) { parts[0] = parts[0].slice(1); parts.unshift(''); } return parts; } exports.getPatternParts = getPatternParts; function makeRe(pattern, options) { return micromatch.makeRe(pattern, options); } exports.makeRe = makeRe; function convertPatternsToRe(patterns, options) { return patterns.map((pattern) => makeRe(pattern, options)); } exports.convertPatternsToRe = convertPatternsToRe; function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } exports.matchAny = matchAny; /***/ }), /***/ 8382: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.merge = void 0; const merge2 = __nccwpck_require__(2578); function merge(streams) { const mergedStream = merge2(streams); streams.forEach((stream) => { stream.once('error', (error) => mergedStream.emit('error', error)); }); mergedStream.once('close', () => propagateCloseEventToSources(streams)); mergedStream.once('end', () => propagateCloseEventToSources(streams)); return mergedStream; } exports.merge = merge; function propagateCloseEventToSources(streams) { streams.forEach((stream) => stream.emit('close')); } /***/ }), /***/ 2203: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isEmpty = exports.isString = void 0; function isString(input) { return typeof input === 'string'; } exports.isString = isString; function isEmpty(input) { return input === ''; } exports.isEmpty = isEmpty; /***/ }), /***/ 7340: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* eslint-disable no-var */ var reusify = __nccwpck_require__(2113) function fastqueue (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker worker = context context = null } if (concurrency < 1) { throw new Error('fastqueue concurrency must be greater than 1') } var cache = reusify(Task) var queueHead = null var queueTail = null var _running = 0 var errorHandler = null var self = { push: push, drain: noop, saturated: noop, pause: pause, paused: false, concurrency: concurrency, running: running, resume: resume, idle: idle, length: length, getQueue: getQueue, unshift: unshift, empty: noop, kill: kill, killAndDrain: killAndDrain, error: error } return self function running () { return _running } function pause () { self.paused = true } function length () { var current = queueHead var counter = 0 while (current) { current = current.next counter++ } return counter } function getQueue () { var current = queueHead var tasks = [] while (current) { tasks.push(current.value) current = current.next } return tasks } function resume () { if (!self.paused) return self.paused = false for (var i = 0; i < self.concurrency; i++) { _running++ release() } } function idle () { return _running === 0 && self.length() === 0 } function push (value, done) { var current = cache.get() current.context = context current.release = release current.value = value current.callback = done || noop current.errorHandler = errorHandler if (_running === self.concurrency || self.paused) { if (queueTail) { queueTail.next = current queueTail = current } else { queueHead = current queueTail = current self.saturated() } } else { _running++ worker.call(context, current.value, current.worked) } } function unshift (value, done) { var current = cache.get() current.context = context current.release = release current.value = value current.callback = done || noop if (_running === self.concurrency || self.paused) { if (queueHead) { current.next = queueHead queueHead = current } else { queueHead = current queueTail = current self.saturated() } } else { _running++ worker.call(context, current.value, current.worked) } } function release (holder) { if (holder) { cache.release(holder) } var next = queueHead if (next) { if (!self.paused) { if (queueTail === queueHead) { queueTail = null } queueHead = next.next next.next = null worker.call(context, next.value, next.worked) if (queueTail === null) { self.empty() } } else { _running-- } } else if (--_running === 0) { self.drain() } } function kill () { queueHead = null queueTail = null self.drain = noop } function killAndDrain () { queueHead = null queueTail = null self.drain() self.drain = noop } function error (handler) { errorHandler = handler } } function noop () {} function Task () { this.value = null this.callback = noop this.next = null this.release = noop this.context = null this.errorHandler = null var self = this this.worked = function worked (err, result) { var callback = self.callback var errorHandler = self.errorHandler var val = self.value self.value = null self.callback = noop if (self.errorHandler) { errorHandler(err, val) } callback.call(self.context, err, result) self.release(self) } } function queueAsPromised (context, worker, concurrency) { if (typeof context === 'function') { concurrency = worker worker = context context = null } function asyncWrapper (arg, cb) { worker.call(this, arg) .then(function (res) { cb(null, res) }, cb) } var queue = fastqueue(context, asyncWrapper, concurrency) var pushCb = queue.push var unshiftCb = queue.unshift queue.push = push queue.unshift = unshift queue.drained = drained return queue function push (value) { var p = new Promise(function (resolve, reject) { pushCb(value, function (err, result) { if (err) { reject(err) return } resolve(result) }) }) // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop) return p } function unshift (value) { var p = new Promise(function (resolve, reject) { unshiftCb(value, function (err, result) { if (err) { reject(err) return } resolve(result) }) }) // Let's fork the promise chain to // make the error bubble up to the user but // not lead to a unhandledRejection p.catch(noop) return p } function drained () { var previousDrain = queue.drain var p = new Promise(function (resolve) { queue.drain = function () { previousDrain() resolve() } }) return p } } module.exports = fastqueue module.exports.promise = queueAsPromised /***/ }), /***/ 6330: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! * fill-range * * Copyright (c) 2014-present, Jon Schlinkert. * Licensed under the MIT License. */ const util = __nccwpck_require__(3837); const toRegexRange = __nccwpck_require__(1861); const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); const transform = toNumber => { return value => toNumber === true ? Number(value) : String(value); }; const isValidValue = value => { return typeof value === 'number' || (typeof value === 'string' && value !== ''); }; const isNumber = num => Number.isInteger(+num); const zeros = input => { let value = `${input}`; let index = -1; if (value[0] === '-') value = value.slice(1); if (value === '0') return false; while (value[++index] === '0'); return index > 0; }; const stringify = (start, end, options) => { if (typeof start === 'string' || typeof end === 'string') { return true; } return options.stringify === true; }; const pad = (input, maxLength, toNumber) => { if (maxLength > 0) { let dash = input[0] === '-' ? '-' : ''; if (dash) input = input.slice(1); input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); } if (toNumber === false) { return String(input); } return input; }; const toMaxLen = (input, maxLength) => { let negative = input[0] === '-' ? '-' : ''; if (negative) { input = input.slice(1); maxLength--; } while (input.length < maxLength) input = '0' + input; return negative ? ('-' + input) : input; }; const toSequence = (parts, options) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); let prefix = options.capture ? '' : '?:'; let positives = ''; let negatives = ''; let result; if (parts.positives.length) { positives = parts.positives.join('|'); } if (parts.negatives.length) { negatives = `-(${prefix}${parts.negatives.join('|')})`; } if (positives && negatives) { result = `${positives}|${negatives}`; } else { result = positives || negatives; } if (options.wrap) { return `(${prefix}${result})`; } return result; }; const toRange = (a, b, isNumbers, options) => { if (isNumbers) { return toRegexRange(a, b, { wrap: false, ...options }); } let start = String.fromCharCode(a); if (a === b) return start; let stop = String.fromCharCode(b); return `[${start}-${stop}]`; }; const toRegex = (start, end, options) => { if (Array.isArray(start)) { let wrap = options.wrap === true; let prefix = options.capture ? '' : '?:'; return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); } return toRegexRange(start, end, options); }; const rangeError = (...args) => { return new RangeError('Invalid range arguments: ' + util.inspect(...args)); }; const invalidRange = (start, end, options) => { if (options.strictRanges === true) throw rangeError([start, end]); return []; }; const invalidStep = (step, options) => { if (options.strictRanges === true) { throw new TypeError(`Expected step "${step}" to be a number`); } return []; }; const fillNumbers = (start, end, step = 1, options = {}) => { let a = Number(start); let b = Number(end); if (!Number.isInteger(a) || !Number.isInteger(b)) { if (options.strictRanges === true) throw rangeError([start, end]); return []; } // fix negative zero if (a === 0) a = 0; if (b === 0) b = 0; let descending = a > b; let startString = String(start); let endString = String(end); let stepString = String(step); step = Math.max(Math.abs(step), 1); let padded = zeros(startString) || zeros(endString) || zeros(stepString); let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; let toNumber = padded === false && stringify(start, end, options) === false; let format = options.transform || transform(toNumber); if (options.toRegex && step === 1) { return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } let parts = { negatives: [], positives: [] }; let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); let range = []; let index = 0; while (descending ? a >= b : a <= b) { if (options.toRegex === true && step > 1) { push(a); } else { range.push(pad(format(a, index), maxLen, toNumber)); } a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return step > 1 ? toSequence(parts, options) : toRegex(range, null, { wrap: false, ...options }); } return range; }; const fillLetters = (start, end, step = 1, options = {}) => { if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { return invalidRange(start, end, options); } let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); let descending = a > b; let min = Math.min(a, b); let max = Math.max(a, b); if (options.toRegex && step === 1) { return toRange(min, max, false, options); } let range = []; let index = 0; while (descending ? a >= b : a <= b) { range.push(format(a, index)); a = descending ? a - step : a + step; index++; } if (options.toRegex === true) { return toRegex(range, null, { wrap: false, options }); } return range; }; const fill = (start, end, step, options = {}) => { if (end == null && isValidValue(start)) { return [start]; } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); } if (typeof step === 'function') { return fill(start, end, 1, { transform: step }); } if (isObject(step)) { return fill(start, end, 0, step); } let opts = { ...options }; if (opts.capture === true) opts.wrap = true; step = step || opts.step || 1; if (!isNumber(step)) { if (step != null && !isObject(step)) return invalidStep(step, opts); return fill(start, end, 1, step); } if (isNumber(start) && isNumber(end)) { return fillNumbers(start, end, step, opts); } return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; module.exports = fill; /***/ }), /***/ 4655: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var isGlob = __nccwpck_require__(4466); var pathPosixDirname = (__nccwpck_require__(1017).posix.dirname); var isWin32 = (__nccwpck_require__(2037).platform)() === 'win32'; var slash = '/'; var backslash = /\\/g; var enclosure = /[\{\[].*[\}\]]$/; var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; /** * @param {string} str * @param {Object} opts * @param {boolean} [opts.flipBackslashes=true] * @returns {string} */ module.exports = function globParent(str, opts) { var options = Object.assign({ flipBackslashes: true }, opts); // flip windows path separators if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { str = str.replace(backslash, slash); } // special case for strings ending in enclosure containing path separator if (enclosure.test(str)) { str += slash; } // preserves full path in case of trailing path separator str += 'a'; // remove path parts that are globby do { str = pathPosixDirname(str); } while (isGlob(str) || globby.test(str)); // remove escape chars and return result return str.replace(escaped, '$1'); }; /***/ }), /***/ 4777: /***/ ((module) => { // A simple implementation of make-array function makeArray (subject) { return Array.isArray(subject) ? subject : [subject] } const EMPTY = '' const SPACE = ' ' const ESCAPE = '\\' const REGEX_TEST_BLANK_LINE = /^\s+$/ const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ const REGEX_SPLITALL_CRLF = /\r?\n/g // /foo, // ./foo, // ../foo, // . // .. const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ const SLASH = '/' const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') /* istanbul ignore next */ : 'node-ignore' const define = (object, key, value) => Object.defineProperty(object, key, {value}) const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g const RETURN_FALSE = () => false // Sanitize the range of a regular expression // The cases are complicated, see test cases for details const sanitizeRange = range => range.replace( REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but // fatal for JavaScript regular expression, so eliminate it. : EMPTY ) // See fixtures #59 const cleanRangeBackSlash = slashes => { const {length} = slashes return slashes.slice(0, length - length % 2) } // > If the pattern ends with a slash, // > it is removed for the purpose of the following description, // > but it would only find a match with a directory. // > In other words, foo/ will match a directory foo and paths underneath it, // > but will not match a regular file or a symbolic link foo // > (this is consistent with the way how pathspec works in general in Git). // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call // you could use option `mark: true` with `glob` // '`foo/`' should not continue with the '`..`' const REPLACERS = [ // > Trailing spaces are ignored unless they are quoted with backslash ("\") [ // (a\ ) -> (a ) // (a ) -> (a) // (a \ ) -> (a ) /\\?\s+$/, match => match.indexOf('\\') === 0 ? SPACE : EMPTY ], // replace (\ ) with ' ' [ /\\\s/g, () => SPACE ], // Escape metacharacters // which is written down by users but means special for regular expressions. // > There are 12 characters with special meanings: // > - the backslash \, // > - the caret ^, // > - the dollar sign $, // > - the period or dot ., // > - the vertical bar or pipe symbol |, // > - the question mark ?, // > - the asterisk or star *, // > - the plus sign +, // > - the opening parenthesis (, // > - the closing parenthesis ), // > - and the opening square bracket [, // > - the opening curly brace {, // > These special characters are often called "metacharacters". [ /[\\$.|*+(){^]/g, match => `\\${match}` ], [ // > a question mark (?) matches a single character /(?!\\)\?/g, () => '[^/]' ], // leading slash [ // > A leading slash matches the beginning of the pathname. // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". // A leading slash matches the beginning of the pathname /^\//, () => '^' ], // replace special metacharacter slash after the leading slash [ /\//g, () => '\\/' ], [ // > A leading "**" followed by a slash means match in all directories. // > For example, "**/foo" matches file or directory "foo" anywhere, // > the same as pattern "foo". // > "**/foo/bar" matches file or directory "bar" anywhere that is directly // > under directory "foo". // Notice that the '*'s have been replaced as '\\*' /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' () => '^(?:.*\\/)?' ], // starting [ // there will be no leading '/' // (which has been replaced by section "leading slash") // If starts with '**', adding a '^' to the regular expression also works /^(?=[^^])/, function startingReplacer () { // If has a slash `/` at the beginning or middle return !/\/(?!$)/.test(this) // > Prior to 2.22.1 // > If the pattern does not contain a slash /, // > Git treats it as a shell glob pattern // Actually, if there is only a trailing slash, // git also treats it as a shell glob pattern // After 2.22.1 (compatible but clearer) // > If there is a separator at the beginning or middle (or both) // > of the pattern, then the pattern is relative to the directory // > level of the particular .gitignore file itself. // > Otherwise the pattern may also match at any level below // > the .gitignore level. ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for // > consumption by fnmatch(3) : '^' } ], // two globstars [ // Use lookahead assertions so that we could match more than one `'/**'` /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories // should not use '*', or it will be replaced by the next replacer // Check if it is not the last `'/**'` (_, index, str) => index + 6 < str.length // case: /**/ // > A slash followed by two consecutive asterisks then a slash matches // > zero or more directories. // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. // '/**/' ? '(?:\\/[^\\/]+)*' // case: /** // > A trailing `"/**"` matches everything inside. // #21: everything inside but it should not include the current folder : '\\/.+' ], // intermediate wildcards [ // Never replace escaped '*' // ignore rule '\*' will match the path '*' // 'abc.*/' -> go // 'abc.*' -> skip this rule /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js' // '*.js' doesn't match 'abc' (_, p1) => `${p1}[^\\/]*` ], [ // unescape, revert step 3 except for back slash // For example, if a user escape a '\\*', // after step 3, the result will be '\\\\\\*' /\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE ], [ // '\\\\' -> '\\' /\\\\/g, () => ESCAPE ], [ // > The range notation, e.g. [a-zA-Z], // > can be used to match one of the characters in a range. // `\` is escaped by step 3 /(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE // '\\[bar]' -> '\\\\[bar\\]' ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === ']' ? endEscape.length % 2 === 0 // A normal case, and it is a range notation // '[bar]' // '[bar\\\\]' ? `[${sanitizeRange(range)}${endEscape}]` // Invalid range notaton // '[bar\\]' -> '[bar\\\\]' : '[]' : '[]' ], // ending [ // 'js' will not match 'js.' // 'ab' will not match 'abc' /(?:[^*])$/, // WTF! // https://git-scm.com/docs/gitignore // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) // which re-fixes #24, #38 // > If there is a separator at the end of the pattern then the pattern // > will only match directories, otherwise the pattern can match both // > files and directories. // 'js*' will not match 'a.js' // 'js/' will not match 'a.js' // 'js' will match 'a.js' and 'a.js/' match => /\/$/.test(match) // foo/ will not match 'foo' ? `${match}$` // foo matches 'foo' and 'foo/' : `${match}(?=$|\\/$)` ], // trailing wildcard [ /(\^|\\\/)?\\\*$/, (_, p1) => { const prefix = p1 // '\^': // '/*' does not match EMPTY // '/*' does not match everything // '\\\/': // 'abc/*' does not match 'abc/' ? `${p1}[^/]+` // 'a*' matches 'a' // 'a*' matches 'aa' : '[^/]*' return `${prefix}(?=$|\\/$)` } ], ] // A simple cache, because an ignore rule only has only one certain meaning const regexCache = Object.create(null) // @param {pattern} const makeRegex = (pattern, ignoreCase) => { let source = regexCache[pattern] if (!source) { source = REPLACERS.reduce( (prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern ) regexCache[pattern] = source } return ignoreCase ? new RegExp(source, 'i') : new RegExp(source) } const isString = subject => typeof subject === 'string' // > A blank line matches no files, so it can serve as a separator for readability. const checkPattern = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. && pattern.indexOf('#') !== 0 const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) class IgnoreRule { constructor ( origin, pattern, negative, regex ) { this.origin = origin this.pattern = pattern this.negative = negative this.regex = regex } } const createRule = (pattern, ignoreCase) => { const origin = pattern let negative = false // > An optional prefix "!" which negates the pattern; if (pattern.indexOf('!') === 0) { negative = true pattern = pattern.substr(1) } pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that // > begin with a literal "!", for example, `"\!important!.txt"`. .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that // > begin with a hash. .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') const regex = makeRegex(pattern, ignoreCase) return new IgnoreRule( origin, pattern, negative, regex ) } const throwError = (message, Ctor) => { throw new Ctor(message) } const checkPath = (path, originalPath, doThrow) => { if (!isString(path)) { return doThrow( `path must be a string, but got \`${originalPath}\``, TypeError ) } // We don't know if we should ignore EMPTY, so throw if (!path) { return doThrow(`path must not be empty`, TypeError) } // Check if it is a relative path if (checkPath.isNotRelative(path)) { const r = '`path.relative()`d' return doThrow( `path should be a ${r} string, but got "${originalPath}"`, RangeError ) } return true } const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) checkPath.isNotRelative = isNotRelative checkPath.convert = p => p class Ignore { constructor ({ ignorecase = true, ignoreCase = ignorecase, allowRelativePaths = false } = {}) { define(this, KEY_IGNORE, true) this._rules = [] this._ignoreCase = ignoreCase this._allowRelativePaths = allowRelativePaths this._initCache() } _initCache () { this._ignoreCache = Object.create(null) this._testCache = Object.create(null) } _addPattern (pattern) { // #32 if (pattern && pattern[KEY_IGNORE]) { this._rules = this._rules.concat(pattern._rules) this._added = true return } if (checkPattern(pattern)) { const rule = createRule(pattern, this._ignoreCase) this._added = true this._rules.push(rule) } } // @param {Array | string | Ignore} pattern add (pattern) { this._added = false makeArray( isString(pattern) ? splitPattern(pattern) : pattern ).forEach(this._addPattern, this) // Some rules have just added to the ignore, // making the behavior changed. if (this._added) { this._initCache() } return this } // legacy addPattern (pattern) { return this.add(pattern) } // | ignored : unignored // negative | 0:0 | 0:1 | 1:0 | 1:1 // -------- | ------- | ------- | ------- | -------- // 0 | TEST | TEST | SKIP | X // 1 | TESTIF | SKIP | TEST | X // - SKIP: always skip // - TEST: always test // - TESTIF: only test if checkUnignored // - X: that never happen // @param {boolean} whether should check if the path is unignored, // setting `checkUnignored` to `false` could reduce additional // path matching. // @returns {TestResult} true if a file is ignored _testOne (path, checkUnignored) { let ignored = false let unignored = false this._rules.forEach(rule => { const {negative} = rule if ( unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored ) { return } const matched = rule.regex.test(path) if (matched) { ignored = !negative unignored = negative } }) return { ignored, unignored } } // @returns {TestResult} _test (originalPath, cache, checkUnignored, slices) { const path = originalPath // Supports nullable path && checkPath.convert(originalPath) checkPath( path, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError ) return this._t(path, cache, checkUnignored, slices) } _t (path, cache, checkUnignored, slices) { if (path in cache) { return cache[path] } if (!slices) { // path/to/a.js // ['path', 'to', 'a.js'] slices = path.split(SLASH) } slices.pop() // If the path has no parent directory, just test it if (!slices.length) { return cache[path] = this._testOne(path, checkUnignored) } const parent = this._t( slices.join(SLASH) + SLASH, cache, checkUnignored, slices ) // If the path contains a parent directory, check the parent first return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of // > that file is excluded. ? parent : this._testOne(path, checkUnignored) } ignores (path) { return this._test(path, this._ignoreCache, false).ignored } createFilter () { return path => !this.ignores(path) } filter (paths) { return makeArray(paths).filter(this.createFilter()) } // @returns {TestResult} test (path) { return this._test(path, this._testCache, true) } } const factory = options => new Ignore(options) const isPathValid = path => checkPath(path && checkPath.convert(path), path, RETURN_FALSE) factory.isPathValid = isPathValid // Fixes typescript factory.default = factory module.exports = factory // Windows // -------------------------------------------------------------- /* istanbul ignore if */ if ( // Detect `process` so that it can run in browsers. typeof process !== 'undefined' && ( process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32' ) ) { /* eslint no-control-regex: "off" */ const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/') checkPath.convert = makePosix // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' // 'd:\\foo' const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path) } /***/ }), /***/ 6435: /***/ ((module) => { /*! * is-extglob * * Copyright (c) 2014-2016, Jon Schlinkert. * Licensed under the MIT License. */ module.exports = function isExtglob(str) { if (typeof str !== 'string' || str === '') { return false; } var match; while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { if (match[2]) return true; str = str.slice(match.index + match[0].length); } return false; }; /***/ }), /***/ 4466: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! * is-glob * * Copyright (c) 2014-2017, Jon Schlinkert. * Released under the MIT License. */ var isExtglob = __nccwpck_require__(6435); var chars = { '{': '}', '(': ')', '[': ']'}; var strictCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; var pipeIndex = -2; var closeSquareIndex = -2; var closeCurlyIndex = -2; var closeParenIndex = -2; var backSlashIndex = -2; while (index < str.length) { if (str[index] === '*') { return true; } if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { return true; } if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { if (closeSquareIndex < index) { closeSquareIndex = str.indexOf(']', index); } if (closeSquareIndex > index) { if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { return true; } } } if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { closeCurlyIndex = str.indexOf('}', index); if (closeCurlyIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { return true; } } } if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { closeParenIndex = str.indexOf(')', index); if (closeParenIndex > index) { backSlashIndex = str.indexOf('\\', index); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { if (pipeIndex < index) { pipeIndex = str.indexOf('|', index); } if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { closeParenIndex = str.indexOf(')', pipeIndex); if (closeParenIndex > pipeIndex) { backSlashIndex = str.indexOf('\\', pipeIndex); if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { return true; } } } } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; var relaxedCheck = function(str) { if (str[0] === '!') { return true; } var index = 0; while (index < str.length) { if (/[*?{}()[\]]/.test(str[index])) { return true; } if (str[index] === '\\') { var open = str[index + 1]; index += 2; var close = chars[open]; if (close) { var n = str.indexOf(close, index); if (n !== -1) { index = n + 1; } } if (str[index] === '!') { return true; } } else { index++; } } return false; }; module.exports = function isGlob(str, options) { if (typeof str !== 'string' || str === '') { return false; } if (isExtglob(str)) { return true; } var check = strictCheck; // optionally relax check if (options && options.strict === false) { check = relaxedCheck; } return check(str); }; /***/ }), /***/ 5680: /***/ ((module) => { "use strict"; /*! * is-number * * Copyright (c) 2014-present, Jon Schlinkert. * Released under the MIT License. */ module.exports = function(num) { if (typeof num === 'number') { return num - num === 0; } if (typeof num === 'string' && num.trim() !== '') { return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); } return false; }; /***/ }), /***/ 6786: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; //////////////////////////////////////////////////////////////////////////////// // Helpers // Merge objects // function assign(obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); sources.forEach(function (source) { if (!source) { return; } Object.keys(source).forEach(function (key) { obj[key] = source[key]; }); }); return obj; } function _class(obj) { return Object.prototype.toString.call(obj); } function isString(obj) { return _class(obj) === '[object String]'; } function isObject(obj) { return _class(obj) === '[object Object]'; } function isRegExp(obj) { return _class(obj) === '[object RegExp]'; } function isFunction(obj) { return _class(obj) === '[object Function]'; } function escapeRE(str) { return str.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&'); } //////////////////////////////////////////////////////////////////////////////// var defaultOptions = { fuzzyLink: true, fuzzyEmail: true, fuzzyIP: false }; function isOptionsObj(obj) { return Object.keys(obj || {}).reduce(function (acc, k) { return acc || defaultOptions.hasOwnProperty(k); }, false); } var defaultSchemas = { 'http:': { validate: function (text, pos, self) { var tail = text.slice(pos); if (!self.re.http) { // compile lazily, because "host"-containing variables can change on tlds update. self.re.http = new RegExp( '^\\/\\/' + self.re.src_auth + self.re.src_host_port_strict + self.re.src_path, 'i' ); } if (self.re.http.test(tail)) { return tail.match(self.re.http)[0].length; } return 0; } }, 'https:': 'http:', 'ftp:': 'http:', '//': { validate: function (text, pos, self) { var tail = text.slice(pos); if (!self.re.no_http) { // compile lazily, because "host"-containing variables can change on tlds update. self.re.no_http = new RegExp( '^' + self.re.src_auth + // Don't allow single-level domains, because of false positives like '//test' // with code comments '(?:localhost|(?:(?:' + self.re.src_domain + ')\\.)+' + self.re.src_domain_root + ')' + self.re.src_port + self.re.src_host_terminator + self.re.src_path, 'i' ); } if (self.re.no_http.test(tail)) { // should not be `://` & `///`, that protects from errors in protocol name if (pos >= 3 && text[pos - 3] === ':') { return 0; } if (pos >= 3 && text[pos - 3] === '/') { return 0; } return tail.match(self.re.no_http)[0].length; } return 0; } }, 'mailto:': { validate: function (text, pos, self) { var tail = text.slice(pos); if (!self.re.mailto) { self.re.mailto = new RegExp( '^' + self.re.src_email_name + '@' + self.re.src_host_strict, 'i' ); } if (self.re.mailto.test(tail)) { return tail.match(self.re.mailto)[0].length; } return 0; } } }; /*eslint-disable max-len*/ // RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js) var tlds_2ch_src_re = 'a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]'; // DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead var tlds_default = 'biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф'.split('|'); /*eslint-enable max-len*/ //////////////////////////////////////////////////////////////////////////////// function resetScanCache(self) { self.__index__ = -1; self.__text_cache__ = ''; } function createValidator(re) { return function (text, pos) { var tail = text.slice(pos); if (re.test(tail)) { return tail.match(re)[0].length; } return 0; }; } function createNormalizer() { return function (match, self) { self.normalize(match); }; } // Schemas compiler. Build regexps. // function compile(self) { // Load & clone RE patterns. var re = self.re = __nccwpck_require__(4971)(self.__opts__); // Define dynamic patterns var tlds = self.__tlds__.slice(); self.onCompile(); if (!self.__tlds_replaced__) { tlds.push(tlds_2ch_src_re); } tlds.push(re.src_xn); re.src_tlds = tlds.join('|'); function untpl(tpl) { return tpl.replace('%TLDS%', re.src_tlds); } re.email_fuzzy = RegExp(untpl(re.tpl_email_fuzzy), 'i'); re.link_fuzzy = RegExp(untpl(re.tpl_link_fuzzy), 'i'); re.link_no_ip_fuzzy = RegExp(untpl(re.tpl_link_no_ip_fuzzy), 'i'); re.host_fuzzy_test = RegExp(untpl(re.tpl_host_fuzzy_test), 'i'); // // Compile each schema // var aliases = []; self.__compiled__ = {}; // Reset compiled data function schemaError(name, val) { throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val); } Object.keys(self.__schemas__).forEach(function (name) { var val = self.__schemas__[name]; // skip disabled methods if (val === null) { return; } var compiled = { validate: null, link: null }; self.__compiled__[name] = compiled; if (isObject(val)) { if (isRegExp(val.validate)) { compiled.validate = createValidator(val.validate); } else if (isFunction(val.validate)) { compiled.validate = val.validate; } else { schemaError(name, val); } if (isFunction(val.normalize)) { compiled.normalize = val.normalize; } else if (!val.normalize) { compiled.normalize = createNormalizer(); } else { schemaError(name, val); } return; } if (isString(val)) { aliases.push(name); return; } schemaError(name, val); }); // // Compile postponed aliases // aliases.forEach(function (alias) { if (!self.__compiled__[self.__schemas__[alias]]) { // Silently fail on missed schemas to avoid errons on disable. // schemaError(alias, self.__schemas__[alias]); return; } self.__compiled__[alias].validate = self.__compiled__[self.__schemas__[alias]].validate; self.__compiled__[alias].normalize = self.__compiled__[self.__schemas__[alias]].normalize; }); // // Fake record for guessed links // self.__compiled__[''] = { validate: null, normalize: createNormalizer() }; // // Build schema condition // var slist = Object.keys(self.__compiled__) .filter(function (name) { // Filter disabled & fake schemas return name.length > 0 && self.__compiled__[name]; }) .map(escapeRE) .join('|'); // (?!_) cause 1.5x slowdown self.re.schema_test = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'i'); self.re.schema_search = RegExp('(^|(?!_)(?:[><\uff5c]|' + re.src_ZPCc + '))(' + slist + ')', 'ig'); self.re.schema_at_start = RegExp('^' + self.re.schema_search.source, 'i'); self.re.pretest = RegExp( '(' + self.re.schema_test.source + ')|(' + self.re.host_fuzzy_test.source + ')|@', 'i' ); // // Cleanup // resetScanCache(self); } /** * class Match * * Match result. Single element of array, returned by [[LinkifyIt#match]] **/ function Match(self, shift) { var start = self.__index__, end = self.__last_index__, text = self.__text_cache__.slice(start, end); /** * Match#schema -> String * * Prefix (protocol) for matched string. **/ this.schema = self.__schema__.toLowerCase(); /** * Match#index -> Number * * First position of matched string. **/ this.index = start + shift; /** * Match#lastIndex -> Number * * Next position after matched string. **/ this.lastIndex = end + shift; /** * Match#raw -> String * * Matched string. **/ this.raw = text; /** * Match#text -> String * * Notmalized text of matched string. **/ this.text = text; /** * Match#url -> String * * Normalized url of matched string. **/ this.url = text; } function createMatch(self, shift) { var match = new Match(self, shift); self.__compiled__[match.schema].normalize(match, self); return match; } /** * class LinkifyIt **/ /** * new LinkifyIt(schemas, options) * - schemas (Object): Optional. Additional schemas to validate (prefix/validator) * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } * * Creates new linkifier instance with optional additional schemas. * Can be called without `new` keyword for convenience. * * By default understands: * * - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links * - "fuzzy" links and emails (example.com, foo@bar.com). * * `schemas` is an object, where each key/value describes protocol/rule: * * - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` * for example). `linkify-it` makes shure that prefix is not preceeded with * alphanumeric char and symbols. Only whitespaces and punctuation allowed. * - __value__ - rule to check tail after link prefix * - _String_ - just alias to existing rule * - _Object_ * - _validate_ - validator function (should return matched length on success), * or `RegExp`. * - _normalize_ - optional function to normalize text & url of matched result * (for example, for @twitter mentions). * * `options`: * * - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. * - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts * like version numbers. Default `false`. * - __fuzzyEmail__ - recognize emails without `mailto:` prefix. * **/ function LinkifyIt(schemas, options) { if (!(this instanceof LinkifyIt)) { return new LinkifyIt(schemas, options); } if (!options) { if (isOptionsObj(schemas)) { options = schemas; schemas = {}; } } this.__opts__ = assign({}, defaultOptions, options); // Cache last tested result. Used to skip repeating steps on next `match` call. this.__index__ = -1; this.__last_index__ = -1; // Next scan position this.__schema__ = ''; this.__text_cache__ = ''; this.__schemas__ = assign({}, defaultSchemas, schemas); this.__compiled__ = {}; this.__tlds__ = tlds_default; this.__tlds_replaced__ = false; this.re = {}; compile(this); } /** chainable * LinkifyIt#add(schema, definition) * - schema (String): rule name (fixed pattern prefix) * - definition (String|RegExp|Object): schema definition * * Add new rule definition. See constructor description for details. **/ LinkifyIt.prototype.add = function add(schema, definition) { this.__schemas__[schema] = definition; compile(this); return this; }; /** chainable * LinkifyIt#set(options) * - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } * * Set recognition options for links without schema. **/ LinkifyIt.prototype.set = function set(options) { this.__opts__ = assign(this.__opts__, options); return this; }; /** * LinkifyIt#test(text) -> Boolean * * Searches linkifiable pattern and returns `true` on success or `false` on fail. **/ LinkifyIt.prototype.test = function test(text) { // Reset scan cache this.__text_cache__ = text; this.__index__ = -1; if (!text.length) { return false; } var m, ml, me, len, shift, next, re, tld_pos, at_pos; // try to scan for link with schema - that's the most simple rule if (this.re.schema_test.test(text)) { re = this.re.schema_search; re.lastIndex = 0; while ((m = re.exec(text)) !== null) { len = this.testSchemaAt(text, m[2], re.lastIndex); if (len) { this.__schema__ = m[2]; this.__index__ = m.index + m[1].length; this.__last_index__ = m.index + m[0].length + len; break; } } } if (this.__opts__.fuzzyLink && this.__compiled__['http:']) { // guess schemaless links tld_pos = text.search(this.re.host_fuzzy_test); if (tld_pos >= 0) { // if tld is located after found link - no need to check fuzzy pattern if (this.__index__ < 0 || tld_pos < this.__index__) { if ((ml = text.match(this.__opts__.fuzzyIP ? this.re.link_fuzzy : this.re.link_no_ip_fuzzy)) !== null) { shift = ml.index + ml[1].length; if (this.__index__ < 0 || shift < this.__index__) { this.__schema__ = ''; this.__index__ = shift; this.__last_index__ = ml.index + ml[0].length; } } } } } if (this.__opts__.fuzzyEmail && this.__compiled__['mailto:']) { // guess schemaless emails at_pos = text.indexOf('@'); if (at_pos >= 0) { // We can't skip this check, because this cases are possible: // 192.168.1.1@gmail.com, my.in@example.com if ((me = text.match(this.re.email_fuzzy)) !== null) { shift = me.index + me[1].length; next = me.index + me[0].length; if (this.__index__ < 0 || shift < this.__index__ || (shift === this.__index__ && next > this.__last_index__)) { this.__schema__ = 'mailto:'; this.__index__ = shift; this.__last_index__ = next; } } } } return this.__index__ >= 0; }; /** * LinkifyIt#pretest(text) -> Boolean * * Very quick check, that can give false positives. Returns true if link MAY BE * can exists. Can be used for speed optimization, when you need to check that * link NOT exists. **/ LinkifyIt.prototype.pretest = function pretest(text) { return this.re.pretest.test(text); }; /** * LinkifyIt#testSchemaAt(text, name, position) -> Number * - text (String): text to scan * - name (String): rule (schema) name * - position (Number): text offset to check from * * Similar to [[LinkifyIt#test]] but checks only specific protocol tail exactly * at given position. Returns length of found pattern (0 on fail). **/ LinkifyIt.prototype.testSchemaAt = function testSchemaAt(text, schema, pos) { // If not supported schema check requested - terminate if (!this.__compiled__[schema.toLowerCase()]) { return 0; } return this.__compiled__[schema.toLowerCase()].validate(text, pos, this); }; /** * LinkifyIt#match(text) -> Array|null * * Returns array of found link descriptions or `null` on fail. We strongly * recommend to use [[LinkifyIt#test]] first, for best speed. * * ##### Result match description * * - __schema__ - link schema, can be empty for fuzzy links, or `//` for * protocol-neutral links. * - __index__ - offset of matched text * - __lastIndex__ - index of next char after mathch end * - __raw__ - matched text * - __text__ - normalized text * - __url__ - link, generated from matched text **/ LinkifyIt.prototype.match = function match(text) { var shift = 0, result = []; // Try to take previous element from cache, if .test() called before if (this.__index__ >= 0 && this.__text_cache__ === text) { result.push(createMatch(this, shift)); shift = this.__last_index__; } // Cut head if cache was used var tail = shift ? text.slice(shift) : text; // Scan string until end reached while (this.test(tail)) { result.push(createMatch(this, shift)); tail = tail.slice(this.__last_index__); shift += this.__last_index__; } if (result.length) { return result; } return null; }; /** * LinkifyIt#matchAtStart(text) -> Match|null * * Returns fully-formed (not fuzzy) link if it starts at the beginning * of the string, and null otherwise. **/ LinkifyIt.prototype.matchAtStart = function matchAtStart(text) { // Reset scan cache this.__text_cache__ = text; this.__index__ = -1; if (!text.length) return null; var m = this.re.schema_at_start.exec(text); if (!m) return null; var len = this.testSchemaAt(text, m[2], m[0].length); if (!len) return null; this.__schema__ = m[2]; this.__index__ = m.index + m[1].length; this.__last_index__ = m.index + m[0].length + len; return createMatch(this, 0); }; /** chainable * LinkifyIt#tlds(list [, keepOld]) -> this * - list (Array): list of tlds * - keepOld (Boolean): merge with current list if `true` (`false` by default) * * Load (or merge) new tlds list. Those are user for fuzzy links (without prefix) * to avoid false positives. By default this algorythm used: * * - hostname with any 2-letter root zones are ok. * - biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф * are ok. * - encoded (`xn--...`) root zones are ok. * * If list is replaced, then exact match for 2-chars root zones will be checked. **/ LinkifyIt.prototype.tlds = function tlds(list, keepOld) { list = Array.isArray(list) ? list : [ list ]; if (!keepOld) { this.__tlds__ = list.slice(); this.__tlds_replaced__ = true; compile(this); return this; } this.__tlds__ = this.__tlds__.concat(list) .sort() .filter(function (el, idx, arr) { return el !== arr[idx - 1]; }) .reverse(); compile(this); return this; }; /** * LinkifyIt#normalize(match) * * Default normalizer (if schema does not define it's own). **/ LinkifyIt.prototype.normalize = function normalize(match) { // Do minimal possible changes by default. Need to collect feedback prior // to move forward https://github.com/markdown-it/linkify-it/issues/1 if (!match.schema) { match.url = 'http://' + match.url; } if (match.schema === 'mailto:' && !/^mailto:/i.test(match.url)) { match.url = 'mailto:' + match.url; } }; /** * LinkifyIt#onCompile() * * Override to modify basic RegExp-s. **/ LinkifyIt.prototype.onCompile = function onCompile() { }; module.exports = LinkifyIt; /***/ }), /***/ 4971: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = function (opts) { var re = {}; opts = opts || {}; // Use direct extract instead of `regenerate` to reduse browserified size re.src_Any = (__nccwpck_require__(703).source); re.src_Cc = (__nccwpck_require__(4338).source); re.src_Z = (__nccwpck_require__(8810).source); re.src_P = (__nccwpck_require__(8019).source); // \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation) re.src_ZPCc = [ re.src_Z, re.src_P, re.src_Cc ].join('|'); // \p{\Z\Cc} (white spaces + control) re.src_ZCc = [ re.src_Z, re.src_Cc ].join('|'); // Experimental. List of chars, completely prohibited in links // because can separate it from other part of text var text_separators = '[><\uff5c]'; // All possible word characters (everything without punctuation, spaces & controls) // Defined via punctuation & spaces to save space // Should be something like \p{\L\N\S\M} (\w but without `_`) re.src_pseudo_letter = '(?:(?!' + text_separators + '|' + re.src_ZPCc + ')' + re.src_Any + ')'; // The same as abothe but without [0-9] // var src_pseudo_letter_non_d = '(?:(?![0-9]|' + src_ZPCc + ')' + src_Any + ')'; //////////////////////////////////////////////////////////////////////////////// re.src_ip4 = '(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'; // Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch. re.src_auth = '(?:(?:(?!' + re.src_ZCc + '|[@/\\[\\]()]).)+@)?'; re.src_port = '(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?'; re.src_host_terminator = '(?=$|' + text_separators + '|' + re.src_ZPCc + ')' + '(?!' + (opts['---'] ? '-(?!--)|' : '-|') + '_|:\\d|\\.-|\\.(?!$|' + re.src_ZPCc + '))'; re.src_path = '(?:' + '[/?#]' + '(?:' + '(?!' + re.src_ZCc + '|' + text_separators + '|[()[\\]{}.,"\'?!\\-;]).|' + '\\[(?:(?!' + re.src_ZCc + '|\\]).)*\\]|' + '\\((?:(?!' + re.src_ZCc + '|[)]).)*\\)|' + '\\{(?:(?!' + re.src_ZCc + '|[}]).)*\\}|' + '\\"(?:(?!' + re.src_ZCc + '|["]).)+\\"|' + "\\'(?:(?!" + re.src_ZCc + "|[']).)+\\'|" + "\\'(?=" + re.src_pseudo_letter + '|[-])|' + // allow `I'm_king` if no pair found '\\.{2,}[a-zA-Z0-9%/&]|' + // google has many dots in "google search" links (#66, #81). // github has ... in commit range links, // Restrict to // - english // - percent-encoded // - parts of file path // - params separator // until more examples found. '\\.(?!' + re.src_ZCc + '|[.]|$)|' + (opts['---'] ? '\\-(?!--(?:[^-]|$))(?:-*)|' // `---` => long dash, terminate : '\\-+|' ) + ',(?!' + re.src_ZCc + '|$)|' + // allow `,,,` in paths ';(?!' + re.src_ZCc + '|$)|' + // allow `;` if not followed by space-like char '\\!+(?!' + re.src_ZCc + '|[!]|$)|' + // allow `!!!` in paths, but not at the end '\\?(?!' + re.src_ZCc + '|[?]|$)' + ')+' + '|\\/' + ')?'; // Allow anything in markdown spec, forbid quote (") at the first position // because emails enclosed in quotes are far more common re.src_email_name = '[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'; re.src_xn = 'xn--[a-z0-9\\-]{1,59}'; // More to read about domain names // http://serverfault.com/questions/638260/ re.src_domain_root = // Allow letters & digits (http://test1) '(?:' + re.src_xn + '|' + re.src_pseudo_letter + '{1,63}' + ')'; re.src_domain = '(?:' + re.src_xn + '|' + '(?:' + re.src_pseudo_letter + ')' + '|' + '(?:' + re.src_pseudo_letter + '(?:-|' + re.src_pseudo_letter + '){0,61}' + re.src_pseudo_letter + ')' + ')'; re.src_host = '(?:' + // Don't need IP check, because digits are already allowed in normal domain names // src_ip4 + // '|' + '(?:(?:(?:' + re.src_domain + ')\\.)*' + re.src_domain/*_root*/ + ')' + ')'; re.tpl_host_fuzzy = '(?:' + re.src_ip4 + '|' + '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))' + ')'; re.tpl_host_no_ip_fuzzy = '(?:(?:(?:' + re.src_domain + ')\\.)+(?:%TLDS%))'; re.src_host_strict = re.src_host + re.src_host_terminator; re.tpl_host_fuzzy_strict = re.tpl_host_fuzzy + re.src_host_terminator; re.src_host_port_strict = re.src_host + re.src_port + re.src_host_terminator; re.tpl_host_port_fuzzy_strict = re.tpl_host_fuzzy + re.src_port + re.src_host_terminator; re.tpl_host_port_no_ip_fuzzy_strict = re.tpl_host_no_ip_fuzzy + re.src_port + re.src_host_terminator; //////////////////////////////////////////////////////////////////////////////// // Main rules // Rude test fuzzy links by host, for quick deny re.tpl_host_fuzzy_test = 'localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:' + re.src_ZPCc + '|>|$))'; re.tpl_email_fuzzy = '(^|' + text_separators + '|"|\\(|' + re.src_ZCc + ')' + '(' + re.src_email_name + '@' + re.tpl_host_fuzzy_strict + ')'; re.tpl_link_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation. // but can start with > (markdown blockquote) '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_fuzzy_strict + re.src_path + ')'; re.tpl_link_no_ip_fuzzy = // Fuzzy link can't be prepended with .:/\- and non punctuation. // but can start with > (markdown blockquote) '(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|' + re.src_ZPCc + '))' + '((?![$+<=>^`|\uff5c])' + re.tpl_host_port_no_ip_fuzzy_strict + re.src_path + ')'; return re; }; /***/ }), /***/ 8561: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(4949); /***/ }), /***/ 9220: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // HTML5 entities map: { name -> utf16string } // /*eslint quotes:0*/ module.exports = __nccwpck_require__(9323); /***/ }), /***/ 9035: /***/ ((module) => { "use strict"; // List of valid html blocks names, accorting to commonmark spec // http://jgm.github.io/CommonMark/spec.html#html-blocks module.exports = [ 'address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu', 'menuitem', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'section', 'source', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul' ]; /***/ }), /***/ 6537: /***/ ((module) => { "use strict"; // Regexps to match html elements var attr_name = '[a-zA-Z_:][a-zA-Z0-9:._-]*'; var unquoted = '[^"\'=<>`\\x00-\\x20]+'; var single_quoted = "'[^']*'"; var double_quoted = '"[^"]*"'; var attr_value = '(?:' + unquoted + '|' + single_quoted + '|' + double_quoted + ')'; var attribute = '(?:\\s+' + attr_name + '(?:\\s*=\\s*' + attr_value + ')?)'; var open_tag = '<[A-Za-z][A-Za-z0-9\\-]*' + attribute + '*\\s*\\/?>'; var close_tag = '<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>'; var comment = '|'; var processing = '<[?][\\s\\S]*?[?]>'; var declaration = ']*>'; var cdata = ''; var HTML_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + '|' + comment + '|' + processing + '|' + declaration + '|' + cdata + ')'); var HTML_OPEN_CLOSE_TAG_RE = new RegExp('^(?:' + open_tag + '|' + close_tag + ')'); module.exports.n = HTML_TAG_RE; module.exports.q = HTML_OPEN_CLOSE_TAG_RE; /***/ }), /***/ 506: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Utilities // function _class(obj) { return Object.prototype.toString.call(obj); } function isString(obj) { return _class(obj) === '[object String]'; } var _hasOwnProperty = Object.prototype.hasOwnProperty; function has(object, key) { return _hasOwnProperty.call(object, key); } // Merge objects // function assign(obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); sources.forEach(function (source) { if (!source) { return; } if (typeof source !== 'object') { throw new TypeError(source + 'must be object'); } Object.keys(source).forEach(function (key) { obj[key] = source[key]; }); }); return obj; } // Remove element from array and put another array at those position. // Useful for some operations with tokens function arrayReplaceAt(src, pos, newElements) { return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1)); } //////////////////////////////////////////////////////////////////////////////// function isValidEntityCode(c) { /*eslint no-bitwise:0*/ // broken sequence if (c >= 0xD800 && c <= 0xDFFF) { return false; } // never used if (c >= 0xFDD0 && c <= 0xFDEF) { return false; } if ((c & 0xFFFF) === 0xFFFF || (c & 0xFFFF) === 0xFFFE) { return false; } // control codes if (c >= 0x00 && c <= 0x08) { return false; } if (c === 0x0B) { return false; } if (c >= 0x0E && c <= 0x1F) { return false; } if (c >= 0x7F && c <= 0x9F) { return false; } // out of range if (c > 0x10FFFF) { return false; } return true; } function fromCodePoint(c) { /*eslint no-bitwise:0*/ if (c > 0xffff) { c -= 0x10000; var surrogate1 = 0xd800 + (c >> 10), surrogate2 = 0xdc00 + (c & 0x3ff); return String.fromCharCode(surrogate1, surrogate2); } return String.fromCharCode(c); } var UNESCAPE_MD_RE = /\\([!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])/g; var ENTITY_RE = /&([a-z#][a-z0-9]{1,31});/gi; var UNESCAPE_ALL_RE = new RegExp(UNESCAPE_MD_RE.source + '|' + ENTITY_RE.source, 'gi'); var DIGITAL_ENTITY_TEST_RE = /^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))/i; var entities = __nccwpck_require__(9220); function replaceEntityPattern(match, name) { var code = 0; if (has(entities, name)) { return entities[name]; } if (name.charCodeAt(0) === 0x23/* # */ && DIGITAL_ENTITY_TEST_RE.test(name)) { code = name[1].toLowerCase() === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10); if (isValidEntityCode(code)) { return fromCodePoint(code); } } return match; } /*function replaceEntities(str) { if (str.indexOf('&') < 0) { return str; } return str.replace(ENTITY_RE, replaceEntityPattern); }*/ function unescapeMd(str) { if (str.indexOf('\\') < 0) { return str; } return str.replace(UNESCAPE_MD_RE, '$1'); } function unescapeAll(str) { if (str.indexOf('\\') < 0 && str.indexOf('&') < 0) { return str; } return str.replace(UNESCAPE_ALL_RE, function (match, escaped, entity) { if (escaped) { return escaped; } return replaceEntityPattern(match, entity); }); } //////////////////////////////////////////////////////////////////////////////// var HTML_ESCAPE_TEST_RE = /[&<>"]/; var HTML_ESCAPE_REPLACE_RE = /[&<>"]/g; var HTML_REPLACEMENTS = { '&': '&', '<': '<', '>': '>', '"': '"' }; function replaceUnsafeChar(ch) { return HTML_REPLACEMENTS[ch]; } function escapeHtml(str) { if (HTML_ESCAPE_TEST_RE.test(str)) { return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar); } return str; } //////////////////////////////////////////////////////////////////////////////// var REGEXP_ESCAPE_RE = /[.?*+^$[\]\\(){}|-]/g; function escapeRE(str) { return str.replace(REGEXP_ESCAPE_RE, '\\$&'); } //////////////////////////////////////////////////////////////////////////////// function isSpace(code) { switch (code) { case 0x09: case 0x20: return true; } return false; } // Zs (unicode class) || [\t\f\v\r\n] function isWhiteSpace(code) { if (code >= 0x2000 && code <= 0x200A) { return true; } switch (code) { case 0x09: // \t case 0x0A: // \n case 0x0B: // \v case 0x0C: // \f case 0x0D: // \r case 0x20: case 0xA0: case 0x1680: case 0x202F: case 0x205F: case 0x3000: return true; } return false; } //////////////////////////////////////////////////////////////////////////////// /*eslint-disable max-len*/ var UNICODE_PUNCT_RE = __nccwpck_require__(8019); // Currently without astral characters support. function isPunctChar(ch) { return UNICODE_PUNCT_RE.test(ch); } // Markdown ASCII punctuation characters. // // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ // http://spec.commonmark.org/0.15/#ascii-punctuation-character // // Don't confuse with unicode punctuation !!! It lacks some chars in ascii range. // function isMdAsciiPunct(ch) { switch (ch) { case 0x21/* ! */: case 0x22/* " */: case 0x23/* # */: case 0x24/* $ */: case 0x25/* % */: case 0x26/* & */: case 0x27/* ' */: case 0x28/* ( */: case 0x29/* ) */: case 0x2A/* * */: case 0x2B/* + */: case 0x2C/* , */: case 0x2D/* - */: case 0x2E/* . */: case 0x2F/* / */: case 0x3A/* : */: case 0x3B/* ; */: case 0x3C/* < */: case 0x3D/* = */: case 0x3E/* > */: case 0x3F/* ? */: case 0x40/* @ */: case 0x5B/* [ */: case 0x5C/* \ */: case 0x5D/* ] */: case 0x5E/* ^ */: case 0x5F/* _ */: case 0x60/* ` */: case 0x7B/* { */: case 0x7C/* | */: case 0x7D/* } */: case 0x7E/* ~ */: return true; default: return false; } } // Hepler to unify [reference labels]. // function normalizeReference(str) { // Trim and collapse whitespace // str = str.trim().replace(/\s+/g, ' '); // In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug // fixed in v12 (couldn't find any details). // // So treat this one as a special case // (remove this when node v10 is no longer supported). // if ('ẞ'.toLowerCase() === 'Ṿ') { str = str.replace(/ẞ/g, 'ß'); } // .toLowerCase().toUpperCase() should get rid of all differences // between letter variants. // // Simple .toLowerCase() doesn't normalize 125 code points correctly, // and .toUpperCase doesn't normalize 6 of them (list of exceptions: // İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently // uppercased versions). // // Here's an example showing how it happens. Lets take greek letter omega: // uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ) // // Unicode entries: // 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8; // 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398 // 03D1;GREEK THETA SYMBOL;Ll;0;L; 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398 // 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L; 0398;;;;N;;;;03B8; // // Case-insensitive comparison should treat all of them as equivalent. // // But .toLowerCase() doesn't change ϑ (it's already lowercase), // and .toUpperCase() doesn't change ϴ (already uppercase). // // Applying first lower then upper case normalizes any character: // '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398' // // Note: this is equivalent to unicode case folding; unicode normalization // is a different step that is not required here. // // Final result should be uppercased, because it's later stored in an object // (this avoid a conflict with Object.prototype members, // most notably, `__proto__`) // return str.toLowerCase().toUpperCase(); } //////////////////////////////////////////////////////////////////////////////// // Re-export libraries commonly used in both markdown-it and its plugins, // so plugins won't have to depend on them explicitly, which reduces their // bundled size (e.g. a browser build). // exports.lib = {}; exports.lib.mdurl = __nccwpck_require__(114); exports.lib.ucmicro = __nccwpck_require__(5649); exports.assign = assign; exports.isString = isString; exports.has = has; exports.unescapeMd = unescapeMd; exports.unescapeAll = unescapeAll; exports.isValidEntityCode = isValidEntityCode; exports.fromCodePoint = fromCodePoint; // exports.replaceEntities = replaceEntities; exports.escapeHtml = escapeHtml; exports.arrayReplaceAt = arrayReplaceAt; exports.isSpace = isSpace; exports.isWhiteSpace = isWhiteSpace; exports.isMdAsciiPunct = isMdAsciiPunct; exports.isPunctChar = isPunctChar; exports.escapeRE = escapeRE; exports.normalizeReference = normalizeReference; /***/ }), /***/ 3380: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; // Just a shortcut for bulk export exports.parseLinkLabel = __nccwpck_require__(7945); exports.parseLinkDestination = __nccwpck_require__(9914); exports.parseLinkTitle = __nccwpck_require__(3085); /***/ }), /***/ 9914: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Parse link destination // var unescapeAll = (__nccwpck_require__(506).unescapeAll); module.exports = function parseLinkDestination(str, pos, max) { var code, level, lines = 0, start = pos, result = { ok: false, pos: 0, lines: 0, str: '' }; if (str.charCodeAt(pos) === 0x3C /* < */) { pos++; while (pos < max) { code = str.charCodeAt(pos); if (code === 0x0A /* \n */) { return result; } if (code === 0x3C /* < */) { return result; } if (code === 0x3E /* > */) { result.pos = pos + 1; result.str = unescapeAll(str.slice(start + 1, pos)); result.ok = true; return result; } if (code === 0x5C /* \ */ && pos + 1 < max) { pos += 2; continue; } pos++; } // no closing '>' return result; } // this should be ... } else { ... branch level = 0; while (pos < max) { code = str.charCodeAt(pos); if (code === 0x20) { break; } // ascii control characters if (code < 0x20 || code === 0x7F) { break; } if (code === 0x5C /* \ */ && pos + 1 < max) { if (str.charCodeAt(pos + 1) === 0x20) { break; } pos += 2; continue; } if (code === 0x28 /* ( */) { level++; if (level > 32) { return result; } } if (code === 0x29 /* ) */) { if (level === 0) { break; } level--; } pos++; } if (start === pos) { return result; } if (level !== 0) { return result; } result.str = unescapeAll(str.slice(start, pos)); result.lines = lines; result.pos = pos; result.ok = true; return result; }; /***/ }), /***/ 7945: /***/ ((module) => { "use strict"; // Parse link label // // this function assumes that first character ("[") already matches; // returns the end of the label // module.exports = function parseLinkLabel(state, start, disableNested) { var level, found, marker, prevPos, labelEnd = -1, max = state.posMax, oldPos = state.pos; state.pos = start + 1; level = 1; while (state.pos < max) { marker = state.src.charCodeAt(state.pos); if (marker === 0x5D /* ] */) { level--; if (level === 0) { found = true; break; } } prevPos = state.pos; state.md.inline.skipToken(state); if (marker === 0x5B /* [ */) { if (prevPos === state.pos - 1) { // increase level if we find text `[`, which is not a part of any token level++; } else if (disableNested) { state.pos = oldPos; return -1; } } } if (found) { labelEnd = state.pos; } // restore old state state.pos = oldPos; return labelEnd; }; /***/ }), /***/ 3085: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Parse link title // var unescapeAll = (__nccwpck_require__(506).unescapeAll); module.exports = function parseLinkTitle(str, pos, max) { var code, marker, lines = 0, start = pos, result = { ok: false, pos: 0, lines: 0, str: '' }; if (pos >= max) { return result; } marker = str.charCodeAt(pos); if (marker !== 0x22 /* " */ && marker !== 0x27 /* ' */ && marker !== 0x28 /* ( */) { return result; } pos++; // if opening marker is "(", switch it to closing marker ")" if (marker === 0x28) { marker = 0x29; } while (pos < max) { code = str.charCodeAt(pos); if (code === marker) { result.pos = pos + 1; result.lines = lines; result.str = unescapeAll(str.slice(start + 1, pos)); result.ok = true; return result; } else if (code === 0x28 /* ( */ && marker === 0x29 /* ) */) { return result; } else if (code === 0x0A) { lines++; } else if (code === 0x5C /* \ */ && pos + 1 < max) { pos++; if (str.charCodeAt(pos) === 0x0A) { lines++; } } pos++; } return result; }; /***/ }), /***/ 4949: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Main parser class var utils = __nccwpck_require__(506); var helpers = __nccwpck_require__(3380); var Renderer = __nccwpck_require__(3041); var ParserCore = __nccwpck_require__(4004); var ParserBlock = __nccwpck_require__(8007); var ParserInline = __nccwpck_require__(6031); var LinkifyIt = __nccwpck_require__(6786); var mdurl = __nccwpck_require__(114); var punycode = __nccwpck_require__(5477); var config = { default: __nccwpck_require__(1007), zero: __nccwpck_require__(6719), commonmark: __nccwpck_require__(3084) }; //////////////////////////////////////////////////////////////////////////////// // // This validator can prohibit more than really needed to prevent XSS. It's a // tradeoff to keep code simple and to be secure by default. // // If you need different setup - override validator method as you wish. Or // replace it with dummy function and use external sanitizer. // var BAD_PROTO_RE = /^(vbscript|javascript|file|data):/; var GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/; function validateLink(url) { // url should be normalized at this point, and existing entities are decoded var str = url.trim().toLowerCase(); return BAD_PROTO_RE.test(str) ? (GOOD_DATA_RE.test(str) ? true : false) : true; } //////////////////////////////////////////////////////////////////////////////// var RECODE_HOSTNAME_FOR = [ 'http:', 'https:', 'mailto:' ]; function normalizeLink(url) { var parsed = mdurl.parse(url, true); if (parsed.hostname) { // Encode hostnames in urls like: // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` // // We don't encode unknown schemas, because it's likely that we encode // something we shouldn't (e.g. `skype:name` treated as `skype:host`) // if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { try { parsed.hostname = punycode.toASCII(parsed.hostname); } catch (er) { /**/ } } } return mdurl.encode(mdurl.format(parsed)); } function normalizeLinkText(url) { var parsed = mdurl.parse(url, true); if (parsed.hostname) { // Encode hostnames in urls like: // `http://host/`, `https://host/`, `mailto:user@host`, `//host/` // // We don't encode unknown schemas, because it's likely that we encode // something we shouldn't (e.g. `skype:name` treated as `skype:host`) // if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) { try { parsed.hostname = punycode.toUnicode(parsed.hostname); } catch (er) { /**/ } } } // add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720 return mdurl.decode(mdurl.format(parsed), mdurl.decode.defaultChars + '%'); } /** * class MarkdownIt * * Main parser/renderer class. * * ##### Usage * * ```javascript * // node.js, "classic" way: * var MarkdownIt = require('markdown-it'), * md = new MarkdownIt(); * var result = md.render('# markdown-it rulezz!'); * * // node.js, the same, but with sugar: * var md = require('markdown-it')(); * var result = md.render('# markdown-it rulezz!'); * * // browser without AMD, added to "window" on script load * // Note, there are no dash. * var md = window.markdownit(); * var result = md.render('# markdown-it rulezz!'); * ``` * * Single line rendering, without paragraph wrap: * * ```javascript * var md = require('markdown-it')(); * var result = md.renderInline('__markdown-it__ rulezz!'); * ``` **/ /** * new MarkdownIt([presetName, options]) * - presetName (String): optional, `commonmark` / `zero` * - options (Object) * * Creates parser instanse with given config. Can be called without `new`. * * ##### presetName * * MarkdownIt provides named presets as a convenience to quickly * enable/disable active syntax rules and options for common use cases. * * - ["commonmark"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/commonmark.js) - * configures parser to strict [CommonMark](http://commonmark.org/) mode. * - [default](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/default.js) - * similar to GFM, used when no preset name given. Enables all available rules, * but still without html, typographer & autolinker. * - ["zero"](https://github.com/markdown-it/markdown-it/blob/master/lib/presets/zero.js) - * all rules disabled. Useful to quickly setup your config via `.enable()`. * For example, when you need only `bold` and `italic` markup and nothing else. * * ##### options: * * - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful! * That's not safe! You may need external sanitizer to protect output from XSS. * It's better to extend features via plugins, instead of enabling HTML. * - __xhtmlOut__ - `false`. Set `true` to add '/' when closing single tags * (`
`). This is needed only for full CommonMark compatibility. In real * world you will need HTML output. * - __breaks__ - `false`. Set `true` to convert `\n` in paragraphs into `
`. * - __langPrefix__ - `language-`. CSS language class prefix for fenced blocks. * Can be useful for external highlighters. * - __linkify__ - `false`. Set `true` to autoconvert URL-like text to links. * - __typographer__ - `false`. Set `true` to enable [some language-neutral * replacement](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js) + * quotes beautification (smartquotes). * - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement * pairs, when typographer enabled and smartquotes on. For example, you can * use `'«»„“'` for Russian, `'„“‚‘'` for German, and * `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp). * - __highlight__ - `null`. Highlighter function for fenced code blocks. * Highlighter `function (str, lang)` should return escaped HTML. It can also * return empty string if the source was not changed and should be escaped * externaly. If result starts with `): * * ```javascript * var hljs = require('highlight.js') // https://highlightjs.org/ * * // Actual default values * var md = require('markdown-it')({ * highlight: function (str, lang) { * if (lang && hljs.getLanguage(lang)) { * try { * return '
' +
 *                hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
 *                '
'; * } catch (__) {} * } * * return '
' + md.utils.escapeHtml(str) + '
'; * } * }); * ``` * **/ function MarkdownIt(presetName, options) { if (!(this instanceof MarkdownIt)) { return new MarkdownIt(presetName, options); } if (!options) { if (!utils.isString(presetName)) { options = presetName || {}; presetName = 'default'; } } /** * MarkdownIt#inline -> ParserInline * * Instance of [[ParserInline]]. You may need it to add new rules when * writing plugins. For simple rules control use [[MarkdownIt.disable]] and * [[MarkdownIt.enable]]. **/ this.inline = new ParserInline(); /** * MarkdownIt#block -> ParserBlock * * Instance of [[ParserBlock]]. You may need it to add new rules when * writing plugins. For simple rules control use [[MarkdownIt.disable]] and * [[MarkdownIt.enable]]. **/ this.block = new ParserBlock(); /** * MarkdownIt#core -> Core * * Instance of [[Core]] chain executor. You may need it to add new rules when * writing plugins. For simple rules control use [[MarkdownIt.disable]] and * [[MarkdownIt.enable]]. **/ this.core = new ParserCore(); /** * MarkdownIt#renderer -> Renderer * * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering * rules for new token types, generated by plugins. * * ##### Example * * ```javascript * var md = require('markdown-it')(); * * function myToken(tokens, idx, options, env, self) { * //... * return result; * }; * * md.renderer.rules['my_token'] = myToken * ``` * * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js). **/ this.renderer = new Renderer(); /** * MarkdownIt#linkify -> LinkifyIt * * [linkify-it](https://github.com/markdown-it/linkify-it) instance. * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.js) * rule. **/ this.linkify = new LinkifyIt(); /** * MarkdownIt#validateLink(url) -> Boolean * * Link validation function. CommonMark allows too much in links. By default * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas * except some embedded image types. * * You can change this behaviour: * * ```javascript * var md = require('markdown-it')(); * // enable everything * md.validateLink = function () { return true; } * ``` **/ this.validateLink = validateLink; /** * MarkdownIt#normalizeLink(url) -> String * * Function used to encode link url to a machine-readable format, * which includes url-encoding, punycode, etc. **/ this.normalizeLink = normalizeLink; /** * MarkdownIt#normalizeLinkText(url) -> String * * Function used to decode link url to a human-readable format` **/ this.normalizeLinkText = normalizeLinkText; // Expose utils & helpers for easy acces from plugins /** * MarkdownIt#utils -> utils * * Assorted utility functions, useful to write plugins. See details * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.js). **/ this.utils = utils; /** * MarkdownIt#helpers -> helpers * * Link components parser functions, useful to write plugins. See details * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers). **/ this.helpers = utils.assign({}, helpers); this.options = {}; this.configure(presetName); if (options) { this.set(options); } } /** chainable * MarkdownIt.set(options) * * Set parser options (in the same format as in constructor). Probably, you * will never need it, but you can change options after constructor call. * * ##### Example * * ```javascript * var md = require('markdown-it')() * .set({ html: true, breaks: true }) * .set({ typographer, true }); * ``` * * __Note:__ To achieve the best possible performance, don't modify a * `markdown-it` instance options on the fly. If you need multiple configurations * it's best to create multiple instances and initialize each with separate * config. **/ MarkdownIt.prototype.set = function (options) { utils.assign(this.options, options); return this; }; /** chainable, internal * MarkdownIt.configure(presets) * * Batch load of all options and compenent settings. This is internal method, * and you probably will not need it. But if you will - see available presets * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets) * * We strongly recommend to use presets instead of direct config loads. That * will give better compatibility with next versions. **/ MarkdownIt.prototype.configure = function (presets) { var self = this, presetName; if (utils.isString(presets)) { presetName = presets; presets = config[presetName]; if (!presets) { throw new Error('Wrong `markdown-it` preset "' + presetName + '", check name'); } } if (!presets) { throw new Error('Wrong `markdown-it` preset, can\'t be empty'); } if (presets.options) { self.set(presets.options); } if (presets.components) { Object.keys(presets.components).forEach(function (name) { if (presets.components[name].rules) { self[name].ruler.enableOnly(presets.components[name].rules); } if (presets.components[name].rules2) { self[name].ruler2.enableOnly(presets.components[name].rules2); } }); } return this; }; /** chainable * MarkdownIt.enable(list, ignoreInvalid) * - list (String|Array): rule name or list of rule names to enable * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. * * Enable list or rules. It will automatically find appropriate components, * containing rules with given names. If rule not found, and `ignoreInvalid` * not set - throws exception. * * ##### Example * * ```javascript * var md = require('markdown-it')() * .enable(['sub', 'sup']) * .disable('smartquotes'); * ``` **/ MarkdownIt.prototype.enable = function (list, ignoreInvalid) { var result = []; if (!Array.isArray(list)) { list = [ list ]; } [ 'core', 'block', 'inline' ].forEach(function (chain) { result = result.concat(this[chain].ruler.enable(list, true)); }, this); result = result.concat(this.inline.ruler2.enable(list, true)); var missed = list.filter(function (name) { return result.indexOf(name) < 0; }); if (missed.length && !ignoreInvalid) { throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed); } return this; }; /** chainable * MarkdownIt.disable(list, ignoreInvalid) * - list (String|Array): rule name or list of rule names to disable. * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. * * The same as [[MarkdownIt.enable]], but turn specified rules off. **/ MarkdownIt.prototype.disable = function (list, ignoreInvalid) { var result = []; if (!Array.isArray(list)) { list = [ list ]; } [ 'core', 'block', 'inline' ].forEach(function (chain) { result = result.concat(this[chain].ruler.disable(list, true)); }, this); result = result.concat(this.inline.ruler2.disable(list, true)); var missed = list.filter(function (name) { return result.indexOf(name) < 0; }); if (missed.length && !ignoreInvalid) { throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed); } return this; }; /** chainable * MarkdownIt.use(plugin, params) * * Load specified plugin with given params into current parser instance. * It's just a sugar to call `plugin(md, params)` with curring. * * ##### Example * * ```javascript * var iterator = require('markdown-it-for-inline'); * var md = require('markdown-it')() * .use(iterator, 'foo_replace', 'text', function (tokens, idx) { * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar'); * }); * ``` **/ MarkdownIt.prototype.use = function (plugin /*, params, ... */) { var args = [ this ].concat(Array.prototype.slice.call(arguments, 1)); plugin.apply(plugin, args); return this; }; /** internal * MarkdownIt.parse(src, env) -> Array * - src (String): source string * - env (Object): environment sandbox * * Parse input string and return list of block tokens (special token type * "inline" will contain list of inline tokens). You should not call this * method directly, until you write custom renderer (for example, to produce * AST). * * `env` is used to pass data between "distributed" rules and return additional * metadata like reference info, needed for the renderer. It also can be used to * inject data in specific cases. Usually, you will be ok to pass `{}`, * and then pass updated object to renderer. **/ MarkdownIt.prototype.parse = function (src, env) { if (typeof src !== 'string') { throw new Error('Input data should be a String'); } var state = new this.core.State(src, this, env); this.core.process(state); return state.tokens; }; /** * MarkdownIt.render(src [, env]) -> String * - src (String): source string * - env (Object): environment sandbox * * Render markdown string into html. It does all magic for you :). * * `env` can be used to inject additional metadata (`{}` by default). * But you will not need it with high probability. See also comment * in [[MarkdownIt.parse]]. **/ MarkdownIt.prototype.render = function (src, env) { env = env || {}; return this.renderer.render(this.parse(src, env), this.options, env); }; /** internal * MarkdownIt.parseInline(src, env) -> Array * - src (String): source string * - env (Object): environment sandbox * * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the * block tokens list with the single `inline` element, containing parsed inline * tokens in `children` property. Also updates `env` object. **/ MarkdownIt.prototype.parseInline = function (src, env) { var state = new this.core.State(src, this, env); state.inlineMode = true; this.core.process(state); return state.tokens; }; /** * MarkdownIt.renderInline(src [, env]) -> String * - src (String): source string * - env (Object): environment sandbox * * Similar to [[MarkdownIt.render]] but for single paragraph content. Result * will NOT be wrapped into `

` tags. **/ MarkdownIt.prototype.renderInline = function (src, env) { env = env || {}; return this.renderer.render(this.parseInline(src, env), this.options, env); }; module.exports = MarkdownIt; /***/ }), /***/ 8007: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** internal * class ParserBlock * * Block-level tokenizer. **/ var Ruler = __nccwpck_require__(2093); var _rules = [ // First 2 params - rule name & source. Secondary array - list of rules, // which can be terminated by this one. [ 'table', __nccwpck_require__(7722), [ 'paragraph', 'reference' ] ], [ 'code', __nccwpck_require__(7693) ], [ 'fence', __nccwpck_require__(7749), [ 'paragraph', 'reference', 'blockquote', 'list' ] ], [ 'blockquote', __nccwpck_require__(6888), [ 'paragraph', 'reference', 'blockquote', 'list' ] ], [ 'hr', __nccwpck_require__(3514), [ 'paragraph', 'reference', 'blockquote', 'list' ] ], [ 'list', __nccwpck_require__(2050), [ 'paragraph', 'reference', 'blockquote' ] ], [ 'reference', __nccwpck_require__(2235) ], [ 'html_block', __nccwpck_require__(5732), [ 'paragraph', 'reference', 'blockquote' ] ], [ 'heading', __nccwpck_require__(2702), [ 'paragraph', 'reference', 'blockquote' ] ], [ 'lheading', __nccwpck_require__(3551) ], [ 'paragraph', __nccwpck_require__(9450) ] ]; /** * new ParserBlock() **/ function ParserBlock() { /** * ParserBlock#ruler -> Ruler * * [[Ruler]] instance. Keep configuration of block rules. **/ this.ruler = new Ruler(); for (var i = 0; i < _rules.length; i++) { this.ruler.push(_rules[i][0], _rules[i][1], { alt: (_rules[i][2] || []).slice() }); } } // Generate tokens for input range // ParserBlock.prototype.tokenize = function (state, startLine, endLine) { var ok, i, rules = this.ruler.getRules(''), len = rules.length, line = startLine, hasEmptyLines = false, maxNesting = state.md.options.maxNesting; while (line < endLine) { state.line = line = state.skipEmptyLines(line); if (line >= endLine) { break; } // Termination condition for nested calls. // Nested calls currently used for blockquotes & lists if (state.sCount[line] < state.blkIndent) { break; } // If nesting level exceeded - skip tail to the end. That's not ordinary // situation and we should not care about content. if (state.level >= maxNesting) { state.line = endLine; break; } // Try all possible rules. // On success, rule should: // // - update `state.line` // - update `state.tokens` // - return true for (i = 0; i < len; i++) { ok = rules[i](state, line, endLine, false); if (ok) { break; } } // set state.tight if we had an empty line before current tag // i.e. latest empty line should not count state.tight = !hasEmptyLines; // paragraph might "eat" one newline after it in nested lists if (state.isEmpty(state.line - 1)) { hasEmptyLines = true; } line = state.line; if (line < endLine && state.isEmpty(line)) { hasEmptyLines = true; line++; state.line = line; } } }; /** * ParserBlock.parse(str, md, env, outTokens) * * Process input string and push block tokens into `outTokens` **/ ParserBlock.prototype.parse = function (src, md, env, outTokens) { var state; if (!src) { return; } state = new this.State(src, md, env, outTokens); this.tokenize(state, state.line, state.lineMax); }; ParserBlock.prototype.State = __nccwpck_require__(9497); module.exports = ParserBlock; /***/ }), /***/ 4004: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** internal * class Core * * Top-level rules executor. Glues block/inline parsers and does intermediate * transformations. **/ var Ruler = __nccwpck_require__(2093); var _rules = [ [ 'normalize', __nccwpck_require__(2764) ], [ 'block', __nccwpck_require__(31) ], [ 'inline', __nccwpck_require__(1951) ], [ 'linkify', __nccwpck_require__(5462) ], [ 'replacements', __nccwpck_require__(8373) ], [ 'smartquotes', __nccwpck_require__(2178) ], // `text_join` finds `text_special` tokens (for escape sequences) // and joins them with the rest of the text [ 'text_join', __nccwpck_require__(7502) ] ]; /** * new Core() **/ function Core() { /** * Core#ruler -> Ruler * * [[Ruler]] instance. Keep configuration of core rules. **/ this.ruler = new Ruler(); for (var i = 0; i < _rules.length; i++) { this.ruler.push(_rules[i][0], _rules[i][1]); } } /** * Core.process(state) * * Executes core chain rules. **/ Core.prototype.process = function (state) { var i, l, rules; rules = this.ruler.getRules(''); for (i = 0, l = rules.length; i < l; i++) { rules[i](state); } }; Core.prototype.State = __nccwpck_require__(9052); module.exports = Core; /***/ }), /***/ 6031: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /** internal * class ParserInline * * Tokenizes paragraph content. **/ var Ruler = __nccwpck_require__(2093); //////////////////////////////////////////////////////////////////////////////// // Parser rules var _rules = [ [ 'text', __nccwpck_require__(1117) ], [ 'linkify', __nccwpck_require__(1783) ], [ 'newline', __nccwpck_require__(8774) ], [ 'escape', __nccwpck_require__(1836) ], [ 'backticks', __nccwpck_require__(8520) ], [ 'strikethrough', (__nccwpck_require__(3015)/* .tokenize */ .w) ], [ 'emphasis', (__nccwpck_require__(1677)/* .tokenize */ .w) ], [ 'link', __nccwpck_require__(8798) ], [ 'image', __nccwpck_require__(9998) ], [ 'autolink', __nccwpck_require__(3939) ], [ 'html_inline', __nccwpck_require__(7753) ], [ 'entity', __nccwpck_require__(973) ] ]; // `rule2` ruleset was created specifically for emphasis/strikethrough // post-processing and may be changed in the future. // // Don't use this for anything except pairs (plugins working with `balance_pairs`). // var _rules2 = [ [ 'balance_pairs', __nccwpck_require__(9418) ], [ 'strikethrough', (__nccwpck_require__(3015)/* .postProcess */ .g) ], [ 'emphasis', (__nccwpck_require__(1677)/* .postProcess */ .g) ], // rules for pairs separate '**' into its own text tokens, which may be left unused, // rule below merges unused segments back with the rest of the text [ 'fragments_join', __nccwpck_require__(3807) ] ]; /** * new ParserInline() **/ function ParserInline() { var i; /** * ParserInline#ruler -> Ruler * * [[Ruler]] instance. Keep configuration of inline rules. **/ this.ruler = new Ruler(); for (i = 0; i < _rules.length; i++) { this.ruler.push(_rules[i][0], _rules[i][1]); } /** * ParserInline#ruler2 -> Ruler * * [[Ruler]] instance. Second ruler used for post-processing * (e.g. in emphasis-like rules). **/ this.ruler2 = new Ruler(); for (i = 0; i < _rules2.length; i++) { this.ruler2.push(_rules2[i][0], _rules2[i][1]); } } // Skip single token by running all rules in validation mode; // returns `true` if any rule reported success // ParserInline.prototype.skipToken = function (state) { var ok, i, pos = state.pos, rules = this.ruler.getRules(''), len = rules.length, maxNesting = state.md.options.maxNesting, cache = state.cache; if (typeof cache[pos] !== 'undefined') { state.pos = cache[pos]; return; } if (state.level < maxNesting) { for (i = 0; i < len; i++) { // Increment state.level and decrement it later to limit recursion. // It's harmless to do here, because no tokens are created. But ideally, // we'd need a separate private state variable for this purpose. // state.level++; ok = rules[i](state, true); state.level--; if (ok) { break; } } } else { // Too much nesting, just skip until the end of the paragraph. // // NOTE: this will cause links to behave incorrectly in the following case, // when an amount of `[` is exactly equal to `maxNesting + 1`: // // [[[[[[[[[[[[[[[[[[[[[foo]() // // TODO: remove this workaround when CM standard will allow nested links // (we can replace it by preventing links from being parsed in // validation mode) // state.pos = state.posMax; } if (!ok) { state.pos++; } cache[pos] = state.pos; }; // Generate tokens for input range // ParserInline.prototype.tokenize = function (state) { var ok, i, rules = this.ruler.getRules(''), len = rules.length, end = state.posMax, maxNesting = state.md.options.maxNesting; while (state.pos < end) { // Try all possible rules. // On success, rule should: // // - update `state.pos` // - update `state.tokens` // - return true if (state.level < maxNesting) { for (i = 0; i < len; i++) { ok = rules[i](state, false); if (ok) { break; } } } if (ok) { if (state.pos >= end) { break; } continue; } state.pending += state.src[state.pos++]; } if (state.pending) { state.pushPending(); } }; /** * ParserInline.parse(str, md, env, outTokens) * * Process input string and push inline tokens into `outTokens` **/ ParserInline.prototype.parse = function (str, md, env, outTokens) { var i, rules, len; var state = new this.State(str, md, env, outTokens); this.tokenize(state); rules = this.ruler2.getRules(''); len = rules.length; for (i = 0; i < len; i++) { rules[i](state); } }; ParserInline.prototype.State = __nccwpck_require__(1247); module.exports = ParserInline; /***/ }), /***/ 3084: /***/ ((module) => { "use strict"; // Commonmark default options module.exports = { options: { html: true, // Enable HTML tags in source xhtmlOut: true, // Use '/' to close single tags (
) breaks: false, // Convert '\n' in paragraphs into
langPrefix: 'language-', // CSS language prefix for fenced blocks linkify: false, // autoconvert URL-like texts to links // Enable some language-neutral replacements + quotes beautification typographer: false, // Double + single quotes replacement pairs, when typographer enabled, // and smartquotes on. Could be either a String or an Array. // // For example, you can use '«»„“' for Russian, '„“‚‘' for German, // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). quotes: '\u201c\u201d\u2018\u2019', /* “”‘’ */ // Highlighter function. Should return escaped HTML, // or '' if the source string is not changed and should be escaped externaly. // If result starts with { "use strict"; // markdown-it default options module.exports = { options: { html: false, // Enable HTML tags in source xhtmlOut: false, // Use '/' to close single tags (
) breaks: false, // Convert '\n' in paragraphs into
langPrefix: 'language-', // CSS language prefix for fenced blocks linkify: false, // autoconvert URL-like texts to links // Enable some language-neutral replacements + quotes beautification typographer: false, // Double + single quotes replacement pairs, when typographer enabled, // and smartquotes on. Could be either a String or an Array. // // For example, you can use '«»„“' for Russian, '„“‚‘' for German, // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). quotes: '\u201c\u201d\u2018\u2019', /* “”‘’ */ // Highlighter function. Should return escaped HTML, // or '' if the source string is not changed and should be escaped externaly. // If result starts with { "use strict"; // "Zero" preset, with nothing enabled. Useful for manual configuring of simple // modes. For example, to parse bold/italic only. module.exports = { options: { html: false, // Enable HTML tags in source xhtmlOut: false, // Use '/' to close single tags (
) breaks: false, // Convert '\n' in paragraphs into
langPrefix: 'language-', // CSS language prefix for fenced blocks linkify: false, // autoconvert URL-like texts to links // Enable some language-neutral replacements + quotes beautification typographer: false, // Double + single quotes replacement pairs, when typographer enabled, // and smartquotes on. Could be either a String or an Array. // // For example, you can use '«»„“' for Russian, '„“‚‘' for German, // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp). quotes: '\u201c\u201d\u2018\u2019', /* “”‘’ */ // Highlighter function. Should return escaped HTML, // or '' if the source string is not changed and should be escaped externaly. // If result starts with { "use strict"; /** * class Renderer * * Generates HTML from parsed token stream. Each instance has independent * copy of rules. Those can be rewritten with ease. Also, you can add new * rules if you create plugin and adds new token types. **/ var assign = (__nccwpck_require__(506).assign); var unescapeAll = (__nccwpck_require__(506).unescapeAll); var escapeHtml = (__nccwpck_require__(506).escapeHtml); //////////////////////////////////////////////////////////////////////////////// var default_rules = {}; default_rules.code_inline = function (tokens, idx, options, env, slf) { var token = tokens[idx]; return '' + escapeHtml(tokens[idx].content) + ''; }; default_rules.code_block = function (tokens, idx, options, env, slf) { var token = tokens[idx]; return '' + escapeHtml(tokens[idx].content) + '\n'; }; default_rules.fence = function (tokens, idx, options, env, slf) { var token = tokens[idx], info = token.info ? unescapeAll(token.info).trim() : '', langName = '', langAttrs = '', highlighted, i, arr, tmpAttrs, tmpToken; if (info) { arr = info.split(/(\s+)/g); langName = arr[0]; langAttrs = arr.slice(2).join(''); } if (options.highlight) { highlighted = options.highlight(token.content, langName, langAttrs) || escapeHtml(token.content); } else { highlighted = escapeHtml(token.content); } if (highlighted.indexOf('' + highlighted + '\n'; } return '

'
        + highlighted
        + '
\n'; }; default_rules.image = function (tokens, idx, options, env, slf) { var token = tokens[idx]; // "alt" attr MUST be set, even if empty. Because it's mandatory and // should be placed on proper position for tests. // // Replace content with actual value token.attrs[token.attrIndex('alt')][1] = slf.renderInlineAsText(token.children, options, env); return slf.renderToken(tokens, idx, options); }; default_rules.hardbreak = function (tokens, idx, options /*, env */) { return options.xhtmlOut ? '
\n' : '
\n'; }; default_rules.softbreak = function (tokens, idx, options /*, env */) { return options.breaks ? (options.xhtmlOut ? '
\n' : '
\n') : '\n'; }; default_rules.text = function (tokens, idx /*, options, env */) { return escapeHtml(tokens[idx].content); }; default_rules.html_block = function (tokens, idx /*, options, env */) { return tokens[idx].content; }; default_rules.html_inline = function (tokens, idx /*, options, env */) { return tokens[idx].content; }; /** * new Renderer() * * Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults. **/ function Renderer() { /** * Renderer#rules -> Object * * Contains render rules for tokens. Can be updated and extended. * * ##### Example * * ```javascript * var md = require('markdown-it')(); * * md.renderer.rules.strong_open = function () { return ''; }; * md.renderer.rules.strong_close = function () { return ''; }; * * var result = md.renderInline(...); * ``` * * Each rule is called as independent static function with fixed signature: * * ```javascript * function my_token_render(tokens, idx, options, env, renderer) { * // ... * return renderedHTML; * } * ``` * * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js) * for more details and examples. **/ this.rules = assign({}, default_rules); } /** * Renderer.renderAttrs(token) -> String * * Render token attributes to string. **/ Renderer.prototype.renderAttrs = function renderAttrs(token) { var i, l, result; if (!token.attrs) { return ''; } result = ''; for (i = 0, l = token.attrs.length; i < l; i++) { result += ' ' + escapeHtml(token.attrs[i][0]) + '="' + escapeHtml(token.attrs[i][1]) + '"'; } return result; }; /** * Renderer.renderToken(tokens, idx, options) -> String * - tokens (Array): list of tokens * - idx (Numbed): token index to render * - options (Object): params of parser instance * * Default token renderer. Can be overriden by custom function * in [[Renderer#rules]]. **/ Renderer.prototype.renderToken = function renderToken(tokens, idx, options) { var nextToken, result = '', needLf = false, token = tokens[idx]; // Tight list paragraphs if (token.hidden) { return ''; } // Insert a newline between hidden paragraph and subsequent opening // block-level tag. // // For example, here we should insert a newline before blockquote: // - a // > // if (token.block && token.nesting !== -1 && idx && tokens[idx - 1].hidden) { result += '\n'; } // Add token name, e.g. ``. // needLf = false; } } } } result += needLf ? '>\n' : '>'; return result; }; /** * Renderer.renderInline(tokens, options, env) -> String * - tokens (Array): list on block tokens to render * - options (Object): params of parser instance * - env (Object): additional data from parsed input (references, for example) * * The same as [[Renderer.render]], but for single token of `inline` type. **/ Renderer.prototype.renderInline = function (tokens, options, env) { var type, result = '', rules = this.rules; for (var i = 0, len = tokens.length; i < len; i++) { type = tokens[i].type; if (typeof rules[type] !== 'undefined') { result += rules[type](tokens, i, options, env, this); } else { result += this.renderToken(tokens, i, options); } } return result; }; /** internal * Renderer.renderInlineAsText(tokens, options, env) -> String * - tokens (Array): list on block tokens to render * - options (Object): params of parser instance * - env (Object): additional data from parsed input (references, for example) * * Special kludge for image `alt` attributes to conform CommonMark spec. * Don't try to use it! Spec requires to show `alt` content with stripped markup, * instead of simple escaping. **/ Renderer.prototype.renderInlineAsText = function (tokens, options, env) { var result = ''; for (var i = 0, len = tokens.length; i < len; i++) { if (tokens[i].type === 'text') { result += tokens[i].content; } else if (tokens[i].type === 'image') { result += this.renderInlineAsText(tokens[i].children, options, env); } else if (tokens[i].type === 'softbreak') { result += '\n'; } } return result; }; /** * Renderer.render(tokens, options, env) -> String * - tokens (Array): list on block tokens to render * - options (Object): params of parser instance * - env (Object): additional data from parsed input (references, for example) * * Takes token stream and generates HTML. Probably, you will never need to call * this method directly. **/ Renderer.prototype.render = function (tokens, options, env) { var i, len, type, result = '', rules = this.rules; for (i = 0, len = tokens.length; i < len; i++) { type = tokens[i].type; if (type === 'inline') { result += this.renderInline(tokens[i].children, options, env); } else if (typeof rules[type] !== 'undefined') { result += rules[tokens[i].type](tokens, i, options, env, this); } else { result += this.renderToken(tokens, i, options, env); } } return result; }; module.exports = Renderer; /***/ }), /***/ 2093: /***/ ((module) => { "use strict"; /** * class Ruler * * Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and * [[MarkdownIt#inline]] to manage sequences of functions (rules): * * - keep rules in defined order * - assign the name to each rule * - enable/disable rules * - add/replace rules * - allow assign rules to additional named chains (in the same) * - cacheing lists of active rules * * You will not need use this class directly until write plugins. For simple * rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and * [[MarkdownIt.use]]. **/ /** * new Ruler() **/ function Ruler() { // List of added rules. Each element is: // // { // name: XXX, // enabled: Boolean, // fn: Function(), // alt: [ name2, name3 ] // } // this.__rules__ = []; // Cached rule chains. // // First level - chain name, '' for default. // Second level - diginal anchor for fast filtering by charcodes. // this.__cache__ = null; } //////////////////////////////////////////////////////////////////////////////// // Helper methods, should not be used directly // Find rule index by name // Ruler.prototype.__find__ = function (name) { for (var i = 0; i < this.__rules__.length; i++) { if (this.__rules__[i].name === name) { return i; } } return -1; }; // Build rules lookup cache // Ruler.prototype.__compile__ = function () { var self = this; var chains = [ '' ]; // collect unique names self.__rules__.forEach(function (rule) { if (!rule.enabled) { return; } rule.alt.forEach(function (altName) { if (chains.indexOf(altName) < 0) { chains.push(altName); } }); }); self.__cache__ = {}; chains.forEach(function (chain) { self.__cache__[chain] = []; self.__rules__.forEach(function (rule) { if (!rule.enabled) { return; } if (chain && rule.alt.indexOf(chain) < 0) { return; } self.__cache__[chain].push(rule.fn); }); }); }; /** * Ruler.at(name, fn [, options]) * - name (String): rule name to replace. * - fn (Function): new rule function. * - options (Object): new rule options (not mandatory). * * Replace rule by name with new function & options. Throws error if name not * found. * * ##### Options: * * - __alt__ - array with names of "alternate" chains. * * ##### Example * * Replace existing typographer replacement rule with new one: * * ```javascript * var md = require('markdown-it')(); * * md.core.ruler.at('replacements', function replace(state) { * //... * }); * ``` **/ Ruler.prototype.at = function (name, fn, options) { var index = this.__find__(name); var opt = options || {}; if (index === -1) { throw new Error('Parser rule not found: ' + name); } this.__rules__[index].fn = fn; this.__rules__[index].alt = opt.alt || []; this.__cache__ = null; }; /** * Ruler.before(beforeName, ruleName, fn [, options]) * - beforeName (String): new rule will be added before this one. * - ruleName (String): name of added rule. * - fn (Function): rule function. * - options (Object): rule options (not mandatory). * * Add new rule to chain before one with given name. See also * [[Ruler.after]], [[Ruler.push]]. * * ##### Options: * * - __alt__ - array with names of "alternate" chains. * * ##### Example * * ```javascript * var md = require('markdown-it')(); * * md.block.ruler.before('paragraph', 'my_rule', function replace(state) { * //... * }); * ``` **/ Ruler.prototype.before = function (beforeName, ruleName, fn, options) { var index = this.__find__(beforeName); var opt = options || {}; if (index === -1) { throw new Error('Parser rule not found: ' + beforeName); } this.__rules__.splice(index, 0, { name: ruleName, enabled: true, fn: fn, alt: opt.alt || [] }); this.__cache__ = null; }; /** * Ruler.after(afterName, ruleName, fn [, options]) * - afterName (String): new rule will be added after this one. * - ruleName (String): name of added rule. * - fn (Function): rule function. * - options (Object): rule options (not mandatory). * * Add new rule to chain after one with given name. See also * [[Ruler.before]], [[Ruler.push]]. * * ##### Options: * * - __alt__ - array with names of "alternate" chains. * * ##### Example * * ```javascript * var md = require('markdown-it')(); * * md.inline.ruler.after('text', 'my_rule', function replace(state) { * //... * }); * ``` **/ Ruler.prototype.after = function (afterName, ruleName, fn, options) { var index = this.__find__(afterName); var opt = options || {}; if (index === -1) { throw new Error('Parser rule not found: ' + afterName); } this.__rules__.splice(index + 1, 0, { name: ruleName, enabled: true, fn: fn, alt: opt.alt || [] }); this.__cache__ = null; }; /** * Ruler.push(ruleName, fn [, options]) * - ruleName (String): name of added rule. * - fn (Function): rule function. * - options (Object): rule options (not mandatory). * * Push new rule to the end of chain. See also * [[Ruler.before]], [[Ruler.after]]. * * ##### Options: * * - __alt__ - array with names of "alternate" chains. * * ##### Example * * ```javascript * var md = require('markdown-it')(); * * md.core.ruler.push('my_rule', function replace(state) { * //... * }); * ``` **/ Ruler.prototype.push = function (ruleName, fn, options) { var opt = options || {}; this.__rules__.push({ name: ruleName, enabled: true, fn: fn, alt: opt.alt || [] }); this.__cache__ = null; }; /** * Ruler.enable(list [, ignoreInvalid]) -> Array * - list (String|Array): list of rule names to enable. * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. * * Enable rules with given names. If any rule name not found - throw Error. * Errors can be disabled by second param. * * Returns list of found rule names (if no exception happened). * * See also [[Ruler.disable]], [[Ruler.enableOnly]]. **/ Ruler.prototype.enable = function (list, ignoreInvalid) { if (!Array.isArray(list)) { list = [ list ]; } var result = []; // Search by name and enable list.forEach(function (name) { var idx = this.__find__(name); if (idx < 0) { if (ignoreInvalid) { return; } throw new Error('Rules manager: invalid rule name ' + name); } this.__rules__[idx].enabled = true; result.push(name); }, this); this.__cache__ = null; return result; }; /** * Ruler.enableOnly(list [, ignoreInvalid]) * - list (String|Array): list of rule names to enable (whitelist). * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. * * Enable rules with given names, and disable everything else. If any rule name * not found - throw Error. Errors can be disabled by second param. * * See also [[Ruler.disable]], [[Ruler.enable]]. **/ Ruler.prototype.enableOnly = function (list, ignoreInvalid) { if (!Array.isArray(list)) { list = [ list ]; } this.__rules__.forEach(function (rule) { rule.enabled = false; }); this.enable(list, ignoreInvalid); }; /** * Ruler.disable(list [, ignoreInvalid]) -> Array * - list (String|Array): list of rule names to disable. * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found. * * Disable rules with given names. If any rule name not found - throw Error. * Errors can be disabled by second param. * * Returns list of found rule names (if no exception happened). * * See also [[Ruler.enable]], [[Ruler.enableOnly]]. **/ Ruler.prototype.disable = function (list, ignoreInvalid) { if (!Array.isArray(list)) { list = [ list ]; } var result = []; // Search by name and disable list.forEach(function (name) { var idx = this.__find__(name); if (idx < 0) { if (ignoreInvalid) { return; } throw new Error('Rules manager: invalid rule name ' + name); } this.__rules__[idx].enabled = false; result.push(name); }, this); this.__cache__ = null; return result; }; /** * Ruler.getRules(chainName) -> Array * * Return array of active functions (rules) for given chain name. It analyzes * rules configuration, compiles caches if not exists and returns result. * * Default chain name is `''` (empty string). It can't be skipped. That's * done intentionally, to keep signature monomorphic for high speed. **/ Ruler.prototype.getRules = function (chainName) { if (this.__cache__ === null) { this.__compile__(); } // Chain can be empty, if rules disabled. But we still have to return Array. return this.__cache__[chainName] || []; }; module.exports = Ruler; /***/ }), /***/ 6888: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Block quotes var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function blockquote(state, startLine, endLine, silent) { var adjustTab, ch, i, initial, l, lastLineEmpty, lines, nextLine, offset, oldBMarks, oldBSCount, oldIndent, oldParentType, oldSCount, oldTShift, spaceAfterMarker, terminate, terminatorRules, token, isOutdented, oldLineMax = state.lineMax, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } // check the block quote marker if (state.src.charCodeAt(pos++) !== 0x3E/* > */) { return false; } // we know that it's going to be a valid blockquote, // so no point trying to find the end of it in silent mode if (silent) { return true; } // set offset past spaces and ">" initial = offset = state.sCount[startLine] + 1; // skip one optional space after '>' if (state.src.charCodeAt(pos) === 0x20 /* space */) { // ' > test ' // ^ -- position start of line here: pos++; initial++; offset++; adjustTab = false; spaceAfterMarker = true; } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { spaceAfterMarker = true; if ((state.bsCount[startLine] + offset) % 4 === 3) { // ' >\t test ' // ^ -- position start of line here (tab has width===1) pos++; initial++; offset++; adjustTab = false; } else { // ' >\t test ' // ^ -- position start of line here + shift bsCount slightly // to make extra space appear adjustTab = true; } } else { spaceAfterMarker = false; } oldBMarks = [ state.bMarks[startLine] ]; state.bMarks[startLine] = pos; while (pos < max) { ch = state.src.charCodeAt(pos); if (isSpace(ch)) { if (ch === 0x09) { offset += 4 - (offset + state.bsCount[startLine] + (adjustTab ? 1 : 0)) % 4; } else { offset++; } } else { break; } pos++; } oldBSCount = [ state.bsCount[startLine] ]; state.bsCount[startLine] = state.sCount[startLine] + 1 + (spaceAfterMarker ? 1 : 0); lastLineEmpty = pos >= max; oldSCount = [ state.sCount[startLine] ]; state.sCount[startLine] = offset - initial; oldTShift = [ state.tShift[startLine] ]; state.tShift[startLine] = pos - state.bMarks[startLine]; terminatorRules = state.md.block.ruler.getRules('blockquote'); oldParentType = state.parentType; state.parentType = 'blockquote'; // Search the end of the block // // Block ends with either: // 1. an empty line outside: // ``` // > test // // ``` // 2. an empty line inside: // ``` // > // test // ``` // 3. another tag: // ``` // > test // - - - // ``` for (nextLine = startLine + 1; nextLine < endLine; nextLine++) { // check if it's outdented, i.e. it's inside list item and indented // less than said list item: // // ``` // 1. anything // > current blockquote // 2. checking this line // ``` isOutdented = state.sCount[nextLine] < state.blkIndent; pos = state.bMarks[nextLine] + state.tShift[nextLine]; max = state.eMarks[nextLine]; if (pos >= max) { // Case 1: line is not inside the blockquote, and this line is empty. break; } if (state.src.charCodeAt(pos++) === 0x3E/* > */ && !isOutdented) { // This line is inside the blockquote. // set offset past spaces and ">" initial = offset = state.sCount[nextLine] + 1; // skip one optional space after '>' if (state.src.charCodeAt(pos) === 0x20 /* space */) { // ' > test ' // ^ -- position start of line here: pos++; initial++; offset++; adjustTab = false; spaceAfterMarker = true; } else if (state.src.charCodeAt(pos) === 0x09 /* tab */) { spaceAfterMarker = true; if ((state.bsCount[nextLine] + offset) % 4 === 3) { // ' >\t test ' // ^ -- position start of line here (tab has width===1) pos++; initial++; offset++; adjustTab = false; } else { // ' >\t test ' // ^ -- position start of line here + shift bsCount slightly // to make extra space appear adjustTab = true; } } else { spaceAfterMarker = false; } oldBMarks.push(state.bMarks[nextLine]); state.bMarks[nextLine] = pos; while (pos < max) { ch = state.src.charCodeAt(pos); if (isSpace(ch)) { if (ch === 0x09) { offset += 4 - (offset + state.bsCount[nextLine] + (adjustTab ? 1 : 0)) % 4; } else { offset++; } } else { break; } pos++; } lastLineEmpty = pos >= max; oldBSCount.push(state.bsCount[nextLine]); state.bsCount[nextLine] = state.sCount[nextLine] + 1 + (spaceAfterMarker ? 1 : 0); oldSCount.push(state.sCount[nextLine]); state.sCount[nextLine] = offset - initial; oldTShift.push(state.tShift[nextLine]); state.tShift[nextLine] = pos - state.bMarks[nextLine]; continue; } // Case 2: line is not inside the blockquote, and the last line was empty. if (lastLineEmpty) { break; } // Case 3: another tag found. terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { // Quirk to enforce "hard termination mode" for paragraphs; // normally if you call `tokenize(state, startLine, nextLine)`, // paragraphs will look below nextLine for paragraph continuation, // but if blockquote is terminated by another tag, they shouldn't state.lineMax = nextLine; if (state.blkIndent !== 0) { // state.blkIndent was non-zero, we now set it to zero, // so we need to re-calculate all offsets to appear as // if indent wasn't changed oldBMarks.push(state.bMarks[nextLine]); oldBSCount.push(state.bsCount[nextLine]); oldTShift.push(state.tShift[nextLine]); oldSCount.push(state.sCount[nextLine]); state.sCount[nextLine] -= state.blkIndent; } break; } oldBMarks.push(state.bMarks[nextLine]); oldBSCount.push(state.bsCount[nextLine]); oldTShift.push(state.tShift[nextLine]); oldSCount.push(state.sCount[nextLine]); // A negative indentation means that this is a paragraph continuation // state.sCount[nextLine] = -1; } oldIndent = state.blkIndent; state.blkIndent = 0; token = state.push('blockquote_open', 'blockquote', 1); token.markup = '>'; token.map = lines = [ startLine, 0 ]; state.md.block.tokenize(state, startLine, nextLine); token = state.push('blockquote_close', 'blockquote', -1); token.markup = '>'; state.lineMax = oldLineMax; state.parentType = oldParentType; lines[1] = state.line; // Restore original tShift; this might not be necessary since the parser // has already been here, but just to make sure we can do that. for (i = 0; i < oldTShift.length; i++) { state.bMarks[i + startLine] = oldBMarks[i]; state.tShift[i + startLine] = oldTShift[i]; state.sCount[i + startLine] = oldSCount[i]; state.bsCount[i + startLine] = oldBSCount[i]; } state.blkIndent = oldIndent; return true; }; /***/ }), /***/ 7693: /***/ ((module) => { "use strict"; // Code block (4 spaces padded) module.exports = function code(state, startLine, endLine/*, silent*/) { var nextLine, last, token; if (state.sCount[startLine] - state.blkIndent < 4) { return false; } last = nextLine = startLine + 1; while (nextLine < endLine) { if (state.isEmpty(nextLine)) { nextLine++; continue; } if (state.sCount[nextLine] - state.blkIndent >= 4) { nextLine++; last = nextLine; continue; } break; } state.line = last; token = state.push('code_block', 'code', 0); token.content = state.getLines(startLine, last, 4 + state.blkIndent, false) + '\n'; token.map = [ startLine, state.line ]; return true; }; /***/ }), /***/ 7749: /***/ ((module) => { "use strict"; // fences (``` lang, ~~~ lang) module.exports = function fence(state, startLine, endLine, silent) { var marker, len, params, nextLine, mem, token, markup, haveEndMarker = false, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } if (pos + 3 > max) { return false; } marker = state.src.charCodeAt(pos); if (marker !== 0x7E/* ~ */ && marker !== 0x60 /* ` */) { return false; } // scan marker length mem = pos; pos = state.skipChars(pos, marker); len = pos - mem; if (len < 3) { return false; } markup = state.src.slice(mem, pos); params = state.src.slice(pos, max); if (marker === 0x60 /* ` */) { if (params.indexOf(String.fromCharCode(marker)) >= 0) { return false; } } // Since start is found, we can report success here in validation mode if (silent) { return true; } // search end of block nextLine = startLine; for (;;) { nextLine++; if (nextLine >= endLine) { // unclosed block should be autoclosed by end of document. // also block seems to be autoclosed by end of parent break; } pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]; max = state.eMarks[nextLine]; if (pos < max && state.sCount[nextLine] < state.blkIndent) { // non-empty line with negative indent should stop the list: // - ``` // test break; } if (state.src.charCodeAt(pos) !== marker) { continue; } if (state.sCount[nextLine] - state.blkIndent >= 4) { // closing fence should be indented less than 4 spaces continue; } pos = state.skipChars(pos, marker); // closing code fence must be at least as long as the opening one if (pos - mem < len) { continue; } // make sure tail has spaces only pos = state.skipSpaces(pos); if (pos < max) { continue; } haveEndMarker = true; // found! break; } // If a fence has heading spaces, they should be removed from its inner block len = state.sCount[startLine]; state.line = nextLine + (haveEndMarker ? 1 : 0); token = state.push('fence', 'code', 0); token.info = params; token.content = state.getLines(startLine + 1, nextLine, len, true); token.markup = markup; token.map = [ startLine, state.line ]; return true; }; /***/ }), /***/ 2702: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // heading (#, ##, ...) var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function heading(state, startLine, endLine, silent) { var ch, level, tmp, token, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } ch = state.src.charCodeAt(pos); if (ch !== 0x23/* # */ || pos >= max) { return false; } // count heading level level = 1; ch = state.src.charCodeAt(++pos); while (ch === 0x23/* # */ && pos < max && level <= 6) { level++; ch = state.src.charCodeAt(++pos); } if (level > 6 || (pos < max && !isSpace(ch))) { return false; } if (silent) { return true; } // Let's cut tails like ' ### ' from the end of string max = state.skipSpacesBack(max, pos); tmp = state.skipCharsBack(max, 0x23, pos); // # if (tmp > pos && isSpace(state.src.charCodeAt(tmp - 1))) { max = tmp; } state.line = startLine + 1; token = state.push('heading_open', 'h' + String(level), 1); token.markup = '########'.slice(0, level); token.map = [ startLine, state.line ]; token = state.push('inline', '', 0); token.content = state.src.slice(pos, max).trim(); token.map = [ startLine, state.line ]; token.children = []; token = state.push('heading_close', 'h' + String(level), -1); token.markup = '########'.slice(0, level); return true; }; /***/ }), /***/ 3514: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Horizontal rule var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function hr(state, startLine, endLine, silent) { var marker, cnt, ch, token, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } marker = state.src.charCodeAt(pos++); // Check hr marker if (marker !== 0x2A/* * */ && marker !== 0x2D/* - */ && marker !== 0x5F/* _ */) { return false; } // markers can be mixed with spaces, but there should be at least 3 of them cnt = 1; while (pos < max) { ch = state.src.charCodeAt(pos++); if (ch !== marker && !isSpace(ch)) { return false; } if (ch === marker) { cnt++; } } if (cnt < 3) { return false; } if (silent) { return true; } state.line = startLine + 1; token = state.push('hr', 'hr', 0); token.map = [ startLine, state.line ]; token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); return true; }; /***/ }), /***/ 5732: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // HTML block var block_names = __nccwpck_require__(9035); var HTML_OPEN_CLOSE_TAG_RE = (__nccwpck_require__(6537)/* .HTML_OPEN_CLOSE_TAG_RE */ .q); // An array of opening and corresponding closing sequences for html tags, // last argument defines whether it can terminate a paragraph or not // var HTML_SEQUENCES = [ [ /^<(script|pre|style|textarea)(?=(\s|>|$))/i, /<\/(script|pre|style|textarea)>/i, true ], [ /^/, true ], [ /^<\?/, /\?>/, true ], [ /^/, true ], [ /^/, true ], [ new RegExp('^|$))', 'i'), /^$/, true ], [ new RegExp(HTML_OPEN_CLOSE_TAG_RE.source + '\\s*$'), /^$/, false ] ]; module.exports = function html_block(state, startLine, endLine, silent) { var i, nextLine, token, lineText, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } if (!state.md.options.html) { return false; } if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; } lineText = state.src.slice(pos, max); for (i = 0; i < HTML_SEQUENCES.length; i++) { if (HTML_SEQUENCES[i][0].test(lineText)) { break; } } if (i === HTML_SEQUENCES.length) { return false; } if (silent) { // true if this sequence can be a terminator, false otherwise return HTML_SEQUENCES[i][2]; } nextLine = startLine + 1; // If we are here - we detected HTML block. // Let's roll down till block end. if (!HTML_SEQUENCES[i][1].test(lineText)) { for (; nextLine < endLine; nextLine++) { if (state.sCount[nextLine] < state.blkIndent) { break; } pos = state.bMarks[nextLine] + state.tShift[nextLine]; max = state.eMarks[nextLine]; lineText = state.src.slice(pos, max); if (HTML_SEQUENCES[i][1].test(lineText)) { if (lineText.length !== 0) { nextLine++; } break; } } } state.line = nextLine; token = state.push('html_block', '', 0); token.map = [ startLine, nextLine ]; token.content = state.getLines(startLine, nextLine, state.blkIndent, true); return true; }; /***/ }), /***/ 3551: /***/ ((module) => { "use strict"; // lheading (---, ===) module.exports = function lheading(state, startLine, endLine/*, silent*/) { var content, terminate, i, l, token, pos, max, level, marker, nextLine = startLine + 1, oldParentType, terminatorRules = state.md.block.ruler.getRules('paragraph'); // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } oldParentType = state.parentType; state.parentType = 'paragraph'; // use paragraph to match terminatorRules // jump line-by-line until empty one or EOF for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { // this would be a code block normally, but after paragraph // it's considered a lazy continuation regardless of what's there if (state.sCount[nextLine] - state.blkIndent > 3) { continue; } // // Check for underline in setext header // if (state.sCount[nextLine] >= state.blkIndent) { pos = state.bMarks[nextLine] + state.tShift[nextLine]; max = state.eMarks[nextLine]; if (pos < max) { marker = state.src.charCodeAt(pos); if (marker === 0x2D/* - */ || marker === 0x3D/* = */) { pos = state.skipChars(pos, marker); pos = state.skipSpaces(pos); if (pos >= max) { level = (marker === 0x3D/* = */ ? 1 : 2); break; } } } } // quirk for blockquotes, this line should already be checked by that rule if (state.sCount[nextLine] < 0) { continue; } // Some tags can terminate paragraph without empty line. terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { break; } } if (!level) { // Didn't find valid underline return false; } content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); state.line = nextLine + 1; token = state.push('heading_open', 'h' + String(level), 1); token.markup = String.fromCharCode(marker); token.map = [ startLine, state.line ]; token = state.push('inline', '', 0); token.content = content; token.map = [ startLine, state.line - 1 ]; token.children = []; token = state.push('heading_close', 'h' + String(level), -1); token.markup = String.fromCharCode(marker); state.parentType = oldParentType; return true; }; /***/ }), /***/ 2050: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Lists var isSpace = (__nccwpck_require__(506).isSpace); // Search `[-+*][\n ]`, returns next pos after marker on success // or -1 on fail. function skipBulletListMarker(state, startLine) { var marker, pos, max, ch; pos = state.bMarks[startLine] + state.tShift[startLine]; max = state.eMarks[startLine]; marker = state.src.charCodeAt(pos++); // Check bullet if (marker !== 0x2A/* * */ && marker !== 0x2D/* - */ && marker !== 0x2B/* + */) { return -1; } if (pos < max) { ch = state.src.charCodeAt(pos); if (!isSpace(ch)) { // " -test " - is not a list item return -1; } } return pos; } // Search `\d+[.)][\n ]`, returns next pos after marker on success // or -1 on fail. function skipOrderedListMarker(state, startLine) { var ch, start = state.bMarks[startLine] + state.tShift[startLine], pos = start, max = state.eMarks[startLine]; // List marker should have at least 2 chars (digit + dot) if (pos + 1 >= max) { return -1; } ch = state.src.charCodeAt(pos++); if (ch < 0x30/* 0 */ || ch > 0x39/* 9 */) { return -1; } for (;;) { // EOL -> fail if (pos >= max) { return -1; } ch = state.src.charCodeAt(pos++); if (ch >= 0x30/* 0 */ && ch <= 0x39/* 9 */) { // List marker should have no more than 9 digits // (prevents integer overflow in browsers) if (pos - start >= 10) { return -1; } continue; } // found valid marker if (ch === 0x29/* ) */ || ch === 0x2e/* . */) { break; } return -1; } if (pos < max) { ch = state.src.charCodeAt(pos); if (!isSpace(ch)) { // " 1.test " - is not a list item return -1; } } return pos; } function markTightParagraphs(state, idx) { var i, l, level = state.level + 2; for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) { if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') { state.tokens[i + 2].hidden = true; state.tokens[i].hidden = true; i += 2; } } } module.exports = function list(state, startLine, endLine, silent) { var ch, contentStart, i, indent, indentAfterMarker, initial, isOrdered, itemLines, l, listLines, listTokIdx, markerCharCode, markerValue, max, nextLine, offset, oldListIndent, oldParentType, oldSCount, oldTShift, oldTight, pos, posAfterMarker, prevEmptyEnd, start, terminate, terminatorRules, token, isTerminatingParagraph = false, tight = true; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } // Special case: // - item 1 // - item 2 // - item 3 // - item 4 // - this one is a paragraph continuation if (state.listIndent >= 0 && state.sCount[startLine] - state.listIndent >= 4 && state.sCount[startLine] < state.blkIndent) { return false; } // limit conditions when list can interrupt // a paragraph (validation mode only) if (silent && state.parentType === 'paragraph') { // Next list item should still terminate previous list item; // // This code can fail if plugins use blkIndent as well as lists, // but I hope the spec gets fixed long before that happens. // if (state.sCount[startLine] >= state.blkIndent) { isTerminatingParagraph = true; } } // Detect list type and position after marker if ((posAfterMarker = skipOrderedListMarker(state, startLine)) >= 0) { isOrdered = true; start = state.bMarks[startLine] + state.tShift[startLine]; markerValue = Number(state.src.slice(start, posAfterMarker - 1)); // If we're starting a new ordered list right after // a paragraph, it should start with 1. if (isTerminatingParagraph && markerValue !== 1) return false; } else if ((posAfterMarker = skipBulletListMarker(state, startLine)) >= 0) { isOrdered = false; } else { return false; } // If we're starting a new unordered list right after // a paragraph, first line should not be empty. if (isTerminatingParagraph) { if (state.skipSpaces(posAfterMarker) >= state.eMarks[startLine]) return false; } // We should terminate list on style change. Remember first one to compare. markerCharCode = state.src.charCodeAt(posAfterMarker - 1); // For validation mode we can terminate immediately if (silent) { return true; } // Start list listTokIdx = state.tokens.length; if (isOrdered) { token = state.push('ordered_list_open', 'ol', 1); if (markerValue !== 1) { token.attrs = [ [ 'start', markerValue ] ]; } } else { token = state.push('bullet_list_open', 'ul', 1); } token.map = listLines = [ startLine, 0 ]; token.markup = String.fromCharCode(markerCharCode); // // Iterate list items // nextLine = startLine; prevEmptyEnd = false; terminatorRules = state.md.block.ruler.getRules('list'); oldParentType = state.parentType; state.parentType = 'list'; while (nextLine < endLine) { pos = posAfterMarker; max = state.eMarks[nextLine]; initial = offset = state.sCount[nextLine] + posAfterMarker - (state.bMarks[startLine] + state.tShift[startLine]); while (pos < max) { ch = state.src.charCodeAt(pos); if (ch === 0x09) { offset += 4 - (offset + state.bsCount[nextLine]) % 4; } else if (ch === 0x20) { offset++; } else { break; } pos++; } contentStart = pos; if (contentStart >= max) { // trimming space in "- \n 3" case, indent is 1 here indentAfterMarker = 1; } else { indentAfterMarker = offset - initial; } // If we have more than 4 spaces, the indent is 1 // (the rest is just indented code block) if (indentAfterMarker > 4) { indentAfterMarker = 1; } // " - test" // ^^^^^ - calculating total length of this thing indent = initial + indentAfterMarker; // Run subparser & write tokens token = state.push('list_item_open', 'li', 1); token.markup = String.fromCharCode(markerCharCode); token.map = itemLines = [ startLine, 0 ]; if (isOrdered) { token.info = state.src.slice(start, posAfterMarker - 1); } // change current state, then restore it after parser subcall oldTight = state.tight; oldTShift = state.tShift[startLine]; oldSCount = state.sCount[startLine]; // - example list // ^ listIndent position will be here // ^ blkIndent position will be here // oldListIndent = state.listIndent; state.listIndent = state.blkIndent; state.blkIndent = indent; state.tight = true; state.tShift[startLine] = contentStart - state.bMarks[startLine]; state.sCount[startLine] = offset; if (contentStart >= max && state.isEmpty(startLine + 1)) { // workaround for this case // (list item is empty, list terminates before "foo"): // ~~~~~~~~ // - // // foo // ~~~~~~~~ state.line = Math.min(state.line + 2, endLine); } else { state.md.block.tokenize(state, startLine, endLine, true); } // If any of list item is tight, mark list as tight if (!state.tight || prevEmptyEnd) { tight = false; } // Item become loose if finish with empty line, // but we should filter last element, because it means list finish prevEmptyEnd = (state.line - startLine) > 1 && state.isEmpty(state.line - 1); state.blkIndent = state.listIndent; state.listIndent = oldListIndent; state.tShift[startLine] = oldTShift; state.sCount[startLine] = oldSCount; state.tight = oldTight; token = state.push('list_item_close', 'li', -1); token.markup = String.fromCharCode(markerCharCode); nextLine = startLine = state.line; itemLines[1] = nextLine; contentStart = state.bMarks[startLine]; if (nextLine >= endLine) { break; } // // Try to check if list is terminated or continued. // if (state.sCount[nextLine] < state.blkIndent) { break; } // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { break; } // fail if terminating block found terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { break; } // fail if list has another type if (isOrdered) { posAfterMarker = skipOrderedListMarker(state, nextLine); if (posAfterMarker < 0) { break; } start = state.bMarks[nextLine] + state.tShift[nextLine]; } else { posAfterMarker = skipBulletListMarker(state, nextLine); if (posAfterMarker < 0) { break; } } if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { break; } } // Finalize list if (isOrdered) { token = state.push('ordered_list_close', 'ol', -1); } else { token = state.push('bullet_list_close', 'ul', -1); } token.markup = String.fromCharCode(markerCharCode); listLines[1] = nextLine; state.line = nextLine; state.parentType = oldParentType; // mark paragraphs tight if needed if (tight) { markTightParagraphs(state, listTokIdx); } return true; }; /***/ }), /***/ 9450: /***/ ((module) => { "use strict"; // Paragraph module.exports = function paragraph(state, startLine/*, endLine*/) { var content, terminate, i, l, token, oldParentType, nextLine = startLine + 1, terminatorRules = state.md.block.ruler.getRules('paragraph'), endLine = state.lineMax; oldParentType = state.parentType; state.parentType = 'paragraph'; // jump line-by-line until empty one or EOF for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { // this would be a code block normally, but after paragraph // it's considered a lazy continuation regardless of what's there if (state.sCount[nextLine] - state.blkIndent > 3) { continue; } // quirk for blockquotes, this line should already be checked by that rule if (state.sCount[nextLine] < 0) { continue; } // Some tags can terminate paragraph without empty line. terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { break; } } content = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); state.line = nextLine; token = state.push('paragraph_open', 'p', 1); token.map = [ startLine, state.line ]; token = state.push('inline', '', 0); token.content = content; token.map = [ startLine, state.line ]; token.children = []; token = state.push('paragraph_close', 'p', -1); state.parentType = oldParentType; return true; }; /***/ }), /***/ 2235: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; var normalizeReference = (__nccwpck_require__(506).normalizeReference); var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function reference(state, startLine, _endLine, silent) { var ch, destEndPos, destEndLineNo, endLine, href, i, l, label, labelEnd, oldParentType, res, start, str, terminate, terminatorRules, title, lines = 0, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine], nextLine = startLine + 1; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } if (state.src.charCodeAt(pos) !== 0x5B/* [ */) { return false; } // Simple check to quickly interrupt scan on [link](url) at the start of line. // Can be useful on practice: https://github.com/markdown-it/markdown-it/issues/54 while (++pos < max) { if (state.src.charCodeAt(pos) === 0x5D /* ] */ && state.src.charCodeAt(pos - 1) !== 0x5C/* \ */) { if (pos + 1 === max) { return false; } if (state.src.charCodeAt(pos + 1) !== 0x3A/* : */) { return false; } break; } } endLine = state.lineMax; // jump line-by-line until empty one or EOF terminatorRules = state.md.block.ruler.getRules('reference'); oldParentType = state.parentType; state.parentType = 'reference'; for (; nextLine < endLine && !state.isEmpty(nextLine); nextLine++) { // this would be a code block normally, but after paragraph // it's considered a lazy continuation regardless of what's there if (state.sCount[nextLine] - state.blkIndent > 3) { continue; } // quirk for blockquotes, this line should already be checked by that rule if (state.sCount[nextLine] < 0) { continue; } // Some tags can terminate paragraph without empty line. terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { break; } } str = state.getLines(startLine, nextLine, state.blkIndent, false).trim(); max = str.length; for (pos = 1; pos < max; pos++) { ch = str.charCodeAt(pos); if (ch === 0x5B /* [ */) { return false; } else if (ch === 0x5D /* ] */) { labelEnd = pos; break; } else if (ch === 0x0A /* \n */) { lines++; } else if (ch === 0x5C /* \ */) { pos++; if (pos < max && str.charCodeAt(pos) === 0x0A) { lines++; } } } if (labelEnd < 0 || str.charCodeAt(labelEnd + 1) !== 0x3A/* : */) { return false; } // [label]: destination 'title' // ^^^ skip optional whitespace here for (pos = labelEnd + 2; pos < max; pos++) { ch = str.charCodeAt(pos); if (ch === 0x0A) { lines++; } else if (isSpace(ch)) { /*eslint no-empty:0*/ } else { break; } } // [label]: destination 'title' // ^^^^^^^^^^^ parse this res = state.md.helpers.parseLinkDestination(str, pos, max); if (!res.ok) { return false; } href = state.md.normalizeLink(res.str); if (!state.md.validateLink(href)) { return false; } pos = res.pos; lines += res.lines; // save cursor state, we could require to rollback later destEndPos = pos; destEndLineNo = lines; // [label]: destination 'title' // ^^^ skipping those spaces start = pos; for (; pos < max; pos++) { ch = str.charCodeAt(pos); if (ch === 0x0A) { lines++; } else if (isSpace(ch)) { /*eslint no-empty:0*/ } else { break; } } // [label]: destination 'title' // ^^^^^^^ parse this res = state.md.helpers.parseLinkTitle(str, pos, max); if (pos < max && start !== pos && res.ok) { title = res.str; pos = res.pos; lines += res.lines; } else { title = ''; pos = destEndPos; lines = destEndLineNo; } // skip trailing spaces until the rest of the line while (pos < max) { ch = str.charCodeAt(pos); if (!isSpace(ch)) { break; } pos++; } if (pos < max && str.charCodeAt(pos) !== 0x0A) { if (title) { // garbage at the end of the line after title, // but it could still be a valid reference if we roll back title = ''; pos = destEndPos; lines = destEndLineNo; while (pos < max) { ch = str.charCodeAt(pos); if (!isSpace(ch)) { break; } pos++; } } } if (pos < max && str.charCodeAt(pos) !== 0x0A) { // garbage at the end of the line return false; } label = normalizeReference(str.slice(1, labelEnd)); if (!label) { // CommonMark 0.20 disallows empty labels return false; } // Reference can not terminate anything. This check is for safety only. /*istanbul ignore if*/ if (silent) { return true; } if (typeof state.env.references === 'undefined') { state.env.references = {}; } if (typeof state.env.references[label] === 'undefined') { state.env.references[label] = { title: title, href: href }; } state.parentType = oldParentType; state.line = startLine + lines + 1; return true; }; /***/ }), /***/ 9497: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Parser state class var Token = __nccwpck_require__(8622); var isSpace = (__nccwpck_require__(506).isSpace); function StateBlock(src, md, env, tokens) { var ch, s, start, pos, len, indent, offset, indent_found; this.src = src; // link to parser instance this.md = md; this.env = env; // // Internal state vartiables // this.tokens = tokens; this.bMarks = []; // line begin offsets for fast jumps this.eMarks = []; // line end offsets for fast jumps this.tShift = []; // offsets of the first non-space characters (tabs not expanded) this.sCount = []; // indents for each line (tabs expanded) // An amount of virtual spaces (tabs expanded) between beginning // of each line (bMarks) and real beginning of that line. // // It exists only as a hack because blockquotes override bMarks // losing information in the process. // // It's used only when expanding tabs, you can think about it as // an initial tab length, e.g. bsCount=21 applied to string `\t123` // means first tab should be expanded to 4-21%4 === 3 spaces. // this.bsCount = []; // block parser variables this.blkIndent = 0; // required block content indent (for example, if we are // inside a list, it would be positioned after list marker) this.line = 0; // line index in src this.lineMax = 0; // lines count this.tight = false; // loose/tight mode for lists this.ddIndent = -1; // indent of the current dd block (-1 if there isn't any) this.listIndent = -1; // indent of the current list block (-1 if there isn't any) // can be 'blockquote', 'list', 'root', 'paragraph' or 'reference' // used in lists to determine if they interrupt a paragraph this.parentType = 'root'; this.level = 0; // renderer this.result = ''; // Create caches // Generate markers. s = this.src; indent_found = false; for (start = pos = indent = offset = 0, len = s.length; pos < len; pos++) { ch = s.charCodeAt(pos); if (!indent_found) { if (isSpace(ch)) { indent++; if (ch === 0x09) { offset += 4 - offset % 4; } else { offset++; } continue; } else { indent_found = true; } } if (ch === 0x0A || pos === len - 1) { if (ch !== 0x0A) { pos++; } this.bMarks.push(start); this.eMarks.push(pos); this.tShift.push(indent); this.sCount.push(offset); this.bsCount.push(0); indent_found = false; indent = 0; offset = 0; start = pos + 1; } } // Push fake entry to simplify cache bounds checks this.bMarks.push(s.length); this.eMarks.push(s.length); this.tShift.push(0); this.sCount.push(0); this.bsCount.push(0); this.lineMax = this.bMarks.length - 1; // don't count last fake line } // Push new token to "stream". // StateBlock.prototype.push = function (type, tag, nesting) { var token = new Token(type, tag, nesting); token.block = true; if (nesting < 0) this.level--; // closing tag token.level = this.level; if (nesting > 0) this.level++; // opening tag this.tokens.push(token); return token; }; StateBlock.prototype.isEmpty = function isEmpty(line) { return this.bMarks[line] + this.tShift[line] >= this.eMarks[line]; }; StateBlock.prototype.skipEmptyLines = function skipEmptyLines(from) { for (var max = this.lineMax; from < max; from++) { if (this.bMarks[from] + this.tShift[from] < this.eMarks[from]) { break; } } return from; }; // Skip spaces from given position. StateBlock.prototype.skipSpaces = function skipSpaces(pos) { var ch; for (var max = this.src.length; pos < max; pos++) { ch = this.src.charCodeAt(pos); if (!isSpace(ch)) { break; } } return pos; }; // Skip spaces from given position in reverse. StateBlock.prototype.skipSpacesBack = function skipSpacesBack(pos, min) { if (pos <= min) { return pos; } while (pos > min) { if (!isSpace(this.src.charCodeAt(--pos))) { return pos + 1; } } return pos; }; // Skip char codes from given position StateBlock.prototype.skipChars = function skipChars(pos, code) { for (var max = this.src.length; pos < max; pos++) { if (this.src.charCodeAt(pos) !== code) { break; } } return pos; }; // Skip char codes reverse from given position - 1 StateBlock.prototype.skipCharsBack = function skipCharsBack(pos, code, min) { if (pos <= min) { return pos; } while (pos > min) { if (code !== this.src.charCodeAt(--pos)) { return pos + 1; } } return pos; }; // cut lines range from source. StateBlock.prototype.getLines = function getLines(begin, end, indent, keepLastLF) { var i, lineIndent, ch, first, last, queue, lineStart, line = begin; if (begin >= end) { return ''; } queue = new Array(end - begin); for (i = 0; line < end; line++, i++) { lineIndent = 0; lineStart = first = this.bMarks[line]; if (line + 1 < end || keepLastLF) { // No need for bounds check because we have fake entry on tail. last = this.eMarks[line] + 1; } else { last = this.eMarks[line]; } while (first < last && lineIndent < indent) { ch = this.src.charCodeAt(first); if (isSpace(ch)) { if (ch === 0x09) { lineIndent += 4 - (lineIndent + this.bsCount[line]) % 4; } else { lineIndent++; } } else if (first - lineStart < this.tShift[line]) { // patched tShift masked characters to look like spaces (blockquotes, list markers) lineIndent++; } else { break; } first++; } if (lineIndent > indent) { // partially expanding tabs in code blocks, e.g '\t\tfoobar' // with indent=2 becomes ' \tfoobar' queue[i] = new Array(lineIndent - indent + 1).join(' ') + this.src.slice(first, last); } else { queue[i] = this.src.slice(first, last); } } return queue.join(''); }; // re-export Token class to use in block rules StateBlock.prototype.Token = Token; module.exports = StateBlock; /***/ }), /***/ 7722: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // GFM table, https://github.github.com/gfm/#tables-extension- var isSpace = (__nccwpck_require__(506).isSpace); function getLine(state, line) { var pos = state.bMarks[line] + state.tShift[line], max = state.eMarks[line]; return state.src.slice(pos, max); } function escapedSplit(str) { var result = [], pos = 0, max = str.length, ch, isEscaped = false, lastPos = 0, current = ''; ch = str.charCodeAt(pos); while (pos < max) { if (ch === 0x7c/* | */) { if (!isEscaped) { // pipe separating cells, '|' result.push(current + str.substring(lastPos, pos)); current = ''; lastPos = pos + 1; } else { // escaped pipe, '\|' current += str.substring(lastPos, pos - 1); lastPos = pos; } } isEscaped = (ch === 0x5c/* \ */); pos++; ch = str.charCodeAt(pos); } result.push(current + str.substring(lastPos)); return result; } module.exports = function table(state, startLine, endLine, silent) { var ch, lineText, pos, i, l, nextLine, columns, columnCount, token, aligns, t, tableLines, tbodyLines, oldParentType, terminate, terminatorRules, firstCh, secondCh; // should have at least two lines if (startLine + 2 > endLine) { return false; } nextLine = startLine + 1; if (state.sCount[nextLine] < state.blkIndent) { return false; } // if it's indented more than 3 spaces, it should be a code block if (state.sCount[nextLine] - state.blkIndent >= 4) { return false; } // first character of the second line should be '|', '-', ':', // and no other characters are allowed but spaces; // basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp pos = state.bMarks[nextLine] + state.tShift[nextLine]; if (pos >= state.eMarks[nextLine]) { return false; } firstCh = state.src.charCodeAt(pos++); if (firstCh !== 0x7C/* | */ && firstCh !== 0x2D/* - */ && firstCh !== 0x3A/* : */) { return false; } if (pos >= state.eMarks[nextLine]) { return false; } secondCh = state.src.charCodeAt(pos++); if (secondCh !== 0x7C/* | */ && secondCh !== 0x2D/* - */ && secondCh !== 0x3A/* : */ && !isSpace(secondCh)) { return false; } // if first character is '-', then second character must not be a space // (due to parsing ambiguity with list) if (firstCh === 0x2D/* - */ && isSpace(secondCh)) { return false; } while (pos < state.eMarks[nextLine]) { ch = state.src.charCodeAt(pos); if (ch !== 0x7C/* | */ && ch !== 0x2D/* - */ && ch !== 0x3A/* : */ && !isSpace(ch)) { return false; } pos++; } lineText = getLine(state, startLine + 1); columns = lineText.split('|'); aligns = []; for (i = 0; i < columns.length; i++) { t = columns[i].trim(); if (!t) { // allow empty columns before and after table, but not in between columns; // e.g. allow ` |---| `, disallow ` ---||--- ` if (i === 0 || i === columns.length - 1) { continue; } else { return false; } } if (!/^:?-+:?$/.test(t)) { return false; } if (t.charCodeAt(t.length - 1) === 0x3A/* : */) { aligns.push(t.charCodeAt(0) === 0x3A/* : */ ? 'center' : 'right'); } else if (t.charCodeAt(0) === 0x3A/* : */) { aligns.push('left'); } else { aligns.push(''); } } lineText = getLine(state, startLine).trim(); if (lineText.indexOf('|') === -1) { return false; } if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } columns = escapedSplit(lineText); if (columns.length && columns[0] === '') columns.shift(); if (columns.length && columns[columns.length - 1] === '') columns.pop(); // header row will define an amount of columns in the entire table, // and align row should be exactly the same (the rest of the rows can differ) columnCount = columns.length; if (columnCount === 0 || columnCount !== aligns.length) { return false; } if (silent) { return true; } oldParentType = state.parentType; state.parentType = 'table'; // use 'blockquote' lists for termination because it's // the most similar to tables terminatorRules = state.md.block.ruler.getRules('blockquote'); token = state.push('table_open', 'table', 1); token.map = tableLines = [ startLine, 0 ]; token = state.push('thead_open', 'thead', 1); token.map = [ startLine, startLine + 1 ]; token = state.push('tr_open', 'tr', 1); token.map = [ startLine, startLine + 1 ]; for (i = 0; i < columns.length; i++) { token = state.push('th_open', 'th', 1); if (aligns[i]) { token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ]; } token = state.push('inline', '', 0); token.content = columns[i].trim(); token.children = []; token = state.push('th_close', 'th', -1); } token = state.push('tr_close', 'tr', -1); token = state.push('thead_close', 'thead', -1); for (nextLine = startLine + 2; nextLine < endLine; nextLine++) { if (state.sCount[nextLine] < state.blkIndent) { break; } terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { break; } lineText = getLine(state, nextLine).trim(); if (!lineText) { break; } if (state.sCount[nextLine] - state.blkIndent >= 4) { break; } columns = escapedSplit(lineText); if (columns.length && columns[0] === '') columns.shift(); if (columns.length && columns[columns.length - 1] === '') columns.pop(); if (nextLine === startLine + 2) { token = state.push('tbody_open', 'tbody', 1); token.map = tbodyLines = [ startLine + 2, 0 ]; } token = state.push('tr_open', 'tr', 1); token.map = [ nextLine, nextLine + 1 ]; for (i = 0; i < columnCount; i++) { token = state.push('td_open', 'td', 1); if (aligns[i]) { token.attrs = [ [ 'style', 'text-align:' + aligns[i] ] ]; } token = state.push('inline', '', 0); token.content = columns[i] ? columns[i].trim() : ''; token.children = []; token = state.push('td_close', 'td', -1); } token = state.push('tr_close', 'tr', -1); } if (tbodyLines) { token = state.push('tbody_close', 'tbody', -1); tbodyLines[1] = nextLine; } token = state.push('table_close', 'table', -1); tableLines[1] = nextLine; state.parentType = oldParentType; state.line = nextLine; return true; }; /***/ }), /***/ 31: /***/ ((module) => { "use strict"; module.exports = function block(state) { var token; if (state.inlineMode) { token = new state.Token('inline', '', 0); token.content = state.src; token.map = [ 0, 1 ]; token.children = []; state.tokens.push(token); } else { state.md.block.parse(state.src, state.md, state.env, state.tokens); } }; /***/ }), /***/ 1951: /***/ ((module) => { "use strict"; module.exports = function inline(state) { var tokens = state.tokens, tok, i, l; // Parse inlines for (i = 0, l = tokens.length; i < l; i++) { tok = tokens[i]; if (tok.type === 'inline') { state.md.inline.parse(tok.content, state.md, state.env, tok.children); } } }; /***/ }), /***/ 5462: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Replace link-like texts with link nodes. // // Currently restricted by `md.validateLink()` to http/https/ftp // var arrayReplaceAt = (__nccwpck_require__(506).arrayReplaceAt); function isLinkOpen(str) { return /^\s]/i.test(str); } function isLinkClose(str) { return /^<\/a\s*>/i.test(str); } module.exports = function linkify(state) { var i, j, l, tokens, token, currentToken, nodes, ln, text, pos, lastPos, level, htmlLinkLevel, url, fullUrl, urlText, blockTokens = state.tokens, links; if (!state.md.options.linkify) { return; } for (j = 0, l = blockTokens.length; j < l; j++) { if (blockTokens[j].type !== 'inline' || !state.md.linkify.pretest(blockTokens[j].content)) { continue; } tokens = blockTokens[j].children; htmlLinkLevel = 0; // We scan from the end, to keep position when new tags added. // Use reversed logic in links start/end match for (i = tokens.length - 1; i >= 0; i--) { currentToken = tokens[i]; // Skip content of markdown links if (currentToken.type === 'link_close') { i--; while (tokens[i].level !== currentToken.level && tokens[i].type !== 'link_open') { i--; } continue; } // Skip content of html tag links if (currentToken.type === 'html_inline') { if (isLinkOpen(currentToken.content) && htmlLinkLevel > 0) { htmlLinkLevel--; } if (isLinkClose(currentToken.content)) { htmlLinkLevel++; } } if (htmlLinkLevel > 0) { continue; } if (currentToken.type === 'text' && state.md.linkify.test(currentToken.content)) { text = currentToken.content; links = state.md.linkify.match(text); // Now split string to nodes nodes = []; level = currentToken.level; lastPos = 0; // forbid escape sequence at the start of the string, // this avoids http\://example.com/ from being linkified as // http://example.com/ if (links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === 'text_special') { links = links.slice(1); } for (ln = 0; ln < links.length; ln++) { url = links[ln].url; fullUrl = state.md.normalizeLink(url); if (!state.md.validateLink(fullUrl)) { continue; } urlText = links[ln].text; // Linkifier might send raw hostnames like "example.com", where url // starts with domain name. So we prepend http:// in those cases, // and remove it afterwards. // if (!links[ln].schema) { urlText = state.md.normalizeLinkText('http://' + urlText).replace(/^http:\/\//, ''); } else if (links[ln].schema === 'mailto:' && !/^mailto:/i.test(urlText)) { urlText = state.md.normalizeLinkText('mailto:' + urlText).replace(/^mailto:/, ''); } else { urlText = state.md.normalizeLinkText(urlText); } pos = links[ln].index; if (pos > lastPos) { token = new state.Token('text', '', 0); token.content = text.slice(lastPos, pos); token.level = level; nodes.push(token); } token = new state.Token('link_open', 'a', 1); token.attrs = [ [ 'href', fullUrl ] ]; token.level = level++; token.markup = 'linkify'; token.info = 'auto'; nodes.push(token); token = new state.Token('text', '', 0); token.content = urlText; token.level = level; nodes.push(token); token = new state.Token('link_close', 'a', -1); token.level = --level; token.markup = 'linkify'; token.info = 'auto'; nodes.push(token); lastPos = links[ln].lastIndex; } if (lastPos < text.length) { token = new state.Token('text', '', 0); token.content = text.slice(lastPos); token.level = level; nodes.push(token); } // replace current node blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, nodes); } } } }; /***/ }), /***/ 2764: /***/ ((module) => { "use strict"; // Normalize input string // https://spec.commonmark.org/0.29/#line-ending var NEWLINES_RE = /\r\n?|\n/g; var NULL_RE = /\0/g; module.exports = function normalize(state) { var str; // Normalize newlines str = state.src.replace(NEWLINES_RE, '\n'); // Replace NULL characters str = str.replace(NULL_RE, '\uFFFD'); state.src = str; }; /***/ }), /***/ 8373: /***/ ((module) => { "use strict"; // Simple typographic replacements // // (c) (C) → © // (tm) (TM) → ™ // (r) (R) → ® // +- → ± // (p) (P) -> § // ... → … (also ?.... → ?.., !.... → !..) // ???????? → ???, !!!!! → !!!, `,,` → `,` // -- → –, --- → — // // TODO: // - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾ // - multiplications 2 x 4 -> 2 × 4 var RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/; // Workaround for phantomjs - need regex without /g flag, // or root check will fail every second time var SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i; var SCOPED_ABBR_RE = /\((c|tm|r)\)/ig; var SCOPED_ABBR = { c: '©', r: '®', tm: '™' }; function replaceFn(match, name) { return SCOPED_ABBR[name.toLowerCase()]; } function replace_scoped(inlineTokens) { var i, token, inside_autolink = 0; for (i = inlineTokens.length - 1; i >= 0; i--) { token = inlineTokens[i]; if (token.type === 'text' && !inside_autolink) { token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn); } if (token.type === 'link_open' && token.info === 'auto') { inside_autolink--; } if (token.type === 'link_close' && token.info === 'auto') { inside_autolink++; } } } function replace_rare(inlineTokens) { var i, token, inside_autolink = 0; for (i = inlineTokens.length - 1; i >= 0; i--) { token = inlineTokens[i]; if (token.type === 'text' && !inside_autolink) { if (RARE_RE.test(token.content)) { token.content = token.content .replace(/\+-/g, '±') // .., ..., ....... -> … // but ?..... & !..... -> ?.. & !.. .replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..') .replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',') // em-dash .replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014') // en-dash .replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013') .replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013'); } } if (token.type === 'link_open' && token.info === 'auto') { inside_autolink--; } if (token.type === 'link_close' && token.info === 'auto') { inside_autolink++; } } } module.exports = function replace(state) { var blkIdx; if (!state.md.options.typographer) { return; } for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { if (state.tokens[blkIdx].type !== 'inline') { continue; } if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) { replace_scoped(state.tokens[blkIdx].children); } if (RARE_RE.test(state.tokens[blkIdx].content)) { replace_rare(state.tokens[blkIdx].children); } } }; /***/ }), /***/ 2178: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Convert straight quotation marks to typographic ones // var isWhiteSpace = (__nccwpck_require__(506).isWhiteSpace); var isPunctChar = (__nccwpck_require__(506).isPunctChar); var isMdAsciiPunct = (__nccwpck_require__(506).isMdAsciiPunct); var QUOTE_TEST_RE = /['"]/; var QUOTE_RE = /['"]/g; var APOSTROPHE = '\u2019'; /* ’ */ function replaceAt(str, index, ch) { return str.slice(0, index) + ch + str.slice(index + 1); } function process_inlines(tokens, state) { var i, token, text, t, pos, max, thisLevel, item, lastChar, nextChar, isLastPunctChar, isNextPunctChar, isLastWhiteSpace, isNextWhiteSpace, canOpen, canClose, j, isSingle, stack, openQuote, closeQuote; stack = []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; thisLevel = tokens[i].level; for (j = stack.length - 1; j >= 0; j--) { if (stack[j].level <= thisLevel) { break; } } stack.length = j + 1; if (token.type !== 'text') { continue; } text = token.content; pos = 0; max = text.length; /*eslint no-labels:0,block-scoped-var:0*/ OUTER: while (pos < max) { QUOTE_RE.lastIndex = pos; t = QUOTE_RE.exec(text); if (!t) { break; } canOpen = canClose = true; pos = t.index + 1; isSingle = (t[0] === "'"); // Find previous character, // default to space if it's the beginning of the line // lastChar = 0x20; if (t.index - 1 >= 0) { lastChar = text.charCodeAt(t.index - 1); } else { for (j = i - 1; j >= 0; j--) { if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // lastChar defaults to 0x20 if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' lastChar = tokens[j].content.charCodeAt(tokens[j].content.length - 1); break; } } // Find next character, // default to space if it's the end of the line // nextChar = 0x20; if (pos < max) { nextChar = text.charCodeAt(pos); } else { for (j = i + 1; j < tokens.length; j++) { if (tokens[j].type === 'softbreak' || tokens[j].type === 'hardbreak') break; // nextChar defaults to 0x20 if (!tokens[j].content) continue; // should skip all tokens except 'text', 'html_inline' or 'code_inline' nextChar = tokens[j].content.charCodeAt(0); break; } } isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); isLastWhiteSpace = isWhiteSpace(lastChar); isNextWhiteSpace = isWhiteSpace(nextChar); if (isNextWhiteSpace) { canOpen = false; } else if (isNextPunctChar) { if (!(isLastWhiteSpace || isLastPunctChar)) { canOpen = false; } } if (isLastWhiteSpace) { canClose = false; } else if (isLastPunctChar) { if (!(isNextWhiteSpace || isNextPunctChar)) { canClose = false; } } if (nextChar === 0x22 /* " */ && t[0] === '"') { if (lastChar >= 0x30 /* 0 */ && lastChar <= 0x39 /* 9 */) { // special case: 1"" - count first quote as an inch canClose = canOpen = false; } } if (canOpen && canClose) { // Replace quotes in the middle of punctuation sequence, but not // in the middle of the words, i.e.: // // 1. foo " bar " baz - not replaced // 2. foo-"-bar-"-baz - replaced // 3. foo"bar"baz - not replaced // canOpen = isLastPunctChar; canClose = isNextPunctChar; } if (!canOpen && !canClose) { // middle of word if (isSingle) { token.content = replaceAt(token.content, t.index, APOSTROPHE); } continue; } if (canClose) { // this could be a closing quote, rewind the stack to get a match for (j = stack.length - 1; j >= 0; j--) { item = stack[j]; if (stack[j].level < thisLevel) { break; } if (item.single === isSingle && stack[j].level === thisLevel) { item = stack[j]; if (isSingle) { openQuote = state.md.options.quotes[2]; closeQuote = state.md.options.quotes[3]; } else { openQuote = state.md.options.quotes[0]; closeQuote = state.md.options.quotes[1]; } // replace token.content *before* tokens[item.token].content, // because, if they are pointing at the same token, replaceAt // could mess up indices when quote length != 1 token.content = replaceAt(token.content, t.index, closeQuote); tokens[item.token].content = replaceAt( tokens[item.token].content, item.pos, openQuote); pos += closeQuote.length - 1; if (item.token === i) { pos += openQuote.length - 1; } text = token.content; max = text.length; stack.length = j; continue OUTER; } } } if (canOpen) { stack.push({ token: i, pos: t.index, single: isSingle, level: thisLevel }); } else if (canClose && isSingle) { token.content = replaceAt(token.content, t.index, APOSTROPHE); } } } } module.exports = function smartquotes(state) { /*eslint max-depth:0*/ var blkIdx; if (!state.md.options.typographer) { return; } for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) { if (state.tokens[blkIdx].type !== 'inline' || !QUOTE_TEST_RE.test(state.tokens[blkIdx].content)) { continue; } process_inlines(state.tokens[blkIdx].children, state); } }; /***/ }), /***/ 9052: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Core state object // var Token = __nccwpck_require__(8622); function StateCore(src, md, env) { this.src = src; this.env = env; this.tokens = []; this.inlineMode = false; this.md = md; // link to parser instance } // re-export Token class to use in core rules StateCore.prototype.Token = Token; module.exports = StateCore; /***/ }), /***/ 7502: /***/ ((module) => { "use strict"; // Join raw text tokens with the rest of the text // // This is set as a separate rule to provide an opportunity for plugins // to run text replacements after text join, but before escape join. // // For example, `\:)` shouldn't be replaced with an emoji. // module.exports = function text_join(state) { var j, l, tokens, curr, max, last, blockTokens = state.tokens; for (j = 0, l = blockTokens.length; j < l; j++) { if (blockTokens[j].type !== 'inline') continue; tokens = blockTokens[j].children; max = tokens.length; for (curr = 0; curr < max; curr++) { if (tokens[curr].type === 'text_special') { tokens[curr].type = 'text'; } } for (curr = last = 0; curr < max; curr++) { if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { // collapse two adjacent text nodes tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; } else { if (curr !== last) { tokens[last] = tokens[curr]; } last++; } } if (curr !== last) { tokens.length = last; } } }; /***/ }), /***/ 3939: /***/ ((module) => { "use strict"; // Process autolinks '' /*eslint max-len:0*/ var EMAIL_RE = /^([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/; var AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$/; module.exports = function autolink(state, silent) { var url, fullUrl, token, ch, start, max, pos = state.pos; if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; } start = state.pos; max = state.posMax; for (;;) { if (++pos >= max) return false; ch = state.src.charCodeAt(pos); if (ch === 0x3C /* < */) return false; if (ch === 0x3E /* > */) break; } url = state.src.slice(start + 1, pos); if (AUTOLINK_RE.test(url)) { fullUrl = state.md.normalizeLink(url); if (!state.md.validateLink(fullUrl)) { return false; } if (!silent) { token = state.push('link_open', 'a', 1); token.attrs = [ [ 'href', fullUrl ] ]; token.markup = 'autolink'; token.info = 'auto'; token = state.push('text', '', 0); token.content = state.md.normalizeLinkText(url); token = state.push('link_close', 'a', -1); token.markup = 'autolink'; token.info = 'auto'; } state.pos += url.length + 2; return true; } if (EMAIL_RE.test(url)) { fullUrl = state.md.normalizeLink('mailto:' + url); if (!state.md.validateLink(fullUrl)) { return false; } if (!silent) { token = state.push('link_open', 'a', 1); token.attrs = [ [ 'href', fullUrl ] ]; token.markup = 'autolink'; token.info = 'auto'; token = state.push('text', '', 0); token.content = state.md.normalizeLinkText(url); token = state.push('link_close', 'a', -1); token.markup = 'autolink'; token.info = 'auto'; } state.pos += url.length + 2; return true; } return false; }; /***/ }), /***/ 8520: /***/ ((module) => { "use strict"; // Parse backticks module.exports = function backtick(state, silent) { var start, max, marker, token, matchStart, matchEnd, openerLength, closerLength, pos = state.pos, ch = state.src.charCodeAt(pos); if (ch !== 0x60/* ` */) { return false; } start = pos; pos++; max = state.posMax; // scan marker length while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; } marker = state.src.slice(start, pos); openerLength = marker.length; if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) { if (!silent) state.pending += marker; state.pos += openerLength; return true; } matchStart = matchEnd = pos; // Nothing found in the cache, scan until the end of the line (or until marker is found) while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { matchEnd = matchStart + 1; // scan marker length while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; } closerLength = matchEnd - matchStart; if (closerLength === openerLength) { // Found matching closer length. if (!silent) { token = state.push('code_inline', 'code', 0); token.markup = marker; token.content = state.src.slice(pos, matchStart) .replace(/\n/g, ' ') .replace(/^ (.+) $/, '$1'); } state.pos = matchEnd; return true; } // Some different length found, put it in cache as upper limit of where closer can be found state.backticks[closerLength] = matchStart; } // Scanned through the end, didn't find anything state.backticksScanned = true; if (!silent) state.pending += marker; state.pos += openerLength; return true; }; /***/ }), /***/ 9418: /***/ ((module) => { "use strict"; // For each opening emphasis-like marker find a matching closing one // function processDelimiters(state, delimiters) { var closerIdx, openerIdx, closer, opener, minOpenerIdx, newMinOpenerIdx, isOddMatch, lastJump, openersBottom = {}, max = delimiters.length; if (!max) return; // headerIdx is the first delimiter of the current (where closer is) delimiter run var headerIdx = 0; var lastTokenIdx = -2; // needs any value lower than -1 var jumps = []; for (closerIdx = 0; closerIdx < max; closerIdx++) { closer = delimiters[closerIdx]; jumps.push(0); // markers belong to same delimiter run if: // - they have adjacent tokens // - AND markers are the same // if (delimiters[headerIdx].marker !== closer.marker || lastTokenIdx !== closer.token - 1) { headerIdx = closerIdx; } lastTokenIdx = closer.token; // Length is only used for emphasis-specific "rule of 3", // if it's not defined (in strikethrough or 3rd party plugins), // we can default it to 0 to disable those checks. // closer.length = closer.length || 0; if (!closer.close) continue; // Previously calculated lower bounds (previous fails) // for each marker, each delimiter length modulo 3, // and for whether this closer can be an opener; // https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460 if (!openersBottom.hasOwnProperty(closer.marker)) { openersBottom[closer.marker] = [ -1, -1, -1, -1, -1, -1 ]; } minOpenerIdx = openersBottom[closer.marker][(closer.open ? 3 : 0) + (closer.length % 3)]; openerIdx = headerIdx - jumps[headerIdx] - 1; newMinOpenerIdx = openerIdx; for (; openerIdx > minOpenerIdx; openerIdx -= jumps[openerIdx] + 1) { opener = delimiters[openerIdx]; if (opener.marker !== closer.marker) continue; if (opener.open && opener.end < 0) { isOddMatch = false; // from spec: // // If one of the delimiters can both open and close emphasis, then the // sum of the lengths of the delimiter runs containing the opening and // closing delimiters must not be a multiple of 3 unless both lengths // are multiples of 3. // if (opener.close || closer.open) { if ((opener.length + closer.length) % 3 === 0) { if (opener.length % 3 !== 0 || closer.length % 3 !== 0) { isOddMatch = true; } } } if (!isOddMatch) { // If previous delimiter cannot be an opener, we can safely skip // the entire sequence in future checks. This is required to make // sure algorithm has linear complexity (see *_*_*_*_*_... case). // lastJump = openerIdx > 0 && !delimiters[openerIdx - 1].open ? jumps[openerIdx - 1] + 1 : 0; jumps[closerIdx] = closerIdx - openerIdx + lastJump; jumps[openerIdx] = lastJump; closer.open = false; opener.end = closerIdx; opener.close = false; newMinOpenerIdx = -1; // treat next token as start of run, // it optimizes skips in **<...>**a**<...>** pathological case lastTokenIdx = -2; break; } } } if (newMinOpenerIdx !== -1) { // If match for this delimiter run failed, we want to set lower bound for // future lookups. This is required to make sure algorithm has linear // complexity. // // See details here: // https://github.com/commonmark/cmark/issues/178#issuecomment-270417442 // openersBottom[closer.marker][(closer.open ? 3 : 0) + ((closer.length || 0) % 3)] = newMinOpenerIdx; } } } module.exports = function link_pairs(state) { var curr, tokens_meta = state.tokens_meta, max = state.tokens_meta.length; processDelimiters(state, state.delimiters); for (curr = 0; curr < max; curr++) { if (tokens_meta[curr] && tokens_meta[curr].delimiters) { processDelimiters(state, tokens_meta[curr].delimiters); } } }; /***/ }), /***/ 1677: /***/ ((module) => { "use strict"; // Process *this* and _that_ // // Insert each marker as a separate text token, and add it to delimiter list // module.exports.w = function emphasis(state, silent) { var i, scanned, token, start = state.pos, marker = state.src.charCodeAt(start); if (silent) { return false; } if (marker !== 0x5F /* _ */ && marker !== 0x2A /* * */) { return false; } scanned = state.scanDelims(state.pos, marker === 0x2A); for (i = 0; i < scanned.length; i++) { token = state.push('text', '', 0); token.content = String.fromCharCode(marker); state.delimiters.push({ // Char code of the starting marker (number). // marker: marker, // Total length of these series of delimiters. // length: scanned.length, // A position of the token this delimiter corresponds to. // token: state.tokens.length - 1, // If this delimiter is matched as a valid opener, `end` will be // equal to its position, otherwise it's `-1`. // end: -1, // Boolean flags that determine if this delimiter could open or close // an emphasis. // open: scanned.can_open, close: scanned.can_close }); } state.pos += scanned.length; return true; }; function postProcess(state, delimiters) { var i, startDelim, endDelim, token, ch, isStrong, max = delimiters.length; for (i = max - 1; i >= 0; i--) { startDelim = delimiters[i]; if (startDelim.marker !== 0x5F/* _ */ && startDelim.marker !== 0x2A/* * */) { continue; } // Process only opening markers if (startDelim.end === -1) { continue; } endDelim = delimiters[startDelim.end]; // If the previous delimiter has the same marker and is adjacent to this one, // merge those into one strong delimiter. // // `whatever` -> `whatever` // isStrong = i > 0 && delimiters[i - 1].end === startDelim.end + 1 && // check that first two markers match and adjacent delimiters[i - 1].marker === startDelim.marker && delimiters[i - 1].token === startDelim.token - 1 && // check that last two markers are adjacent (we can safely assume they match) delimiters[startDelim.end + 1].token === endDelim.token + 1; ch = String.fromCharCode(startDelim.marker); token = state.tokens[startDelim.token]; token.type = isStrong ? 'strong_open' : 'em_open'; token.tag = isStrong ? 'strong' : 'em'; token.nesting = 1; token.markup = isStrong ? ch + ch : ch; token.content = ''; token = state.tokens[endDelim.token]; token.type = isStrong ? 'strong_close' : 'em_close'; token.tag = isStrong ? 'strong' : 'em'; token.nesting = -1; token.markup = isStrong ? ch + ch : ch; token.content = ''; if (isStrong) { state.tokens[delimiters[i - 1].token].content = ''; state.tokens[delimiters[startDelim.end + 1].token].content = ''; i--; } } } // Walk through delimiter list and replace text tokens with tags // module.exports.g = function emphasis(state) { var curr, tokens_meta = state.tokens_meta, max = state.tokens_meta.length; postProcess(state, state.delimiters); for (curr = 0; curr < max; curr++) { if (tokens_meta[curr] && tokens_meta[curr].delimiters) { postProcess(state, tokens_meta[curr].delimiters); } } }; /***/ }), /***/ 973: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Process html entity - {, ¯, ", ... var entities = __nccwpck_require__(9220); var has = (__nccwpck_require__(506).has); var isValidEntityCode = (__nccwpck_require__(506).isValidEntityCode); var fromCodePoint = (__nccwpck_require__(506).fromCodePoint); var DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i; var NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i; module.exports = function entity(state, silent) { var ch, code, match, token, pos = state.pos, max = state.posMax; if (state.src.charCodeAt(pos) !== 0x26/* & */) return false; if (pos + 1 >= max) return false; ch = state.src.charCodeAt(pos + 1); if (ch === 0x23 /* # */) { match = state.src.slice(pos).match(DIGITAL_RE); if (match) { if (!silent) { code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10); token = state.push('text_special', '', 0); token.content = isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD); token.markup = match[0]; token.info = 'entity'; } state.pos += match[0].length; return true; } } else { match = state.src.slice(pos).match(NAMED_RE); if (match) { if (has(entities, match[1])) { if (!silent) { token = state.push('text_special', '', 0); token.content = entities[match[1]]; token.markup = match[0]; token.info = 'entity'; } state.pos += match[0].length; return true; } } } return false; }; /***/ }), /***/ 1836: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Process escaped chars and hardbreaks var isSpace = (__nccwpck_require__(506).isSpace); var ESCAPED = []; for (var i = 0; i < 256; i++) { ESCAPED.push(0); } '\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-' .split('').forEach(function (ch) { ESCAPED[ch.charCodeAt(0)] = 1; }); module.exports = function escape(state, silent) { var ch1, ch2, origStr, escapedStr, token, pos = state.pos, max = state.posMax; if (state.src.charCodeAt(pos) !== 0x5C/* \ */) return false; pos++; // '\' at the end of the inline block if (pos >= max) return false; ch1 = state.src.charCodeAt(pos); if (ch1 === 0x0A) { if (!silent) { state.push('hardbreak', 'br', 0); } pos++; // skip leading whitespaces from next line while (pos < max) { ch1 = state.src.charCodeAt(pos); if (!isSpace(ch1)) break; pos++; } state.pos = pos; return true; } escapedStr = state.src[pos]; if (ch1 >= 0xD800 && ch1 <= 0xDBFF && pos + 1 < max) { ch2 = state.src.charCodeAt(pos + 1); if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { escapedStr += state.src[pos + 1]; pos++; } } origStr = '\\' + escapedStr; if (!silent) { token = state.push('text_special', '', 0); if (ch1 < 256 && ESCAPED[ch1] !== 0) { token.content = escapedStr; } else { token.content = origStr; } token.markup = origStr; token.info = 'escape'; } state.pos = pos + 1; return true; }; /***/ }), /***/ 3807: /***/ ((module) => { "use strict"; // Clean up tokens after emphasis and strikethrough postprocessing: // merge adjacent text nodes into one and re-calculate all token levels // // This is necessary because initially emphasis delimiter markers (*, _, ~) // are treated as their own separate text tokens. Then emphasis rule either // leaves them as text (needed to merge with adjacent text) or turns them // into opening/closing tags (which messes up levels inside). // module.exports = function fragments_join(state) { var curr, last, level = 0, tokens = state.tokens, max = state.tokens.length; for (curr = last = 0; curr < max; curr++) { // re-calculate levels after emphasis/strikethrough turns some text nodes // into opening/closing tags if (tokens[curr].nesting < 0) level--; // closing tag tokens[curr].level = level; if (tokens[curr].nesting > 0) level++; // opening tag if (tokens[curr].type === 'text' && curr + 1 < max && tokens[curr + 1].type === 'text') { // collapse two adjacent text nodes tokens[curr + 1].content = tokens[curr].content + tokens[curr + 1].content; } else { if (curr !== last) { tokens[last] = tokens[curr]; } last++; } } if (curr !== last) { tokens.length = last; } }; /***/ }), /***/ 7753: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Process html tags var HTML_TAG_RE = (__nccwpck_require__(6537)/* .HTML_TAG_RE */ .n); function isLinkOpen(str) { return /^\s]/i.test(str); } function isLinkClose(str) { return /^<\/a\s*>/i.test(str); } function isLetter(ch) { /*eslint no-bitwise:0*/ var lc = ch | 0x20; // to lower case return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */); } module.exports = function html_inline(state, silent) { var ch, match, max, token, pos = state.pos; if (!state.md.options.html) { return false; } // Check start max = state.posMax; if (state.src.charCodeAt(pos) !== 0x3C/* < */ || pos + 2 >= max) { return false; } // Quick fail on second char ch = state.src.charCodeAt(pos + 1); if (ch !== 0x21/* ! */ && ch !== 0x3F/* ? */ && ch !== 0x2F/* / */ && !isLetter(ch)) { return false; } match = state.src.slice(pos).match(HTML_TAG_RE); if (!match) { return false; } if (!silent) { token = state.push('html_inline', '', 0); token.content = state.src.slice(pos, pos + match[0].length); if (isLinkOpen(token.content)) state.linkLevel++; if (isLinkClose(token.content)) state.linkLevel--; } state.pos += match[0].length; return true; }; /***/ }), /***/ 9998: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Process ![image]( "title") var normalizeReference = (__nccwpck_require__(506).normalizeReference); var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function image(state, silent) { var attrs, code, content, label, labelEnd, labelStart, pos, ref, res, title, token, tokens, start, href = '', oldPos = state.pos, max = state.posMax; if (state.src.charCodeAt(state.pos) !== 0x21/* ! */) { return false; } if (state.src.charCodeAt(state.pos + 1) !== 0x5B/* [ */) { return false; } labelStart = state.pos + 2; labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, false); // parser failed to find ']', so it's not a valid link if (labelEnd < 0) { return false; } pos = labelEnd + 1; if (pos < max && state.src.charCodeAt(pos) === 0x28/* ( */) { // // Inline link // // [link]( "title" ) // ^^ skipping these spaces pos++; for (; pos < max; pos++) { code = state.src.charCodeAt(pos); if (!isSpace(code) && code !== 0x0A) { break; } } if (pos >= max) { return false; } // [link]( "title" ) // ^^^^^^ parsing link destination start = pos; res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); if (res.ok) { href = state.md.normalizeLink(res.str); if (state.md.validateLink(href)) { pos = res.pos; } else { href = ''; } } // [link]( "title" ) // ^^ skipping these spaces start = pos; for (; pos < max; pos++) { code = state.src.charCodeAt(pos); if (!isSpace(code) && code !== 0x0A) { break; } } // [link]( "title" ) // ^^^^^^^ parsing link title res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); if (pos < max && start !== pos && res.ok) { title = res.str; pos = res.pos; // [link]( "title" ) // ^^ skipping these spaces for (; pos < max; pos++) { code = state.src.charCodeAt(pos); if (!isSpace(code) && code !== 0x0A) { break; } } } else { title = ''; } if (pos >= max || state.src.charCodeAt(pos) !== 0x29/* ) */) { state.pos = oldPos; return false; } pos++; } else { // // Link reference // if (typeof state.env.references === 'undefined') { return false; } if (pos < max && state.src.charCodeAt(pos) === 0x5B/* [ */) { start = pos + 1; pos = state.md.helpers.parseLinkLabel(state, pos); if (pos >= 0) { label = state.src.slice(start, pos++); } else { pos = labelEnd + 1; } } else { pos = labelEnd + 1; } // covers label === '' and label === undefined // (collapsed reference link and shortcut reference link respectively) if (!label) { label = state.src.slice(labelStart, labelEnd); } ref = state.env.references[normalizeReference(label)]; if (!ref) { state.pos = oldPos; return false; } href = ref.href; title = ref.title; } // // We found the end of the link, and know for a fact it's a valid link; // so all that's left to do is to call tokenizer. // if (!silent) { content = state.src.slice(labelStart, labelEnd); state.md.inline.parse( content, state.md, state.env, tokens = [] ); token = state.push('image', 'img', 0); token.attrs = attrs = [ [ 'src', href ], [ 'alt', '' ] ]; token.children = tokens; token.content = content; if (title) { attrs.push([ 'title', title ]); } } state.pos = pos; state.posMax = max; return true; }; /***/ }), /***/ 8798: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Process [link]( "stuff") var normalizeReference = (__nccwpck_require__(506).normalizeReference); var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function link(state, silent) { var attrs, code, label, labelEnd, labelStart, pos, res, ref, token, href = '', title = '', oldPos = state.pos, max = state.posMax, start = state.pos, parseReference = true; if (state.src.charCodeAt(state.pos) !== 0x5B/* [ */) { return false; } labelStart = state.pos + 1; labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, true); // parser failed to find ']', so it's not a valid link if (labelEnd < 0) { return false; } pos = labelEnd + 1; if (pos < max && state.src.charCodeAt(pos) === 0x28/* ( */) { // // Inline link // // might have found a valid shortcut link, disable reference parsing parseReference = false; // [link]( "title" ) // ^^ skipping these spaces pos++; for (; pos < max; pos++) { code = state.src.charCodeAt(pos); if (!isSpace(code) && code !== 0x0A) { break; } } if (pos >= max) { return false; } // [link]( "title" ) // ^^^^^^ parsing link destination start = pos; res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax); if (res.ok) { href = state.md.normalizeLink(res.str); if (state.md.validateLink(href)) { pos = res.pos; } else { href = ''; } // [link]( "title" ) // ^^ skipping these spaces start = pos; for (; pos < max; pos++) { code = state.src.charCodeAt(pos); if (!isSpace(code) && code !== 0x0A) { break; } } // [link]( "title" ) // ^^^^^^^ parsing link title res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax); if (pos < max && start !== pos && res.ok) { title = res.str; pos = res.pos; // [link]( "title" ) // ^^ skipping these spaces for (; pos < max; pos++) { code = state.src.charCodeAt(pos); if (!isSpace(code) && code !== 0x0A) { break; } } } } if (pos >= max || state.src.charCodeAt(pos) !== 0x29/* ) */) { // parsing a valid shortcut link failed, fallback to reference parseReference = true; } pos++; } if (parseReference) { // // Link reference // if (typeof state.env.references === 'undefined') { return false; } if (pos < max && state.src.charCodeAt(pos) === 0x5B/* [ */) { start = pos + 1; pos = state.md.helpers.parseLinkLabel(state, pos); if (pos >= 0) { label = state.src.slice(start, pos++); } else { pos = labelEnd + 1; } } else { pos = labelEnd + 1; } // covers label === '' and label === undefined // (collapsed reference link and shortcut reference link respectively) if (!label) { label = state.src.slice(labelStart, labelEnd); } ref = state.env.references[normalizeReference(label)]; if (!ref) { state.pos = oldPos; return false; } href = ref.href; title = ref.title; } // // We found the end of the link, and know for a fact it's a valid link; // so all that's left to do is to call tokenizer. // if (!silent) { state.pos = labelStart; state.posMax = labelEnd; token = state.push('link_open', 'a', 1); token.attrs = attrs = [ [ 'href', href ] ]; if (title) { attrs.push([ 'title', title ]); } state.linkLevel++; state.md.inline.tokenize(state); state.linkLevel--; token = state.push('link_close', 'a', -1); } state.pos = pos; state.posMax = max; return true; }; /***/ }), /***/ 1783: /***/ ((module) => { "use strict"; // Process links like https://example.org/ // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i; module.exports = function linkify(state, silent) { var pos, max, match, proto, link, url, fullUrl, token; if (!state.md.options.linkify) return false; if (state.linkLevel > 0) return false; pos = state.pos; max = state.posMax; if (pos + 3 > max) return false; if (state.src.charCodeAt(pos) !== 0x3A/* : */) return false; if (state.src.charCodeAt(pos + 1) !== 0x2F/* / */) return false; if (state.src.charCodeAt(pos + 2) !== 0x2F/* / */) return false; match = state.pending.match(SCHEME_RE); if (!match) return false; proto = match[1]; link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length)); if (!link) return false; url = link.url; // disallow '*' at the end of the link (conflicts with emphasis) url = url.replace(/\*+$/, ''); fullUrl = state.md.normalizeLink(url); if (!state.md.validateLink(fullUrl)) return false; if (!silent) { state.pending = state.pending.slice(0, -proto.length); token = state.push('link_open', 'a', 1); token.attrs = [ [ 'href', fullUrl ] ]; token.markup = 'linkify'; token.info = 'auto'; token = state.push('text', '', 0); token.content = state.md.normalizeLinkText(url); token = state.push('link_close', 'a', -1); token.markup = 'linkify'; token.info = 'auto'; } state.pos += url.length - proto.length; return true; }; /***/ }), /***/ 8774: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Proceess '\n' var isSpace = (__nccwpck_require__(506).isSpace); module.exports = function newline(state, silent) { var pmax, max, ws, pos = state.pos; if (state.src.charCodeAt(pos) !== 0x0A/* \n */) { return false; } pmax = state.pending.length - 1; max = state.posMax; // ' \n' -> hardbreak // Lookup in pending chars is bad practice! Don't copy to other rules! // Pending string is stored in concat mode, indexed lookups will cause // convertion to flat mode. if (!silent) { if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) { if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) { // Find whitespaces tail of pending chars. ws = pmax - 1; while (ws >= 1 && state.pending.charCodeAt(ws - 1) === 0x20) ws--; state.pending = state.pending.slice(0, ws); state.push('hardbreak', 'br', 0); } else { state.pending = state.pending.slice(0, -1); state.push('softbreak', 'br', 0); } } else { state.push('softbreak', 'br', 0); } } pos++; // skip heading spaces for next line while (pos < max && isSpace(state.src.charCodeAt(pos))) { pos++; } state.pos = pos; return true; }; /***/ }), /***/ 1247: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // Inline parser state var Token = __nccwpck_require__(8622); var isWhiteSpace = (__nccwpck_require__(506).isWhiteSpace); var isPunctChar = (__nccwpck_require__(506).isPunctChar); var isMdAsciiPunct = (__nccwpck_require__(506).isMdAsciiPunct); function StateInline(src, md, env, outTokens) { this.src = src; this.env = env; this.md = md; this.tokens = outTokens; this.tokens_meta = Array(outTokens.length); this.pos = 0; this.posMax = this.src.length; this.level = 0; this.pending = ''; this.pendingLevel = 0; // Stores { start: end } pairs. Useful for backtrack // optimization of pairs parse (emphasis, strikes). this.cache = {}; // List of emphasis-like delimiters for current tag this.delimiters = []; // Stack of delimiter lists for upper level tags this._prev_delimiters = []; // backtick length => last seen position this.backticks = {}; this.backticksScanned = false; // Counter used to disable inline linkify-it execution // inside and markdown links this.linkLevel = 0; } // Flush pending text // StateInline.prototype.pushPending = function () { var token = new Token('text', '', 0); token.content = this.pending; token.level = this.pendingLevel; this.tokens.push(token); this.pending = ''; return token; }; // Push new token to "stream". // If pending text exists - flush it as text token // StateInline.prototype.push = function (type, tag, nesting) { if (this.pending) { this.pushPending(); } var token = new Token(type, tag, nesting); var token_meta = null; if (nesting < 0) { // closing tag this.level--; this.delimiters = this._prev_delimiters.pop(); } token.level = this.level; if (nesting > 0) { // opening tag this.level++; this._prev_delimiters.push(this.delimiters); this.delimiters = []; token_meta = { delimiters: this.delimiters }; } this.pendingLevel = this.level; this.tokens.push(token); this.tokens_meta.push(token_meta); return token; }; // Scan a sequence of emphasis-like markers, and determine whether // it can start an emphasis sequence or end an emphasis sequence. // // - start - position to scan from (it should point at a valid marker); // - canSplitWord - determine if these markers can be found inside a word // StateInline.prototype.scanDelims = function (start, canSplitWord) { var pos = start, lastChar, nextChar, count, can_open, can_close, isLastWhiteSpace, isLastPunctChar, isNextWhiteSpace, isNextPunctChar, left_flanking = true, right_flanking = true, max = this.posMax, marker = this.src.charCodeAt(start); // treat beginning of the line as a whitespace lastChar = start > 0 ? this.src.charCodeAt(start - 1) : 0x20; while (pos < max && this.src.charCodeAt(pos) === marker) { pos++; } count = pos - start; // treat end of the line as a whitespace nextChar = pos < max ? this.src.charCodeAt(pos) : 0x20; isLastPunctChar = isMdAsciiPunct(lastChar) || isPunctChar(String.fromCharCode(lastChar)); isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)); isLastWhiteSpace = isWhiteSpace(lastChar); isNextWhiteSpace = isWhiteSpace(nextChar); if (isNextWhiteSpace) { left_flanking = false; } else if (isNextPunctChar) { if (!(isLastWhiteSpace || isLastPunctChar)) { left_flanking = false; } } if (isLastWhiteSpace) { right_flanking = false; } else if (isLastPunctChar) { if (!(isNextWhiteSpace || isNextPunctChar)) { right_flanking = false; } } if (!canSplitWord) { can_open = left_flanking && (!right_flanking || isLastPunctChar); can_close = right_flanking && (!left_flanking || isNextPunctChar); } else { can_open = left_flanking; can_close = right_flanking; } return { can_open: can_open, can_close: can_close, length: count }; }; // re-export Token class to use in block rules StateInline.prototype.Token = Token; module.exports = StateInline; /***/ }), /***/ 3015: /***/ ((module) => { "use strict"; // ~~strike through~~ // // Insert each marker as a separate text token, and add it to delimiter list // module.exports.w = function strikethrough(state, silent) { var i, scanned, token, len, ch, start = state.pos, marker = state.src.charCodeAt(start); if (silent) { return false; } if (marker !== 0x7E/* ~ */) { return false; } scanned = state.scanDelims(state.pos, true); len = scanned.length; ch = String.fromCharCode(marker); if (len < 2) { return false; } if (len % 2) { token = state.push('text', '', 0); token.content = ch; len--; } for (i = 0; i < len; i += 2) { token = state.push('text', '', 0); token.content = ch + ch; state.delimiters.push({ marker: marker, length: 0, // disable "rule of 3" length checks meant for emphasis token: state.tokens.length - 1, end: -1, open: scanned.can_open, close: scanned.can_close }); } state.pos += scanned.length; return true; }; function postProcess(state, delimiters) { var i, j, startDelim, endDelim, token, loneMarkers = [], max = delimiters.length; for (i = 0; i < max; i++) { startDelim = delimiters[i]; if (startDelim.marker !== 0x7E/* ~ */) { continue; } if (startDelim.end === -1) { continue; } endDelim = delimiters[startDelim.end]; token = state.tokens[startDelim.token]; token.type = 's_open'; token.tag = 's'; token.nesting = 1; token.markup = '~~'; token.content = ''; token = state.tokens[endDelim.token]; token.type = 's_close'; token.tag = 's'; token.nesting = -1; token.markup = '~~'; token.content = ''; if (state.tokens[endDelim.token - 1].type === 'text' && state.tokens[endDelim.token - 1].content === '~') { loneMarkers.push(endDelim.token - 1); } } // If a marker sequence has an odd number of characters, it's splitted // like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the // start of the sequence. // // So, we have to move all those markers after subsequent s_close tags. // while (loneMarkers.length) { i = loneMarkers.pop(); j = i + 1; while (j < state.tokens.length && state.tokens[j].type === 's_close') { j++; } j--; if (i !== j) { token = state.tokens[j]; state.tokens[j] = state.tokens[i]; state.tokens[i] = token; } } } // Walk through delimiter list and replace text tokens with tags // module.exports.g = function strikethrough(state) { var curr, tokens_meta = state.tokens_meta, max = state.tokens_meta.length; postProcess(state, state.delimiters); for (curr = 0; curr < max; curr++) { if (tokens_meta[curr] && tokens_meta[curr].delimiters) { postProcess(state, tokens_meta[curr].delimiters); } } }; /***/ }), /***/ 1117: /***/ ((module) => { "use strict"; // Skip text characters for text token, place those to pending buffer // and increment current pos // Rule to skip pure text // '{}$%@~+=:' reserved for extentions // !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, _, `, {, |, }, or ~ // !!!! Don't confuse with "Markdown ASCII Punctuation" chars // http://spec.commonmark.org/0.15/#ascii-punctuation-character function isTerminatorChar(ch) { switch (ch) { case 0x0A/* \n */: case 0x21/* ! */: case 0x23/* # */: case 0x24/* $ */: case 0x25/* % */: case 0x26/* & */: case 0x2A/* * */: case 0x2B/* + */: case 0x2D/* - */: case 0x3A/* : */: case 0x3C/* < */: case 0x3D/* = */: case 0x3E/* > */: case 0x40/* @ */: case 0x5B/* [ */: case 0x5C/* \ */: case 0x5D/* ] */: case 0x5E/* ^ */: case 0x5F/* _ */: case 0x60/* ` */: case 0x7B/* { */: case 0x7D/* } */: case 0x7E/* ~ */: return true; default: return false; } } module.exports = function text(state, silent) { var pos = state.pos; while (pos < state.posMax && !isTerminatorChar(state.src.charCodeAt(pos))) { pos++; } if (pos === state.pos) { return false; } if (!silent) { state.pending += state.src.slice(state.pos, pos); } state.pos = pos; return true; }; // Alternative implementation, for memory. // // It costs 10% of performance, but allows extend terminators list, if place it // to `ParcerInline` property. Probably, will switch to it sometime, such // flexibility required. /* var TERMINATOR_RE = /[\n!#$%&*+\-:<=>@[\\\]^_`{}~]/; module.exports = function text(state, silent) { var pos = state.pos, idx = state.src.slice(pos).search(TERMINATOR_RE); // first char is terminator -> empty text if (idx === 0) { return false; } // no terminator -> text till end of string if (idx < 0) { if (!silent) { state.pending += state.src.slice(pos); } state.pos = state.src.length; return true; } if (!silent) { state.pending += state.src.slice(pos, pos + idx); } state.pos += idx; return true; };*/ /***/ }), /***/ 8622: /***/ ((module) => { "use strict"; // Token class /** * class Token **/ /** * new Token(type, tag, nesting) * * Create new token and fill passed properties. **/ function Token(type, tag, nesting) { /** * Token#type -> String * * Type of the token (string, e.g. "paragraph_open") **/ this.type = type; /** * Token#tag -> String * * html tag name, e.g. "p" **/ this.tag = tag; /** * Token#attrs -> Array * * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` **/ this.attrs = null; /** * Token#map -> Array * * Source map info. Format: `[ line_begin, line_end ]` **/ this.map = null; /** * Token#nesting -> Number * * Level change (number in {-1, 0, 1} set), where: * * - `1` means the tag is opening * - `0` means the tag is self-closing * - `-1` means the tag is closing **/ this.nesting = nesting; /** * Token#level -> Number * * nesting level, the same as `state.level` **/ this.level = 0; /** * Token#children -> Array * * An array of child nodes (inline and img tokens) **/ this.children = null; /** * Token#content -> String * * In a case of self-closing tag (code, html, fence, etc.), * it has contents of this tag. **/ this.content = ''; /** * Token#markup -> String * * '*' or '_' for emphasis, fence string for fence, etc. **/ this.markup = ''; /** * Token#info -> String * * Additional information: * * - Info string for "fence" tokens * - The value "auto" for autolink "link_open" and "link_close" tokens * - The string value of the item marker for ordered-list "list_item_open" tokens **/ this.info = ''; /** * Token#meta -> Object * * A place for plugins to store an arbitrary data **/ this.meta = null; /** * Token#block -> Boolean * * True for block-level tokens, false for inline tokens. * Used in renderer to calculate line breaks **/ this.block = false; /** * Token#hidden -> Boolean * * If it's true, ignore this element when rendering. Used for tight lists * to hide paragraphs. **/ this.hidden = false; } /** * Token.attrIndex(name) -> Number * * Search attribute index by name. **/ Token.prototype.attrIndex = function attrIndex(name) { var attrs, i, len; if (!this.attrs) { return -1; } attrs = this.attrs; for (i = 0, len = attrs.length; i < len; i++) { if (attrs[i][0] === name) { return i; } } return -1; }; /** * Token.attrPush(attrData) * * Add `[ name, value ]` attribute to list. Init attrs if necessary **/ Token.prototype.attrPush = function attrPush(attrData) { if (this.attrs) { this.attrs.push(attrData); } else { this.attrs = [ attrData ]; } }; /** * Token.attrSet(name, value) * * Set `name` attribute to `value`. Override old value if exists. **/ Token.prototype.attrSet = function attrSet(name, value) { var idx = this.attrIndex(name), attrData = [ name, value ]; if (idx < 0) { this.attrPush(attrData); } else { this.attrs[idx] = attrData; } }; /** * Token.attrGet(name) * * Get the value of attribute `name`, or null if it does not exist. **/ Token.prototype.attrGet = function attrGet(name) { var idx = this.attrIndex(name), value = null; if (idx >= 0) { value = this.attrs[idx][1]; } return value; }; /** * Token.attrJoin(name, value) * * Join value to existing attribute via space. Or create new attribute if not * exists. Useful to operate with token classes. **/ Token.prototype.attrJoin = function attrJoin(name, value) { var idx = this.attrIndex(name); if (idx < 0) { this.attrPush([ name, value ]); } else { this.attrs[idx][1] = this.attrs[idx][1] + ' ' + value; } }; module.exports = Token; /***/ }), /***/ 8552: /***/ ((module) => { "use strict"; // @ts-check // Formats markdownlint-cli2 results in the style of `markdownlint-cli` const outputFormatter = (options) => { const { results, logError } = options; for (const errorInfo of results) { const { fileName, lineNumber, ruleNames, ruleDescription, errorDetail, errorContext, errorRange } = errorInfo; const ruleName = ruleNames.join("/"); const description = ruleDescription + (errorDetail ? ` [${errorDetail}]` : "") + (errorContext ? ` [Context: "${errorContext}"]` : ""); const column = (errorRange && errorRange[0]) || 0; const columnText = column ? `:${column}` : ""; logError( `${fileName}:${lineNumber}${columnText} ${ruleName} ${description}` ); } return Promise.resolve(); }; module.exports = outputFormatter; /***/ }), /***/ 2935: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check // Regular expression for matching common newline characters // See NEWLINES_RE in markdown-it/lib/rules_core/normalize.js const newLineRe = /\r\n?|\n/g; module.exports.newLineRe = newLineRe; // Regular expression for matching common front matter (YAML and TOML) module.exports.frontMatterRe = // eslint-disable-next-line max-len /((^---\s*$[^]*?^---\s*$)|(^\+\+\+\s*$[^]*?^(\+\+\+|\.\.\.)\s*$)|(^\{\s*$[^]*?^\}\s*$))(\r\n|\r|\n|$)/m; // Regular expression for matching the start of inline disable/enable comments const inlineCommentStartRe = // eslint-disable-next-line max-len /()/ig; module.exports.inlineCommentStartRe = inlineCommentStartRe; // Regular expression for matching HTML elements const htmlElementRe = /<(([A-Za-z][A-Za-z0-9-]*)(?:\s[^`>]*)?)\/?>/g; module.exports.htmlElementRe = htmlElementRe; // Regular expressions for range matching module.exports.bareUrlRe = /(?:http|ftp)s?:\/\/[^\s\]"']*(?:\/|[^\s\]"'\W])/ig; module.exports.listItemMarkerRe = /^([\s>]*)(?:[*+-]|\d+[.)])\s+/; module.exports.orderedListItemMarkerRe = /^[\s>]*0*(\d+)[.)]/; // Regular expression for all instances of emphasis markers const emphasisMarkersRe = /[_*]/g; // Regular expression for blockquote prefixes const blockquotePrefixRe = /^[>\s]*/; module.exports.blockquotePrefixRe = blockquotePrefixRe; // Regular expression for reference links (full, collapsed, and shortcut) const referenceLinkRe = /!?\\?\[((?:\[[^\]\0]*]|[^\]\0])*)](?:(?:\[([^\]\0]*)\])|([^(])|$)/g; // Regular expression for link reference definitions const linkReferenceDefinitionRe = /^ {0,3}\[([^\]]*[^\\])]:/; module.exports.linkReferenceDefinitionRe = linkReferenceDefinitionRe; // All punctuation characters (normal and full-width) const allPunctuation = ".,;:!?。,;:!?"; module.exports.allPunctuation = allPunctuation; // All punctuation characters without question mark (normal and full-width) module.exports.allPunctuationNoQuestion = allPunctuation.replace(/[??]/gu, ""); // Returns true iff the input is a number module.exports.isNumber = function isNumber(obj) { return typeof obj === "number"; }; // Returns true iff the input is a string module.exports.isString = function isString(obj) { return typeof obj === "string"; }; // Returns true iff the input string is empty module.exports.isEmptyString = function isEmptyString(str) { return str.length === 0; }; // Returns true iff the input is an object module.exports.isObject = function isObject(obj) { return (obj !== null) && (typeof obj === "object") && !Array.isArray(obj); }; /** * Returns true iff the input line is blank (contains nothing, whitespace, or * comments (unclosed start/end comments allowed)). * * @param {string} line Input line. * @returns {boolean} True iff line is blank. */ function isBlankLine(line) { const startComment = ""; const removeComments = (s) => { // eslint-disable-next-line no-constant-condition while (true) { const start = s.indexOf(startComment); const end = s.indexOf(endComment); if ((end !== -1) && ((start === -1) || (end < start))) { // Unmatched end comment is first s = s.slice(end + endComment.length); } else if ((start !== -1) && (end !== -1)) { // Start comment is before end comment s = s.slice(0, start) + s.slice(end + endComment.length); } else if ((start !== -1) && (end === -1)) { // Unmatched start comment is last s = s.slice(0, start); } else { // No more comments to remove return s; } } }; return ( !line || !line.trim() || !removeComments(line).replace(/>/g, "").trim() ); } module.exports.isBlankLine = isBlankLine; /** * Compare function for Array.prototype.sort for ascending order of numbers. * * @param {number} a First number. * @param {number} b Second number. * @returns {number} Positive value if a>b, negative value if b> 1; if (array[mid] < element) { left = mid + 1; } else if (array[mid] > element) { right = mid - 1; } else { return true; } } return false; }; // Replaces the content of properly-formatted CommonMark comments with "." // This preserves the line/column information for the rest of the document // https://spec.commonmark.org/0.29/#html-blocks // https://spec.commonmark.org/0.29/#html-comment const htmlCommentBegin = ""; module.exports.clearHtmlCommentText = function clearHtmlCommentText(text) { let i = 0; while ((i = text.indexOf(htmlCommentBegin, i)) !== -1) { const j = text.indexOf(htmlCommentEnd, i + 2); if (j === -1) { // Un-terminated comments are treated as text break; } // If the comment has content... if (j > i + htmlCommentBegin.length) { let k = i - 1; while (text[k] === " ") { k--; } // If comment is not within an indented code block... if (k >= i - 4) { const content = text.slice(i + htmlCommentBegin.length, j); const isBlock = (k < 0) || (text[k] === "\n"); const isValid = isBlock || (!content.startsWith(">") && !content.startsWith("->") && !content.endsWith("-") && !content.includes("--")); // If a valid block/inline comment... if (isValid) { text = text.slice(0, i + htmlCommentBegin.length) + content.replace(/[^\r\n]/g, ".") + text.slice(j); } } } i = j + htmlCommentEnd.length; } return text; }; // Escapes a string for use in a RegExp module.exports.escapeForRegExp = function escapeForRegExp(str) { return str.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"); }; // Un-escapes Markdown content (simple algorithm; not a parser) const escapedMarkdownRe = /\\./g; module.exports.unescapeMarkdown = function unescapeMarkdown(markdown, replacement) { return markdown.replace(escapedMarkdownRe, (match) => { const char = match[1]; if ("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".includes(char)) { return replacement || char; } return match; }); }; /** * Return the string representation of a fence markup character. * * @param {string} markup Fence string. * @returns {string} String representation. */ module.exports.fencedCodeBlockStyleFor = function fencedCodeBlockStyleFor(markup) { switch (markup[0]) { case "~": return "tilde"; default: return "backtick"; } }; /** * Return the string representation of a emphasis or strong markup character. * * @param {string} markup Emphasis or strong string. * @returns {string} String representation. */ module.exports.emphasisOrStrongStyleFor = function emphasisOrStrongStyleFor(markup) { switch (markup[0]) { case "*": return "asterisk"; default: return "underscore"; } }; /** * Return the number of characters of indent for a token. * * @param {Object} token MarkdownItToken instance. * @returns {number} Characters of indent. */ function indentFor(token) { const line = token.line.replace(/^[\s>]*(> |>)/, ""); return line.length - line.trimStart().length; } module.exports.indentFor = indentFor; // Returns the heading style for a heading token module.exports.headingStyleFor = function headingStyleFor(token) { if ((token.map[1] - token.map[0]) === 1) { if (/[^\\]#\s*$/.test(token.line)) { return "atx_closed"; } return "atx"; } return "setext"; }; /** * Return the string representation of an unordered list marker. * * @param {Object} token MarkdownItToken instance. * @returns {string} String representation. */ module.exports.unorderedListStyleFor = function unorderedListStyleFor(token) { switch (token.markup) { case "-": return "dash"; case "+": return "plus"; // case "*": default: return "asterisk"; } }; /** * Calls the provided function for each matching token. * * @param {Object} params RuleParams instance. * @param {string} type Token type identifier. * @param {Function} handler Callback function. * @returns {void} */ function filterTokens(params, type, handler) { for (const token of params.tokens) { if (token.type === type) { handler(token); } } } module.exports.filterTokens = filterTokens; /** * Returns whether a token is a math block (created by markdown-it-texmath). * * @param {Object} token MarkdownItToken instance. * @returns {boolean} True iff token is a math block. */ function isMathBlock(token) { return ( ((token.tag === "$$") || (token.tag === "math")) && token.type.startsWith("math_block") && !token.type.endsWith("_end") ); } module.exports.isMathBlock = isMathBlock; // Get line metadata array module.exports.getLineMetadata = function getLineMetadata(params) { const lineMetadata = params.lines.map( (line, index) => [ line, index, false, 0, false, false, false, false ] ); filterTokens(params, "fence", (token) => { lineMetadata[token.map[0]][3] = 1; lineMetadata[token.map[1] - 1][3] = -1; for (let i = token.map[0] + 1; i < token.map[1] - 1; i++) { lineMetadata[i][2] = true; } }); filterTokens(params, "code_block", (token) => { for (let i = token.map[0]; i < token.map[1]; i++) { lineMetadata[i][2] = true; } }); filterTokens(params, "table_open", (token) => { for (let i = token.map[0]; i < token.map[1]; i++) { lineMetadata[i][4] = true; } }); filterTokens(params, "list_item_open", (token) => { let count = 1; for (let i = token.map[0]; i < token.map[1]; i++) { lineMetadata[i][5] = count; count++; } }); filterTokens(params, "hr", (token) => { lineMetadata[token.map[0]][6] = true; }); for (const token of params.tokens.filter(isMathBlock)) { for (let i = token.map[0]; i < token.map[1]; i++) { lineMetadata[i][7] = true; } } return lineMetadata; }; /** * Calls the provided function for each line. * * @param {Object} lineMetadata Line metadata object. * @param {Function} handler Function taking (line, lineIndex, inCode, onFence, * inTable, inItem, inBreak, inMath). * @returns {void} */ function forEachLine(lineMetadata, handler) { for (const metadata of lineMetadata) { handler(...metadata); } } module.exports.forEachLine = forEachLine; // Returns (nested) lists as a flat array (in order) module.exports.flattenLists = function flattenLists(tokens) { const flattenedLists = []; const stack = []; let current = null; let nesting = 0; const nestingStack = []; let lastWithMap = { "map": [ 0, 1 ] }; for (const token of tokens) { if ((token.type === "bullet_list_open") || (token.type === "ordered_list_open")) { // Save current context and start a new one stack.push(current); current = { "unordered": (token.type === "bullet_list_open"), "parentsUnordered": !current || (current.unordered && current.parentsUnordered), "open": token, "indent": indentFor(token), "parentIndent": (current && current.indent) || 0, "items": [], "nesting": nesting, "lastLineIndex": -1, "insert": flattenedLists.length }; nesting++; } else if ((token.type === "bullet_list_close") || (token.type === "ordered_list_close")) { // Finalize current context and restore previous current.lastLineIndex = lastWithMap.map[1]; flattenedLists.splice(current.insert, 0, current); delete current.insert; current = stack.pop(); nesting--; } else if (token.type === "list_item_open") { // Add list item current.items.push(token); } else if (token.type === "blockquote_open") { nestingStack.push(nesting); nesting = 0; } else if (token.type === "blockquote_close") { nesting = nestingStack.pop() || 0; } if (token.map) { // Track last token with map lastWithMap = token; } } return flattenedLists; }; // Calls the provided function for each specified inline child token module.exports.forEachInlineChild = function forEachInlineChild(params, type, handler) { filterTokens(params, "inline", function forToken(token) { for (const child of token.children) { if (child.type === type) { handler(child, token); } } }); }; // Calls the provided function for each heading's content module.exports.forEachHeading = function forEachHeading(params, handler) { let heading = null; for (const token of params.tokens) { if (token.type === "heading_open") { heading = token; } else if (token.type === "heading_close") { heading = null; } else if ((token.type === "inline") && heading) { handler(heading, token.content, token); } } }; /** * Calls the provided function for each inline code span's content. * * @param {string} input Markdown content. * @param {Function} handler Callback function taking (code, lineIndex, * columnIndex, ticks). * @returns {void} */ function forEachInlineCodeSpan(input, handler) { const backtickRe = /`+/g; let match = null; const backticksLengthAndIndex = []; while ((match = backtickRe.exec(input)) !== null) { backticksLengthAndIndex.push([ match[0].length, match.index ]); } const newLinesIndex = []; while ((match = newLineRe.exec(input)) !== null) { newLinesIndex.push(match.index); } let lineIndex = 0; let lineStartIndex = 0; let k = 0; for (let i = 0; i < backticksLengthAndIndex.length - 1; i++) { const [ startLength, startIndex ] = backticksLengthAndIndex[i]; if ((startIndex === 0) || (input[startIndex - 1] !== "\\")) { for (let j = i + 1; j < backticksLengthAndIndex.length; j++) { const [ endLength, endIndex ] = backticksLengthAndIndex[j]; if (startLength === endLength) { for (; k < newLinesIndex.length; k++) { const newLineIndex = newLinesIndex[k]; if (startIndex < newLineIndex) { break; } lineIndex++; lineStartIndex = newLineIndex + 1; } const columnIndex = startIndex - lineStartIndex + startLength; handler( input.slice(startIndex + startLength, endIndex), lineIndex, columnIndex, startLength ); i = j; break; } } } } } module.exports.forEachInlineCodeSpan = forEachInlineCodeSpan; /** * Adds ellipsis to the left/right/middle of the specified text. * * @param {string} text Text to ellipsify. * @param {boolean} [start] True iff the start of the text is important. * @param {boolean} [end] True iff the end of the text is important. * @returns {string} Ellipsified text. */ function ellipsify(text, start, end) { if (text.length <= 30) { // Nothing to do } else if (start && end) { text = text.slice(0, 15) + "..." + text.slice(-15); } else if (end) { text = "..." + text.slice(-30); } else { text = text.slice(0, 30) + "..."; } return text; } module.exports.ellipsify = ellipsify; /** * Adds a generic error object via the onError callback. * * @param {Object} onError RuleOnError instance. * @param {number} lineNumber Line number. * @param {string} [detail] Error details. * @param {string} [context] Error context. * @param {number[]} [range] Column and length of error. * @param {Object} [fixInfo] RuleOnErrorFixInfo instance. * @returns {void} */ function addError(onError, lineNumber, detail, context, range, fixInfo) { onError({ lineNumber, detail, context, range, fixInfo }); } module.exports.addError = addError; // Adds an error object with details conditionally via the onError callback module.exports.addErrorDetailIf = function addErrorDetailIf( onError, lineNumber, expected, actual, detail, context, range, fixInfo) { if (expected !== actual) { addError( onError, lineNumber, "Expected: " + expected + "; Actual: " + actual + (detail ? "; " + detail : ""), context, range, fixInfo); } }; // Adds an error object with context via the onError callback module.exports.addErrorContext = function addErrorContext( onError, lineNumber, context, left, right, range, fixInfo) { context = ellipsify(context, left, right); addError(onError, lineNumber, undefined, context, range, fixInfo); }; /** * Returns an array of code block and span content ranges. * * @param {Object} params RuleParams instance. * @param {Object} lineMetadata Line metadata object. * @returns {number[][]} Array of ranges (lineIndex, columnIndex, length). */ module.exports.codeBlockAndSpanRanges = (params, lineMetadata) => { const exclusions = []; // Add code block ranges (excludes fences) forEachLine(lineMetadata, (line, lineIndex, inCode, onFence) => { if (inCode && !onFence) { exclusions.push([ lineIndex, 0, line.length ]); } }); // Add code span ranges (excludes ticks) filterTokens(params, "inline", (token) => { if (token.children.some((child) => child.type === "code_inline")) { const tokenLines = params.lines.slice(token.map[0], token.map[1]); forEachInlineCodeSpan( tokenLines.join("\n"), (code, lineIndex, columnIndex) => { const codeLines = code.split(newLineRe); for (const [ i, line ] of codeLines.entries()) { exclusions.push([ token.lineNumber - 1 + lineIndex + i, i ? 0 : columnIndex, line.length ]); } } ); } }); return exclusions; }; /** * Returns an array of HTML element ranges. * * @param {Object} params RuleParams instance. * @param {Object} lineMetadata Line metadata object. * @returns {number[][]} Array of ranges (lineIndex, columnIndex, length). */ module.exports.htmlElementRanges = (params, lineMetadata) => { const exclusions = []; forEachLine(lineMetadata, (line, lineIndex, inCode) => { let match = null; // eslint-disable-next-line no-unmodified-loop-condition while (!inCode && ((match = htmlElementRe.exec(line)) !== null)) { exclusions.push([ lineIndex, match.index, match[0].length ]); } }); return exclusions; }; /** * Determines whether the specified range is within another range. * * @param {number[][]} ranges Array of ranges (line, index, length). * @param {number} lineIndex Line index to check. * @param {number} index Index to check. * @param {number} length Length to check. * @returns {boolean} True iff the specified range is within. */ const withinAnyRange = (ranges, lineIndex, index, length) => ( !ranges.every((span) => ( (lineIndex !== span[0]) || (index < span[1]) || (index + length > span[1] + span[2]) )) ); module.exports.withinAnyRange = withinAnyRange; // Returns a range object for a line by applying a RegExp module.exports.rangeFromRegExp = function rangeFromRegExp(line, regexp) { let range = null; const match = line.match(regexp); if (match) { const column = match.index + 1; const length = match[0].length; range = [ column, length ]; } return range; }; // Determines if the front matter includes a title module.exports.frontMatterHasTitle = function frontMatterHasTitle(frontMatterLines, frontMatterTitlePattern) { const ignoreFrontMatter = (frontMatterTitlePattern !== undefined) && !frontMatterTitlePattern; const frontMatterTitleRe = new RegExp( String(frontMatterTitlePattern || "^\\s*\"?title\"?\\s*[:=]"), "i" ); return !ignoreFrontMatter && frontMatterLines.some((line) => frontMatterTitleRe.test(line)); }; /** * Calls the provided function for each link. * * @param {string} line Line of Markdown input. * @param {Function} handler Function taking (index, link, text, destination). * @returns {void} */ function forEachLink(line, handler) { // Helper to find matching close symbol for link text/destination const findClosingSymbol = (index) => { const begin = line[index]; const end = (begin === "[") ? "]" : ")"; let nesting = 0; let escaping = false; let pointy = false; for (let i = index + 1; i < line.length; i++) { const current = line[i]; if (current === "\\") { escaping = !escaping; } else if (!escaping && (current === begin)) { nesting++; } else if (!escaping && (current === end)) { if (nesting > 0) { nesting--; } else if (!pointy) { // Return index after matching close symbol return i + 1; } } else if ((i === index + 1) && (begin === "(") && (current === "<")) { pointy = true; } else if (!escaping && pointy && current === ">") { pointy = false; nesting = 0; } else { escaping = false; } } // No match found return -1; }; // Scan line for unescaped "[" character let escaping = false; for (let i = 0; i < line.length; i++) { const current = line[i]; if (current === "\\") { escaping = !escaping; } else if (!escaping && (current === "[")) { // Scan for matching close "]" of link text const textEnd = findClosingSymbol(i); if (textEnd !== -1) { if ((line[textEnd] === "(") || (line[textEnd] === "[")) { // Scan for matching close ")" or "]" of link destination const destEnd = findClosingSymbol(textEnd); if (destEnd !== -1) { // Call handler with link text and destination const link = line.slice(i, destEnd); const text = line.slice(i, textEnd); const dest = line.slice(textEnd, destEnd); handler(i, link, text, dest); i = destEnd; } } if (i < textEnd) { // Call handler with link text only const text = line.slice(i, textEnd); handler(i, text, text); i = textEnd; } } } else { escaping = false; } } } module.exports.forEachLink = forEachLink; /** * Returns a list of emphasis markers in code spans and links. * * @param {Object} params RuleParams instance. * @returns {number[][]} List of markers. */ function emphasisMarkersInContent(params) { const { lines } = params; const byLine = new Array(lines.length); // Search links for (const [ tokenLineIndex, tokenLine ] of lines.entries()) { const inLine = []; forEachLink(tokenLine, (index, match) => { let markerMatch = null; while ((markerMatch = emphasisMarkersRe.exec(match))) { inLine.push(index + markerMatch.index); } }); byLine[tokenLineIndex] = inLine; } // Search code spans filterTokens(params, "inline", (token) => { const { children, lineNumber, map } = token; if (children.some((child) => child.type === "code_inline")) { const tokenLines = lines.slice(map[0], map[1]); forEachInlineCodeSpan( tokenLines.join("\n"), (code, lineIndex, column, tickCount) => { const codeLines = code.split(newLineRe); for (const [ codeLineIndex, codeLine ] of codeLines.entries()) { const byLineIndex = lineNumber - 1 + lineIndex + codeLineIndex; const inLine = byLine[byLineIndex]; const codeLineOffset = codeLineIndex ? 0 : column - 1 + tickCount; let match = null; while ((match = emphasisMarkersRe.exec(codeLine))) { inLine.push(codeLineOffset + match.index); } byLine[byLineIndex] = inLine; } } ); } }); return byLine; } module.exports.emphasisMarkersInContent = emphasisMarkersInContent; /** * Returns an object with information about reference links and images. * * @param {Object} lineMetadata Line metadata object. * @returns {Object} Reference link/image data. */ function getReferenceLinkImageData(lineMetadata) { // Initialize return values const references = new Map(); const shortcuts = new Set(); const definitions = new Map(); const duplicateDefinitions = []; // Define helper functions const normalizeLabel = (s) => s.toLowerCase().trim().replace(/\s+/g, " "); const exclusions = []; const excluded = (match) => withinAnyRange( exclusions, 0, match.index, match[0].length - (match[3] || "").length ); // Convert input to single-line so multi-line links/images are easier const lineOffsets = []; let currentOffset = 0; const contentLines = []; forEachLine(lineMetadata, (line, lineIndex, inCode) => { lineOffsets[lineIndex] = currentOffset; if (!inCode) { line = line.replace(blockquotePrefixRe, ""); if (line.trim().length === 0) { // Allow RegExp to detect the end of a block line = "\0"; } contentLines.push(line); currentOffset += line.length + 1; } }); lineOffsets.push(currentOffset); const contentLine = contentLines.join(" "); // Determine single-line exclusions for inline code spans forEachInlineCodeSpan(contentLine, (code, lineIndex, columnIndex) => { exclusions.push([ 0, columnIndex, code.length ]); }); // Identify all link/image reference definitions forEachLine(lineMetadata, (line, lineIndex, inCode) => { if (!inCode) { const linkReferenceDefinitionMatch = linkReferenceDefinitionRe.exec(line); if (linkReferenceDefinitionMatch) { const label = normalizeLabel(linkReferenceDefinitionMatch[1]); if (definitions.has(label)) { duplicateDefinitions.push([ label, lineIndex ]); } else { definitions.set(label, lineIndex); } exclusions.push([ 0, lineOffsets[lineIndex], line.length ]); } } }); // Identify all link and image references let lineIndex = 0; const pendingContents = [ { "content": contentLine, "contentLineIndex": 0, "contentIndex": 0, "topLevel": true } ]; let pendingContent = null; while ((pendingContent = pendingContents.shift())) { const { content, contentLineIndex, contentIndex, topLevel } = pendingContent; let referenceLinkMatch = null; while ((referenceLinkMatch = referenceLinkRe.exec(content)) !== null) { const [ matchString, matchText, matchLabel ] = referenceLinkMatch; if ( !matchString.startsWith("\\") && !matchString.startsWith("!\\") && !matchText.endsWith("\\") && !(matchLabel || "").endsWith("\\") && !(topLevel && excluded(referenceLinkMatch)) ) { const shortcutLink = (matchLabel === undefined); const collapsedLink = (!shortcutLink && (matchLabel.length === 0)); const label = normalizeLabel( (shortcutLink || collapsedLink) ? matchText : matchLabel ); if (label.length > 0) { const referenceindex = referenceLinkMatch.index; if (topLevel) { // Calculate line index while (lineOffsets[lineIndex + 1] <= referenceindex) { lineIndex++; } } else { // Use provided line index lineIndex = contentLineIndex; } const referenceIndex = referenceindex + (topLevel ? -lineOffsets[lineIndex] : contentIndex); if (shortcutLink) { // Track separately due to ambiguity in "text [text] text" shortcuts.add(label); } else { // Track reference and location const referenceData = references.get(label) || []; referenceData.push([ lineIndex, referenceIndex, matchString.length ]); references.set(label, referenceData); } // Check for links embedded in brackets if (!matchString.startsWith("!")) { pendingContents.push({ "content": matchText, "contentLineIndex": lineIndex, "contentIndex": referenceIndex + 1, "topLevel": false }); } } } } } return { references, shortcuts, definitions, duplicateDefinitions }; } module.exports.getReferenceLinkImageData = getReferenceLinkImageData; /** * Gets the most common line ending, falling back to the platform default. * * @param {string} input Markdown content to analyze. * @param {Object} [os] Node.js "os" module. * @returns {string} Preferred line ending. */ function getPreferredLineEnding(input, os) { let cr = 0; let lf = 0; let crlf = 0; const endings = input.match(newLineRe) || []; for (const ending of endings) { // eslint-disable-next-line default-case switch (ending) { case "\r": cr++; break; case "\n": lf++; break; case "\r\n": crlf++; break; } } let preferredLineEnding = null; if (!cr && !lf && !crlf) { preferredLineEnding = (os && os.EOL) || "\n"; } else if ((lf >= crlf) && (lf >= cr)) { preferredLineEnding = "\n"; } else if (crlf >= cr) { preferredLineEnding = "\r\n"; } else { preferredLineEnding = "\r"; } return preferredLineEnding; } module.exports.getPreferredLineEnding = getPreferredLineEnding; /** * Normalizes the fields of a RuleOnErrorFixInfo instance. * * @param {Object} fixInfo RuleOnErrorFixInfo instance. * @param {number} [lineNumber] Line number. * @returns {Object} Normalized RuleOnErrorFixInfo instance. */ function normalizeFixInfo(fixInfo, lineNumber) { return { "lineNumber": fixInfo.lineNumber || lineNumber, "editColumn": fixInfo.editColumn || 1, "deleteCount": fixInfo.deleteCount || 0, "insertText": fixInfo.insertText || "" }; } /** * Fixes the specified error on a line of Markdown content. * * @param {string} line Line of Markdown content. * @param {Object} fixInfo RuleOnErrorFixInfo instance. * @param {string} [lineEnding] Line ending to use. * @returns {string | null} Fixed content. */ function applyFix(line, fixInfo, lineEnding) { const { editColumn, deleteCount, insertText } = normalizeFixInfo(fixInfo); const editIndex = editColumn - 1; return (deleteCount === -1) ? null : line.slice(0, editIndex) + insertText.replace(/\n/g, lineEnding || "\n") + line.slice(editIndex + deleteCount); } module.exports.applyFix = applyFix; /** * Applies as many fixes as possible to Markdown content. * * @param {string} input Lines of Markdown content. * @param {Object[]} errors RuleOnErrorInfo instances. * @returns {string} Corrected content. */ function applyFixes(input, errors) { const lineEnding = getPreferredLineEnding(input, __nccwpck_require__(2037)); const lines = input.split(newLineRe); // Normalize fixInfo objects let fixInfos = errors .filter((error) => error.fixInfo) .map((error) => normalizeFixInfo(error.fixInfo, error.lineNumber)); // Sort bottom-to-top, line-deletes last, right-to-left, long-to-short fixInfos.sort((a, b) => { const aDeletingLine = (a.deleteCount === -1); const bDeletingLine = (b.deleteCount === -1); return ( (b.lineNumber - a.lineNumber) || (aDeletingLine ? 1 : (bDeletingLine ? -1 : 0)) || (b.editColumn - a.editColumn) || (b.insertText.length - a.insertText.length) ); }); // Remove duplicate entries (needed for following collapse step) let lastFixInfo = {}; fixInfos = fixInfos.filter((fixInfo) => { const unique = ( (fixInfo.lineNumber !== lastFixInfo.lineNumber) || (fixInfo.editColumn !== lastFixInfo.editColumn) || (fixInfo.deleteCount !== lastFixInfo.deleteCount) || (fixInfo.insertText !== lastFixInfo.insertText) ); lastFixInfo = fixInfo; return unique; }); // Collapse insert/no-delete and no-insert/delete for same line/column lastFixInfo = { "lineNumber": -1 }; for (const fixInfo of fixInfos) { if ( (fixInfo.lineNumber === lastFixInfo.lineNumber) && (fixInfo.editColumn === lastFixInfo.editColumn) && !fixInfo.insertText && (fixInfo.deleteCount > 0) && lastFixInfo.insertText && !lastFixInfo.deleteCount) { fixInfo.insertText = lastFixInfo.insertText; lastFixInfo.lineNumber = 0; } lastFixInfo = fixInfo; } fixInfos = fixInfos.filter((fixInfo) => fixInfo.lineNumber); // Apply all (remaining/updated) fixes let lastLineIndex = -1; let lastEditIndex = -1; for (const fixInfo of fixInfos) { const { lineNumber, editColumn, deleteCount } = fixInfo; const lineIndex = lineNumber - 1; const editIndex = editColumn - 1; if ( (lineIndex !== lastLineIndex) || (deleteCount === -1) || ((editIndex + deleteCount) <= (lastEditIndex - ((deleteCount > 0) ? 0 : 1))) ) { // @ts-ignore lines[lineIndex] = applyFix(lines[lineIndex], fixInfo, lineEnding); } lastLineIndex = lineIndex; lastEditIndex = editIndex; } // Return corrected input return lines.filter((line) => line !== null).join(lineEnding); } module.exports.applyFixes = applyFixes; /** * Gets the range and fixInfo values for reporting an error if the expected * text is found on the specified line. * * @param {string[]} lines Lines of Markdown content. * @param {number} lineIndex Line index to check. * @param {string} search Text to search for. * @param {string} replace Text to replace with. * @param {number} [instance] Instance on the line (1-based). * @returns {Object} Range and fixInfo wrapper. */ module.exports.getRangeAndFixInfoIfFound = (lines, lineIndex, search, replace, instance = 1) => { let range = null; let fixInfo = null; let searchIndex = -1; while (instance > 0) { searchIndex = lines[lineIndex].indexOf(search, searchIndex + 1); instance--; } if (searchIndex !== -1) { const column = searchIndex + 1; const length = search.length; range = [ column, length ]; fixInfo = { "editColumn": column, "deleteCount": length, "insertText": replace }; } return { range, fixInfo }; }; /** * Gets the next (subsequent) child token if it is of the expected type. * * @param {Object} parentToken Parent token. * @param {Object} childToken Child token basis. * @param {string} nextType Token type of next token. * @param {string} nextNextType Token type of next-next token. * @returns {Object} Next token. */ function getNextChildToken(parentToken, childToken, nextType, nextNextType) { const { children } = parentToken; const index = children.indexOf(childToken); if ( (index !== -1) && (children.length > index + 2) && (children[index + 1].type === nextType) && (children[index + 2].type === nextNextType) ) { return children[index + 1]; } return null; } module.exports.getNextChildToken = getNextChildToken; /** * Expands a path with a tilde to an absolute path. * * @param {string} file Path that may begin with a tilde. * @param {Object} os Node.js "os" module. * @returns {string} Absolute path (or original path). */ function expandTildePath(file, os) { const homedir = os && os.homedir && os.homedir(); return homedir ? file.replace(/^~($|\/|\\)/, `${homedir}$1`) : file; } module.exports.expandTildePath = expandTildePath; /***/ }), /***/ 6023: /***/ ((module) => { "use strict"; /* eslint-disable no-bitwise */ var decodeCache = {}; function getDecodeCache(exclude) { var i, ch, cache = decodeCache[exclude]; if (cache) { return cache; } cache = decodeCache[exclude] = []; for (i = 0; i < 128; i++) { ch = String.fromCharCode(i); cache.push(ch); } for (i = 0; i < exclude.length; i++) { ch = exclude.charCodeAt(i); cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2); } return cache; } // Decode percent-encoded string. // function decode(string, exclude) { var cache; if (typeof exclude !== 'string') { exclude = decode.defaultChars; } cache = getDecodeCache(exclude); return string.replace(/(%[a-f0-9]{2})+/gi, function(seq) { var i, l, b1, b2, b3, b4, chr, result = ''; for (i = 0, l = seq.length; i < l; i += 3) { b1 = parseInt(seq.slice(i + 1, i + 3), 16); if (b1 < 0x80) { result += cache[b1]; continue; } if ((b1 & 0xE0) === 0xC0 && (i + 3 < l)) { // 110xxxxx 10xxxxxx b2 = parseInt(seq.slice(i + 4, i + 6), 16); if ((b2 & 0xC0) === 0x80) { chr = ((b1 << 6) & 0x7C0) | (b2 & 0x3F); if (chr < 0x80) { result += '\ufffd\ufffd'; } else { result += String.fromCharCode(chr); } i += 3; continue; } } if ((b1 & 0xF0) === 0xE0 && (i + 6 < l)) { // 1110xxxx 10xxxxxx 10xxxxxx b2 = parseInt(seq.slice(i + 4, i + 6), 16); b3 = parseInt(seq.slice(i + 7, i + 9), 16); if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) { chr = ((b1 << 12) & 0xF000) | ((b2 << 6) & 0xFC0) | (b3 & 0x3F); if (chr < 0x800 || (chr >= 0xD800 && chr <= 0xDFFF)) { result += '\ufffd\ufffd\ufffd'; } else { result += String.fromCharCode(chr); } i += 6; continue; } } if ((b1 & 0xF8) === 0xF0 && (i + 9 < l)) { // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx b2 = parseInt(seq.slice(i + 4, i + 6), 16); b3 = parseInt(seq.slice(i + 7, i + 9), 16); b4 = parseInt(seq.slice(i + 10, i + 12), 16); if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) { chr = ((b1 << 18) & 0x1C0000) | ((b2 << 12) & 0x3F000) | ((b3 << 6) & 0xFC0) | (b4 & 0x3F); if (chr < 0x10000 || chr > 0x10FFFF) { result += '\ufffd\ufffd\ufffd\ufffd'; } else { chr -= 0x10000; result += String.fromCharCode(0xD800 + (chr >> 10), 0xDC00 + (chr & 0x3FF)); } i += 9; continue; } } result += '\ufffd'; } return result; }); } decode.defaultChars = ';/?:@&=+$,#'; decode.componentChars = ''; module.exports = decode; /***/ }), /***/ 6756: /***/ ((module) => { "use strict"; var encodeCache = {}; // Create a lookup array where anything but characters in `chars` string // and alphanumeric chars is percent-encoded. // function getEncodeCache(exclude) { var i, ch, cache = encodeCache[exclude]; if (cache) { return cache; } cache = encodeCache[exclude] = []; for (i = 0; i < 128; i++) { ch = String.fromCharCode(i); if (/^[0-9a-z]$/i.test(ch)) { // always allow unencoded alphanumeric characters cache.push(ch); } else { cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2)); } } for (i = 0; i < exclude.length; i++) { cache[exclude.charCodeAt(i)] = exclude[i]; } return cache; } // Encode unsafe characters with percent-encoding, skipping already // encoded sequences. // // - string - string to encode // - exclude - list of characters to ignore (in addition to a-zA-Z0-9) // - keepEscaped - don't encode '%' in a correct escape sequence (default: true) // function encode(string, exclude, keepEscaped) { var i, l, code, nextCode, cache, result = ''; if (typeof exclude !== 'string') { // encode(string, keepEscaped) keepEscaped = exclude; exclude = encode.defaultChars; } if (typeof keepEscaped === 'undefined') { keepEscaped = true; } cache = getEncodeCache(exclude); for (i = 0, l = string.length; i < l; i++) { code = string.charCodeAt(i); if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) { if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) { result += string.slice(i, i + 3); i += 2; continue; } } if (code < 128) { result += cache[code]; continue; } if (code >= 0xD800 && code <= 0xDFFF) { if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) { nextCode = string.charCodeAt(i + 1); if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) { result += encodeURIComponent(string[i] + string[i + 1]); i++; continue; } } result += '%EF%BF%BD'; continue; } result += encodeURIComponent(string[i]); } return result; } encode.defaultChars = ";/?:@&=+$,-_.!~*'()#"; encode.componentChars = "-_.!~*'()"; module.exports = encode; /***/ }), /***/ 8612: /***/ ((module) => { "use strict"; module.exports = function format(url) { var result = ''; result += url.protocol || ''; result += url.slashes ? '//' : ''; result += url.auth ? url.auth + '@' : ''; if (url.hostname && url.hostname.indexOf(':') !== -1) { // ipv6 address result += '[' + url.hostname + ']'; } else { result += url.hostname || ''; } result += url.port ? ':' + url.port : ''; result += url.pathname || ''; result += url.search || ''; result += url.hash || ''; return result; }; /***/ }), /***/ 114: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports.encode = __nccwpck_require__(6756); module.exports.decode = __nccwpck_require__(6023); module.exports.format = __nccwpck_require__(8612); module.exports.parse = __nccwpck_require__(8062); /***/ }), /***/ 8062: /***/ ((module) => { "use strict"; // 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. // // Changes from joyent/node: // // 1. No leading slash in paths, // e.g. in `url.parse('http://foo?bar')` pathname is ``, not `/` // // 2. Backslashes are not replaced with slashes, // so `http:\\example.org\` is treated like a relative path // // 3. Trailing colon is treated like a part of the path, // i.e. in `http://example.org:foo` pathname is `:foo` // // 4. Nothing is URL-encoded in the resulting object, // (in joyent/node some chars in auth and paths are encoded) // // 5. `url.parse()` does not have `parseQueryString` argument // // 6. Removed extraneous result properties: `host`, `path`, `query`, etc., // which can be constructed using other parts of the url. // function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.pathname = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = [ '<', '>', '"', '`', ' ', '\r', '\n', '\t' ], // RFC 2396: characters not allowed for various reasons. unwise = [ '{', '}', '|', '\\', '^', '`' ].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = [ '\'' ].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = [ '%', '/', '?', ';', '#' ].concat(autoEscape), hostEndingChars = [ '/', '?', '#' ], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. /* eslint-disable no-script-url */ // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }; /* eslint-enable no-script-url */ function urlParse(url, slashesDenoteHost) { if (url && url instanceof Url) { return url; } var u = new Url(); u.parse(url, slashesDenoteHost); return u; } Url.prototype.parse = function(url, slashesDenoteHost) { var i, l, lowerProto, hec, slashes, rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; lowerProto = proto.toLowerCase(); this.protocol = proto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (i = 0; i < hostEndingChars.length; i++) { hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = auth; } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (i = 0; i < nonHostChars.length; i++) { hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) { hostEnd = rest.length; } if (rest[hostEnd - 1] === ':') { hostEnd--; } var host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(host); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) { continue; } if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); rest = rest.slice(0, qm); } if (rest) { this.pathname = rest; } if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = ''; } return this; }; Url.prototype.parseHost = function(host) { var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) { this.hostname = host; } }; module.exports = urlParse; /***/ }), /***/ 2578: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* * merge2 * https://github.com/teambition/merge2 * * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ const Stream = __nccwpck_require__(2781) const PassThrough = Stream.PassThrough const slice = Array.prototype.slice module.exports = merge2 function merge2 () { const streamsQueue = [] const args = slice.call(arguments) let merging = false let options = args[args.length - 1] if (options && !Array.isArray(options) && options.pipe == null) { args.pop() } else { options = {} } const doEnd = options.end !== false const doPipeError = options.pipeError === true if (options.objectMode == null) { options.objectMode = true } if (options.highWaterMark == null) { options.highWaterMark = 64 * 1024 } const mergedStream = PassThrough(options) function addStream () { for (let i = 0, len = arguments.length; i < len; i++) { streamsQueue.push(pauseStreams(arguments[i], options)) } mergeStream() return this } function mergeStream () { if (merging) { return } merging = true let streams = streamsQueue.shift() if (!streams) { process.nextTick(endStream) return } if (!Array.isArray(streams)) { streams = [streams] } let pipesCount = streams.length + 1 function next () { if (--pipesCount > 0) { return } merging = false mergeStream() } function pipe (stream) { function onend () { stream.removeListener('merge2UnpipeEnd', onend) stream.removeListener('end', onend) if (doPipeError) { stream.removeListener('error', onerror) } next() } function onerror (err) { mergedStream.emit('error', err) } // skip ended stream if (stream._readableState.endEmitted) { return next() } stream.on('merge2UnpipeEnd', onend) stream.on('end', onend) if (doPipeError) { stream.on('error', onerror) } stream.pipe(mergedStream, { end: false }) // compatible for old stream stream.resume() } for (let i = 0; i < streams.length; i++) { pipe(streams[i]) } next() } function endStream () { merging = false // emit 'queueDrain' when all streams merged. mergedStream.emit('queueDrain') if (doEnd) { mergedStream.end() } } mergedStream.setMaxListeners(0) mergedStream.add = addStream mergedStream.on('unpipe', function (stream) { stream.emit('merge2UnpipeEnd') }) if (args.length) { addStream.apply(null, args) } return mergedStream } // check and pause streams for pipe. function pauseStreams (streams, options) { if (!Array.isArray(streams)) { // Backwards-compat with old-style streams if (!streams._readableState && streams.pipe) { streams = streams.pipe(PassThrough(options)) } if (!streams._readableState || !streams.pause || !streams.pipe) { throw new Error('Only readable stream can be merged.') } streams.pause() } else { for (let i = 0, len = streams.length; i < len; i++) { streams[i] = pauseStreams(streams[i], options) } } return streams } /***/ }), /***/ 6228: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const util = __nccwpck_require__(3837); const braces = __nccwpck_require__(610); const picomatch = __nccwpck_require__(8569); const utils = __nccwpck_require__(479); const isEmptyString = val => val === '' || val === './'; /** * Returns an array of strings that match one or more glob patterns. * * ```js * const mm = require('micromatch'); * // mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {String|Array} `list` List of strings to match. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) * @return {Array} Returns an array of matches * @summary false * @api public */ const micromatch = (list, patterns, options) => { patterns = [].concat(patterns); list = [].concat(list); let omit = new Set(); let keep = new Set(); let items = new Set(); let negatives = 0; let onResult = state => { items.add(state.output); if (options && options.onResult) { options.onResult(state); } }; for (let i = 0; i < patterns.length; i++) { let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); let negated = isMatch.state.negated || isMatch.state.negatedExtglob; if (negated) negatives++; for (let item of list) { let matched = isMatch(item, true); let match = negated ? !matched.isMatch : matched.isMatch; if (!match) continue; if (negated) { omit.add(matched.output); } else { omit.delete(matched.output); keep.add(matched.output); } } } let result = negatives === patterns.length ? [...items] : [...keep]; let matches = result.filter(item => !omit.has(item)); if (options && matches.length === 0) { if (options.failglob === true) { throw new Error(`No matches found for "${patterns.join(', ')}"`); } if (options.nonull === true || options.nullglob === true) { return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; } } return matches; }; /** * Backwards compatibility */ micromatch.match = micromatch; /** * Returns a matcher function from the given glob `pattern` and `options`. * The returned function takes a string to match as its only argument and returns * true if the string is a match. * * ```js * const mm = require('micromatch'); * // mm.matcher(pattern[, options]); * * const isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @param {String} `pattern` Glob pattern * @param {Object} `options` * @return {Function} Returns a matcher function. * @api public */ micromatch.matcher = (pattern, options) => picomatch(pattern, options); /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const mm = require('micromatch'); * // mm.isMatch(string, patterns[, options]); * * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(mm.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `[options]` See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Backwards compatibility */ micromatch.any = micromatch.isMatch; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js * const mm = require('micromatch'); * // mm.not(list, patterns[, options]); * * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. * @param {String|Array} `patterns` One or more glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array} Returns an array of strings that **do not match** the given patterns. * @api public */ micromatch.not = (list, patterns, options = {}) => { patterns = [].concat(patterns).map(String); let result = new Set(); let items = []; let onResult = state => { if (options.onResult) options.onResult(state); items.push(state.output); }; let matches = new Set(micromatch(list, patterns, { ...options, onResult })); for (let item of items) { if (!matches.has(item)) { result.add(item); } } return [...result]; }; /** * Returns true if the given `string` contains the given pattern. Similar * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js * var mm = require('micromatch'); * // mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. * @param {String|Array} `patterns` Glob pattern to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any of the patterns matches any part of `str`. * @api public */ micromatch.contains = (str, pattern, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util.inspect(str)}"`); } if (Array.isArray(pattern)) { return pattern.some(p => micromatch.contains(str, p, options)); } if (typeof pattern === 'string') { if (isEmptyString(str) || isEmptyString(pattern)) { return false; } if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { return true; } } return micromatch.isMatch(str, pattern, { ...options, contains: true }); }; /** * Filter the keys of the given object with the given `glob` pattern * and `options`. Does not attempt to match nested keys. If you need this feature, * use [glob-object][] instead. * * ```js * const mm = require('micromatch'); * // mm.matchKeys(object, patterns[, options]); * * const obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Object} Returns an object with only keys that match the given patterns. * @api public */ micromatch.matchKeys = (obj, patterns, options) => { if (!utils.isObject(obj)) { throw new TypeError('Expected the first argument to be an object'); } let keys = micromatch(Object.keys(obj), patterns, options); let res = {}; for (let key of keys) res[key] = obj[key]; return res; }; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` * @api public */ micromatch.some = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (items.some(item => isMatch(item))) { return true; } } return false; }; /** * Returns true if every string in the given `list` matches * any of the given glob `patterns`. * * ```js * const mm = require('micromatch'); * // mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` * @api public */ micromatch.every = (list, patterns, options) => { let items = [].concat(list); for (let pattern of [].concat(patterns)) { let isMatch = picomatch(String(pattern), options); if (!items.every(item => isMatch(item))) { return false; } } return true; }; /** * Returns true if **all** of the given `patterns` match * the specified string. * * ```js * const mm = require('micromatch'); * // mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @param {String|Array} `str` The string to test. * @param {String|Array} `patterns` One or more glob patterns to use for matching. * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Boolean} Returns true if any patterns match `str` * @api public */ micromatch.all = (str, patterns, options) => { if (typeof str !== 'string') { throw new TypeError(`Expected a string: "${util.inspect(str)}"`); } return [].concat(patterns).every(p => picomatch(p, options)(str)); }; /** * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. * * ```js * const mm = require('micromatch'); * // mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `glob` Glob pattern to use for matching. * @param {String} `input` String to match * @param {Object} `options` See available [options](#options) for changing how matches are performed * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. * @api public */ micromatch.capture = (glob, input, options) => { let posix = utils.isWindows(options); let regex = picomatch.makeRe(String(glob), { ...options, capture: true }); let match = regex.exec(posix ? utils.toPosixSlashes(input) : input); if (match) { return match.slice(1).map(v => v === void 0 ? '' : v); } }; /** * Create a regular expression from the given glob `pattern`. * * ```js * const mm = require('micromatch'); * // mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. * @param {Object} `options` * @return {RegExp} Returns a regex created from the given pattern. * @api public */ micromatch.makeRe = (...args) => picomatch.makeRe(...args); /** * Scan a glob pattern to separate the pattern into segments. Used * by the [split](#split) method. * * ```js * const mm = require('micromatch'); * const state = mm.scan(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with * @api public */ micromatch.scan = (...args) => picomatch.scan(...args); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const mm = require('micromatch'); * const state = mm.parse(pattern[, options]); * ``` * @param {String} `glob` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as regex source string. * @api public */ micromatch.parse = (patterns, options) => { let res = []; for (let pattern of [].concat(patterns || [])) { for (let str of braces(String(pattern), options)) { res.push(picomatch.parse(str, options)); } } return res; }; /** * Process the given brace `pattern`. * * ```js * const { braces } = require('micromatch'); * console.log(braces('foo/{a,b,c}/bar')); * //=> [ 'foo/(a|b|c)/bar' ] * * console.log(braces('foo/{a,b,c}/bar', { expand: true })); * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] * ``` * @param {String} `pattern` String with brace pattern to process. * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. * @return {Array} * @api public */ micromatch.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { return [pattern]; } return braces(pattern, options); }; /** * Expand braces */ micromatch.braceExpand = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); return micromatch.braces(pattern, { ...options, expand: true }); }; /** * Expose micromatch */ module.exports = micromatch; /***/ }), /***/ 3433: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const {promisify} = __nccwpck_require__(3837); const fs = __nccwpck_require__(7147); async function isType(fsStatType, statsMethodName, filePath) { if (typeof filePath !== 'string') { throw new TypeError(`Expected a string, got ${typeof filePath}`); } try { const stats = await promisify(fs[fsStatType])(filePath); return stats[statsMethodName](); } catch (error) { if (error.code === 'ENOENT') { return false; } throw error; } } function isTypeSync(fsStatType, statsMethodName, filePath) { if (typeof filePath !== 'string') { throw new TypeError(`Expected a string, got ${typeof filePath}`); } try { return fs[fsStatType](filePath)[statsMethodName](); } catch (error) { if (error.code === 'ENOENT') { return false; } throw error; } } exports.isFile = isType.bind(null, 'stat', 'isFile'); exports.isDirectory = isType.bind(null, 'stat', 'isDirectory'); exports.isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink'); exports.isFileSync = isTypeSync.bind(null, 'statSync', 'isFile'); exports.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory'); exports.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); /***/ }), /***/ 8569: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; module.exports = __nccwpck_require__(3322); /***/ }), /***/ 6099: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(1017); const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; /** * Posix glob regex */ const DOT_LITERAL = '\\.'; const PLUS_LITERAL = '\\+'; const QMARK_LITERAL = '\\?'; const SLASH_LITERAL = '\\/'; const ONE_CHAR = '(?=.)'; const QMARK = '[^/]'; const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; const NO_DOT = `(?!${DOT_LITERAL})`; const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; const STAR = `${QMARK}*?`; const POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR, START_ANCHOR }; /** * Windows glob regex */ const WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; /** * POSIX Bracket Regex */ const POSIX_REGEX_SOURCE = { alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', blank: ' \\t', cntrl: '\\x00-\\x1F\\x7F', digit: '0-9', graph: '\\x21-\\x7E', lower: 'a-z', print: '\\x20-\\x7E ', punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', space: ' \\t\\r\\n\\v\\f', upper: 'A-Z', word: 'A-Za-z0-9_', xdigit: 'A-Fa-f0-9' }; module.exports = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { '***': '*', '**/**': '**', '**/**/**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; }, /** * Create GLOB_CHARS */ globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; /***/ }), /***/ 2139: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const constants = __nccwpck_require__(6099); const utils = __nccwpck_require__(479); /** * Constants */ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants; /** * Helpers */ const expandRange = (args, options) => { if (typeof options.expandRange === 'function') { return options.expandRange(...args, options); } args.sort(); const value = `[${args.join('-')}]`; try { /* eslint-disable-next-line no-new */ new RegExp(value); } catch (ex) { return args.map(v => utils.escapeRegex(v)).join('..'); } return value; }; /** * Create the message for a syntax error */ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; /** * Parse the given input string. * @param {String} input * @param {Object} options * @return {Object} */ const parse = (input, options) => { if (typeof input !== 'string') { throw new TypeError('Expected a string'); } input = REPLACEMENTS[input] || input; const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: 'bos', value: '', output: opts.prepend || '' }; const tokens = [bos]; const capture = opts.capture ? '' : '?:'; const win32 = utils.isWindows(options); // create constants based on platform, for windows or posix const PLATFORM_CHARS = constants.globChars(win32); const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS; const globstar = opts => { return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const nodot = opts.dot ? '' : NO_DOT; const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; let star = opts.bash === true ? globstar(opts) : STAR; if (opts.capture) { star = `(${star})`; } // minimatch options support if (typeof opts.noext === 'boolean') { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: '', output: '', prefix: '', backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils.removePrefix(input, state); len = input.length; const extglobs = []; const braces = []; const stack = []; let prev = bos; let value; /** * Tokenizing helpers */ const eos = () => state.index === len - 1; const peek = state.peek = (n = 1) => input[state.index + n]; const advance = state.advance = () => input[++state.index] || ''; const remaining = () => input.slice(state.index + 1); const consume = (value = '', num = 0) => { state.consumed += value; state.index += num; }; const append = token => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = type => { state[type]++; stack.push(type); }; const decrement = type => { state[type]--; stack.pop(); }; /** * Push tokens onto the tokens array. This helper speeds up * tokenizing by 1) helping us avoid backtracking as much as possible, * and 2) helping us avoid creating extra tokens when consecutive * characters are plain text. This improves performance and simplifies * lookbehinds. */ const push = tok => { if (prev.type === 'globstar') { const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { state.output = state.output.slice(0, -prev.output.length); prev.type = 'star'; prev.value = '*'; prev.output = star; state.output += prev.output; } } if (extglobs.length && tok.type !== 'paren') { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append(tok); if (prev && prev.type === 'text' && tok.type === 'text') { prev.value += tok.value; prev.output = (prev.output || '') + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = token => { let output = token.close + (opts.capture ? ')' : ''); let rest; if (token.type === 'negate') { let extglobStar = star; if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { extglobStar = globstar(opts); } if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. // In this case, we need to parse the string and use it in the output of the original pattern. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. // // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. const expression = parse(rest, { ...options, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === 'bos') { state.negatedExtglob = true; } } push({ type: 'paren', extglob: true, value, output }); decrement('parens'); }; /** * Fast paths */ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { if (first === '\\') { backslashes = true; return m; } if (first === '?') { if (esc) { return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } if (index === 0) { return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } return QMARK.repeat(chars.length); } if (first === '.') { return DOT_LITERAL.repeat(chars.length); } if (first === '*') { if (esc) { return esc + first + (rest ? star : ''); } return star; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ''); } else { output = output.replace(/\\+/g, m => { return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils.wrapOutput(output, state, options); return state; } /** * Tokenize input until we reach end-of-string */ while (!eos()) { value = advance(); if (value === '\u0000') { continue; } /** * Escaped characters */ if (value === '\\') { const next = peek(); if (next === '/' && opts.bash !== true) { continue; } if (next === '.' || next === ';') { continue; } if (!next) { value += '\\'; push({ type: 'text', value }); continue; } // collapse slashes to reduce potential for exploits const match = /^\\+/.exec(remaining()); let slashes = 0; if (match && match[0].length > 2) { slashes = match[0].length; state.index += slashes; if (slashes % 2 !== 0) { value += '\\'; } } if (opts.unescape === true) { value = advance(); } else { value += advance(); } if (state.brackets === 0) { push({ type: 'text', value }); continue; } } /** * If we're inside a regex character class, continue * until we reach the closing bracket. */ if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { if (opts.posix !== false && value === ':') { const inner = prev.value.slice(1); if (inner.includes('[')) { prev.posix = true; if (inner.includes(':')) { const idx = prev.value.lastIndexOf('['); const pre = prev.value.slice(0, idx); const rest = prev.value.slice(idx + 2); const posix = POSIX_REGEX_SOURCE[rest]; if (posix) { prev.value = pre + posix; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR; } continue; } } } } if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { value = `\\${value}`; } if (value === ']' && (prev.value === '[' || prev.value === '[^')) { value = `\\${value}`; } if (opts.posix === true && value === '!' && prev.value === '[') { value = '^'; } prev.value += value; append({ value }); continue; } /** * If we're inside a quoted string, continue * until we reach the closing double quote. */ if (state.quotes === 1 && value !== '"') { value = utils.escapeRegex(value); prev.value += value; append({ value }); continue; } /** * Double quotes */ if (value === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push({ type: 'text', value }); } continue; } /** * Parentheses */ if (value === '(') { increment('parens'); push({ type: 'paren', value }); continue; } if (value === ')') { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '(')); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); decrement('parens'); continue; } /** * Square brackets */ if (value === '[') { if (opts.nobracket === true || !remaining().includes(']')) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError('closing', ']')); } value = `\\${value}`; } else { increment('brackets'); } push({ type: 'bracket', value }); continue; } if (value === ']') { if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { push({ type: 'text', value, output: `\\${value}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError('opening', '[')); } push({ type: 'text', value, output: `\\${value}` }); continue; } decrement('brackets'); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { value = `/${value}`; } prev.value += value; append({ value }); // when literal brackets are explicitly disabled // assume we should match with a regex character class if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { continue; } const escaped = utils.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled // assume we should escape the brackets to match literal characters if (opts.literalBrackets === true) { state.output += escaped; prev.value = escaped; continue; } // when the user specifies nothing, try to match both prev.value = `(${capture}${escaped}|${prev.value})`; state.output += prev.value; continue; } /** * Braces */ if (value === '{' && opts.nobrace !== true) { increment('braces'); const open = { type: 'brace', value, output: '(', outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces.push(open); push(open); continue; } if (value === '}') { const brace = braces[braces.length - 1]; if (opts.nobrace === true || !brace) { push({ type: 'text', value, output: value }); continue; } let output = ')'; if (brace.dots === true) { const arr = tokens.slice(); const range = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === 'brace') { break; } if (arr[i].type !== 'dots') { range.unshift(arr[i].value); } } output = expandRange(range, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = '\\{'; value = output = '\\}'; state.output = out; for (const t of toks) { state.output += (t.output || t.value); } } push({ type: 'brace', value, output }); decrement('braces'); braces.pop(); continue; } /** * Pipes */ if (value === '|') { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push({ type: 'text', value }); continue; } /** * Commas */ if (value === ',') { let output = value; const brace = braces[braces.length - 1]; if (brace && stack[stack.length - 1] === 'braces') { brace.comma = true; output = '|'; } push({ type: 'comma', value, output }); continue; } /** * Slashes */ if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } /** * Dots */ if (value === '.') { if (state.braces > 0 && prev.type === 'dot') { if (prev.value === '.') prev.output = DOT_LITERAL; const brace = braces[braces.length - 1]; prev.type = 'dots'; prev.output += value; prev.value += value; brace.dots = true; continue; } if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { push({ type: 'text', value, output: DOT_LITERAL }); continue; } push({ type: 'dot', value, output: DOT_LITERAL }); continue; } /** * Question marks */ if (value === '?') { const isGroup = prev && prev.value === '('; if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('qmark', value); continue; } if (prev && prev.type === 'paren') { const next = peek(); let output = value; if (next === '<' && !utils.supportsLookbehinds()) { throw new Error('Node.js v10 or higher is required for regex lookbehinds'); } if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { output = `\\${value}`; } push({ type: 'text', value, output }); continue; } if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { push({ type: 'qmark', value, output: QMARK_NO_DOT }); continue; } push({ type: 'qmark', value, output: QMARK }); continue; } /** * Exclamation */ if (value === '!') { if (opts.noextglob !== true && peek() === '(') { if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { extglobOpen('negate', value); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } /** * Plus */ if (value === '+') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { extglobOpen('plus', value); continue; } if ((prev && prev.value === '(') || opts.regex === false) { push({ type: 'plus', value, output: PLUS_LITERAL }); continue; } if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { push({ type: 'plus', value }); continue; } push({ type: 'plus', value: PLUS_LITERAL }); continue; } /** * Plain text */ if (value === '@') { if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { push({ type: 'at', extglob: true, value, output: '' }); continue; } push({ type: 'text', value }); continue; } /** * Plain text */ if (value !== '*') { if (value === '$' || value === '^') { value = `\\${value}`; } const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match) { value += match[0]; state.index += match[0].length; } push({ type: 'text', value }); continue; } /** * Stars */ if (prev && (prev.type === 'globstar' || prev.star === true)) { prev.type = 'star'; prev.star = true; prev.value += value; prev.output = star; state.backtrack = true; state.globstar = true; consume(value); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen('star', value); continue; } if (prev.type === 'star') { if (opts.noglobstar === true) { consume(value); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === 'slash' || prior.type === 'bos'; const afterStar = before && (before.type === 'star' || before.type === 'globstar'); if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { push({ type: 'star', value, output: '' }); continue; } const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { push({ type: 'star', value, output: '' }); continue; } // strip consecutive `/**/` while (rest.slice(0, 3) === '/**') { const after = input[state.index + 4]; if (after && after !== '/') { break; } rest = rest.slice(3); consume('/**', 3); } if (prior.type === 'bos' && eos()) { prev.type = 'globstar'; prev.value += value; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); prev.value += value; state.globstar = true; state.output += prior.output + prev.output; consume(value); continue; } if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { const end = rest[1] !== void 0 ? '|$' : ''; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = 'globstar'; prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; prev.value += value; state.output += prior.output + prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } if (prior.type === 'bos' && rest[0] === '/') { prev.type = 'globstar'; prev.value += value; prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; state.output = prev.output; state.globstar = true; consume(value + advance()); push({ type: 'slash', value: '/', output: '' }); continue; } // remove single star from output state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar prev.type = 'globstar'; prev.output = globstar(opts); prev.value += value; // reset output with globstar state.output += prev.output; state.globstar = true; consume(value); continue; } const token = { type: 'star', value, output: star }; if (opts.bash === true) { token.output = '.*?'; if (prev.type === 'bos' || prev.type === 'slash') { token.output = nodot + token.output; } push(token); continue; } if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { token.output = value; push(token); continue; } if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { if (prev.type === 'dot') { state.output += NO_DOT_SLASH; prev.output += NO_DOT_SLASH; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH; prev.output += NO_DOTS_SLASH; } else { state.output += nodot; prev.output += nodot; } if (peek() !== '*') { state.output += ONE_CHAR; prev.output += ONE_CHAR; } } push(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); state.output = utils.escapeLast(state.output, '['); decrement('brackets'); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); state.output = utils.escapeLast(state.output, '('); decrement('parens'); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); state.output = utils.escapeLast(state.output, '{'); decrement('braces'); } if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); } // rebuild the output if we had to backtrack at any point if (state.backtrack === true) { state.output = ''; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; /** * Fast paths for creating regular expressions for common glob patterns. * This can significantly speed up processing and has very little downside * impact when none of the fast paths match. */ parse.fastpaths = (input, options) => { const opts = { ...options }; const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win32 = utils.isWindows(options); // create constants based on platform, for windows or posix const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants.globChars(win32); const nodot = opts.dot ? NO_DOTS : NO_DOT; const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; const capture = opts.capture ? '' : '?:'; const state = { negated: false, prefix: '' }; let star = opts.bash === true ? '.*?' : STAR; if (opts.capture) { star = `(${star})`; } const globstar = opts => { if (opts.noglobstar === true) return star; return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; }; const create = str => { switch (str) { case '*': return `${nodot}${ONE_CHAR}${star}`; case '.*': return `${DOT_LITERAL}${ONE_CHAR}${star}`; case '*.*': return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '*/*': return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; case '**': return nodot + globstar(opts); case '**/*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; case '**/*.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; case '**/.*': return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; default: { const match = /^(.*?)\.(\w+)$/.exec(str); if (!match) return; const source = create(match[1]); if (!source) return; return source + DOT_LITERAL + match[2]; } } }; const output = utils.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL}?`; } return source; }; module.exports = parse; /***/ }), /***/ 3322: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(1017); const scan = __nccwpck_require__(2429); const parse = __nccwpck_require__(2139); const utils = __nccwpck_require__(479); const constants = __nccwpck_require__(6099); const isObject = val => val && typeof val === 'object' && !Array.isArray(val); /** * Creates a matcher function from one or more glob patterns. The * returned function takes a string to match as its first argument, * and returns true if the string is a match. The returned matcher * function also takes a boolean as the second argument that, when true, * returns an object with additional information. * * ```js * const picomatch = require('picomatch'); * // picomatch(glob[, options]); * * const isMatch = picomatch('*.!(*a)'); * console.log(isMatch('a.a')); //=> false * console.log(isMatch('a.b')); //=> true * ``` * @name picomatch * @param {String|Array} `globs` One or more glob patterns. * @param {Object=} `options` * @return {Function=} Returns a matcher function. * @api public */ const picomatch = (glob, options, returnState = false) => { if (Array.isArray(glob)) { const fns = glob.map(input => picomatch(input, options, returnState)); const arrayMatcher = str => { for (const isMatch of fns) { const state = isMatch(str); if (state) return state; } return false; }; return arrayMatcher; } const isState = isObject(glob) && glob.tokens && glob.input; if (glob === '' || (typeof glob !== 'string' && !isState)) { throw new TypeError('Expected pattern to be a non-empty string'); } const opts = options || {}; const posix = utils.isWindows(options); const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); const state = regex.state; delete regex.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } const matcher = (input, returnObject = false) => { const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); const result = { glob, state, regex, posix, input, output, match, isMatch }; if (typeof opts.onResult === 'function') { opts.onResult(result); } if (isMatch === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === 'function') { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === 'function') { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher.state = state; } return matcher; }; /** * Test `input` with the given `regex`. This is used by the main * `picomatch()` function to test the input string. * * ```js * const picomatch = require('picomatch'); * // picomatch.test(input, regex[, options]); * * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } * ``` * @param {String} `input` String to test. * @param {RegExp} `regex` * @return {Object} Returns an object with matching info. * @api public */ picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { throw new TypeError('Expected input to be a string'); } if (input === '') { return { isMatch: false, output: '' }; } const opts = options || {}; const format = opts.format || (posix ? utils.toPosixSlashes : null); let match = input === glob; let output = (match && format) ? format(input) : input; if (match === false) { output = format ? format(input) : input; match = output === glob; } if (match === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match = picomatch.matchBase(input, regex, options, posix); } else { match = regex.exec(output); } } return { isMatch: Boolean(match), match, output }; }; /** * Match the basename of a filepath. * * ```js * const picomatch = require('picomatch'); * // picomatch.matchBase(input, glob[, options]); * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true * ``` * @param {String} `input` String to test. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). * @return {Boolean} * @api public */ picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); return regex.test(path.basename(input)); }; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * ```js * const picomatch = require('picomatch'); * // picomatch.isMatch(string, patterns[, options]); * * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false * ``` * @param {String|Array} str The string to test. * @param {String|Array} patterns One or more glob patterns to use for matching. * @param {Object} [options] See available [options](#options). * @return {Boolean} Returns true if any patterns match `str` * @api public */ picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); /** * Parse a glob pattern to create the source string for a regular * expression. * * ```js * const picomatch = require('picomatch'); * const result = picomatch.parse(pattern[, options]); * ``` * @param {String} `pattern` * @param {Object} `options` * @return {Object} Returns an object with useful properties and output to be used as a regex source string. * @api public */ picomatch.parse = (pattern, options) => { if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); return parse(pattern, { ...options, fastpaths: false }); }; /** * Scan a glob pattern to separate the pattern into segments. * * ```js * const picomatch = require('picomatch'); * // picomatch.scan(input[, options]); * * const result = picomatch.scan('!./foo/*.js'); * console.log(result); * { prefix: '!./', * input: '!./foo/*.js', * start: 3, * base: 'foo', * glob: '*.js', * isBrace: false, * isBracket: false, * isGlob: true, * isExtglob: false, * isGlobstar: false, * negated: true } * ``` * @param {String} `input` Glob pattern to scan. * @param {Object} `options` * @return {Object} Returns an object with * @api public */ picomatch.scan = (input, options) => scan(input, options); /** * Compile a regular expression from the `state` object returned by the * [parse()](#parse) method. * * @param {Object} `state` * @param {Object} `options` * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * @return {RegExp} * @api public */ picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options || {}; const prepend = opts.contains ? '' : '^'; const append = opts.contains ? '' : '$'; let source = `${prepend}(?:${state.output})${append}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex = picomatch.toRegex(source, options); if (returnState === true) { regex.state = state; } return regex; }; /** * Create a regular expression from a parsed glob pattern. * * ```js * const picomatch = require('picomatch'); * const state = picomatch.parse('*.js'); * // picomatch.compileRe(state[, options]); * * console.log(picomatch.compileRe(state)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `state` The object returned from the `.parse` method. * @param {Object} `options` * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * @return {RegExp} Returns a regex created from the given pattern. * @api public */ picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== 'string') { throw new TypeError('Expected a non-empty string'); } let parsed = { negated: false, fastpaths: true }; if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { parsed.output = parse.fastpaths(input, options); } if (!parsed.output) { parsed = parse(input, options); } return picomatch.compileRe(parsed, options, returnOutput, returnState); }; /** * Create a regular expression from the given regex source string. * * ```js * const picomatch = require('picomatch'); * // picomatch.toRegex(source[, options]); * * const { output } = picomatch.parse('*.js'); * console.log(picomatch.toRegex(output)); * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ * ``` * @param {String} `source` Regular expression source string. * @param {Object} `options` * @return {RegExp} * @api public */ picomatch.toRegex = (source, options) => { try { const opts = options || {}; return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); } catch (err) { if (options && options.debug === true) throw err; return /$^/; } }; /** * Picomatch constants. * @return {Object} */ picomatch.constants = constants; /** * Expose "picomatch" */ module.exports = picomatch; /***/ }), /***/ 2429: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const utils = __nccwpck_require__(479); const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ } = __nccwpck_require__(6099); const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; const depth = token => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; /** * Quickly scans a glob pattern and returns an object with a handful of * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). * * ```js * const pm = require('picomatch'); * console.log(pm.scan('foo/bar/*.js')); * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } * ``` * @param {String} `str` * @param {Object} `options` * @return {Object} Returns an object with tokens and regex source string. * @api public */ const scan = (input, options) => { const opts = options || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob = false; let isExtglob = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces = 0; let prev; let code; let token = { value: '', depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { braces++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE) { braces++; continue; } if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA) { isBrace = token.isBrace = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE) { braces--; if (braces === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: '', depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT && index === (start + 1)) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; isExtglob = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { isGlob = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET) { isBracket = token.isBracket = true; isGlob = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { isGlob = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES) { finished = true; break; } } continue; } break; } if (isGlob === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob = false; isGlob = false; } let base = str; let prefix = ''; let glob = ''; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob = str.slice(lastIndex); } else if (isGlob === true) { base = ''; glob = str; } else { base = str; } if (base && base !== '' && base !== '/' && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob) glob = utils.removeBackslashes(glob); if (base && backslashes === true) { base = utils.removeBackslashes(base); } } const state = { prefix, input, start, base, glob, isBrace, isBracket, isGlob, isExtglob, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value = input.slice(n, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value !== '') { parts.push(value); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value = input.slice(prevIndex + 1); parts.push(value); if (opts.tokens) { tokens[tokens.length - 1].value = value; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; module.exports = scan; /***/ }), /***/ 479: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; const path = __nccwpck_require__(1017); const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = __nccwpck_require__(6099); exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); exports.removeBackslashes = str => { return str.replace(REGEX_REMOVE_BACKSLASH, match => { return match === '\\' ? '' : match; }); }; exports.supportsLookbehinds = () => { const segs = process.version.slice(1).split('.').map(Number); if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { return true; } return false; }; exports.isWindows = options => { if (options && typeof options.windows === 'boolean') { return options.windows; } return win32 === true || path.sep === '\\'; }; exports.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith('./')) { output = output.slice(2); state.prefix = './'; } return output; }; exports.wrapOutput = (input, state = {}, options = {}) => { const prepend = options.contains ? '' : '^'; const append = options.contains ? '' : '$'; let output = `${prepend}(?:${input})${append}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; /***/ }), /***/ 9795: /***/ ((module) => { /*! queue-microtask. MIT License. Feross Aboukhadijeh */ let promise module.exports = typeof queueMicrotask === 'function' ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global) // reuse resolved promise, and allocate it lazily : cb => (promise || (promise = Promise.resolve())) .then(cb) .catch(err => setTimeout(() => { throw err }, 0)) /***/ }), /***/ 2113: /***/ ((module) => { "use strict"; function reusify (Constructor) { var head = new Constructor() var tail = head function get () { var current = head if (current.next) { head = current.next } else { head = new Constructor() tail = head } current.next = null return current } function release (obj) { tail.next = obj tail = obj } return { get: get, release: release } } module.exports = reusify /***/ }), /***/ 5288: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! run-parallel. MIT License. Feross Aboukhadijeh */ module.exports = runParallel const queueMicrotask = __nccwpck_require__(9795) function runParallel (tasks, cb) { let results, pending, keys let isSync = true if (Array.isArray(tasks)) { results = [] pending = tasks.length } else { keys = Object.keys(tasks) results = {} pending = keys.length } function done (err) { function end () { if (cb) cb(err, results) cb = null } if (isSync) queueMicrotask(end) else end() } function each (i, err, result) { results[i] = result if (--pending === 0 || err) { done(err) } } if (!pending) { // empty done(null) } else if (keys) { // object keys.forEach(function (key) { tasks[key](function (err, result) { each(key, err, result) }) }) } else { // array tasks.forEach(function (task, i) { task(function (err, result) { each(i, err, result) }) }) } isSync = false } /***/ }), /***/ 1861: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! * to-regex-range * * Copyright (c) 2015-present, Jon Schlinkert. * Released under the MIT License. */ const isNumber = __nccwpck_require__(5680); const toRegexRange = (min, max, options) => { if (isNumber(min) === false) { throw new TypeError('toRegexRange: expected the first argument to be a number'); } if (max === void 0 || min === max) { return String(min); } if (isNumber(max) === false) { throw new TypeError('toRegexRange: expected the second argument to be a number.'); } let opts = { relaxZeros: true, ...options }; if (typeof opts.strictZeros === 'boolean') { opts.relaxZeros = opts.strictZeros === false; } let relax = String(opts.relaxZeros); let shorthand = String(opts.shorthand); let capture = String(opts.capture); let wrap = String(opts.wrap); let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; if (toRegexRange.cache.hasOwnProperty(cacheKey)) { return toRegexRange.cache[cacheKey].result; } let a = Math.min(min, max); let b = Math.max(min, max); if (Math.abs(a - b) === 1) { let result = min + '|' + max; if (opts.capture) { return `(${result})`; } if (opts.wrap === false) { return result; } return `(?:${result})`; } let isPadded = hasPadding(min) || hasPadding(max); let state = { min, max, a, b }; let positives = []; let negatives = []; if (isPadded) { state.isPadded = isPadded; state.maxLen = String(state.max).length; } if (a < 0) { let newMin = b < 0 ? Math.abs(b) : 1; negatives = splitToPatterns(newMin, Math.abs(a), state, opts); a = state.a = 0; } if (b >= 0) { positives = splitToPatterns(a, b, state, opts); } state.negatives = negatives; state.positives = positives; state.result = collatePatterns(negatives, positives, opts); if (opts.capture === true) { state.result = `(${state.result})`; } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { state.result = `(?:${state.result})`; } toRegexRange.cache[cacheKey] = state; return state.result; }; function collatePatterns(neg, pos, options) { let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; let intersected = filterPatterns(neg, pos, '-?', true, options) || []; let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); return subpatterns.join('|'); } function splitToRanges(min, max) { let nines = 1; let zeros = 1; let stop = countNines(min, nines); let stops = new Set([max]); while (min <= stop && stop <= max) { stops.add(stop); nines += 1; stop = countNines(min, nines); } stop = countZeros(max + 1, zeros) - 1; while (min < stop && stop <= max) { stops.add(stop); zeros += 1; stop = countZeros(max + 1, zeros) - 1; } stops = [...stops]; stops.sort(compare); return stops; } /** * Convert a range to a regex pattern * @param {Number} `start` * @param {Number} `stop` * @return {String} */ function rangeToPattern(start, stop, options) { if (start === stop) { return { pattern: start, count: [], digits: 0 }; } let zipped = zip(start, stop); let digits = zipped.length; let pattern = ''; let count = 0; for (let i = 0; i < digits; i++) { let [startDigit, stopDigit] = zipped[i]; if (startDigit === stopDigit) { pattern += startDigit; } else if (startDigit !== '0' || stopDigit !== '9') { pattern += toCharacterClass(startDigit, stopDigit, options); } else { count++; } } if (count) { pattern += options.shorthand === true ? '\\d' : '[0-9]'; } return { pattern, count: [count], digits }; } function splitToPatterns(min, max, tok, options) { let ranges = splitToRanges(min, max); let tokens = []; let start = min; let prev; for (let i = 0; i < ranges.length; i++) { let max = ranges[i]; let obj = rangeToPattern(String(start), String(max), options); let zeros = ''; if (!tok.isPadded && prev && prev.pattern === obj.pattern) { if (prev.count.length > 1) { prev.count.pop(); } prev.count.push(obj.count[0]); prev.string = prev.pattern + toQuantifier(prev.count); start = max + 1; continue; } if (tok.isPadded) { zeros = padZeros(max, tok, options); } obj.string = zeros + obj.pattern + toQuantifier(obj.count); tokens.push(obj); start = max + 1; prev = obj; } return tokens; } function filterPatterns(arr, comparison, prefix, intersection, options) { let result = []; for (let ele of arr) { let { string } = ele; // only push if _both_ are negative... if (!intersection && !contains(comparison, 'string', string)) { result.push(prefix + string); } // or _both_ are positive if (intersection && contains(comparison, 'string', string)) { result.push(prefix + string); } } return result; } /** * Zip strings */ function zip(a, b) { let arr = []; for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); return arr; } function compare(a, b) { return a > b ? 1 : b > a ? -1 : 0; } function contains(arr, key, val) { return arr.some(ele => ele[key] === val); } function countNines(min, len) { return Number(String(min).slice(0, -len) + '9'.repeat(len)); } function countZeros(integer, zeros) { return integer - (integer % Math.pow(10, zeros)); } function toQuantifier(digits) { let [start = 0, stop = ''] = digits; if (stop || start > 1) { return `{${start + (stop ? ',' + stop : '')}}`; } return ''; } function toCharacterClass(a, b, options) { return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; } function hasPadding(str) { return /^-?(0+)\d/.test(str); } function padZeros(value, tok, options) { if (!tok.isPadded) { return value; } let diff = Math.abs(tok.maxLen - String(value).length); let relax = options.relaxZeros !== false; switch (diff) { case 0: return ''; case 1: return relax ? '0?' : '0'; case 2: return relax ? '0{0,2}' : '00'; default: { return relax ? `0{0,${diff}}` : `0{${diff}}`; } } } /** * Cache */ toRegexRange.cache = {}; toRegexRange.clearCache = () => (toRegexRange.cache = {}); /** * Expose `toRegexRange` */ module.exports = toRegexRange; /***/ }), /***/ 4294: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = __nccwpck_require__(4219); /***/ }), /***/ 4219: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; var net = __nccwpck_require__(1808); var tls = __nccwpck_require__(4404); var http = __nccwpck_require__(3685); var https = __nccwpck_require__(5687); var events = __nccwpck_require__(2361); var assert = __nccwpck_require__(9491); var util = __nccwpck_require__(3837); 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 /***/ }), /***/ 4338: /***/ ((module) => { module.exports=/[\0-\x1F\x7F-\x9F]/ /***/ }), /***/ 6149: /***/ ((module) => { module.exports=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/ /***/ }), /***/ 8019: /***/ ((module) => { module.exports=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/ /***/ }), /***/ 8810: /***/ ((module) => { module.exports=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/ /***/ }), /***/ 5649: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; exports.Any = __nccwpck_require__(703); exports.Cc = __nccwpck_require__(4338); exports.Cf = __nccwpck_require__(6149); exports.P = __nccwpck_require__(8019); exports.Z = __nccwpck_require__(8810); /***/ }), /***/ 703: /***/ ((module) => { module.exports=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/ /***/ }), /***/ 5840: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "v1", ({ enumerable: true, get: function () { return _v.default; } })); Object.defineProperty(exports, "v3", ({ enumerable: true, get: function () { return _v2.default; } })); Object.defineProperty(exports, "v4", ({ enumerable: true, get: function () { return _v3.default; } })); Object.defineProperty(exports, "v5", ({ enumerable: true, get: function () { return _v4.default; } })); Object.defineProperty(exports, "NIL", ({ enumerable: true, get: function () { return _nil.default; } })); Object.defineProperty(exports, "version", ({ enumerable: true, get: function () { return _version.default; } })); Object.defineProperty(exports, "validate", ({ enumerable: true, get: function () { return _validate.default; } })); Object.defineProperty(exports, "stringify", ({ enumerable: true, get: function () { return _stringify.default; } })); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return _parse.default; } })); var _v = _interopRequireDefault(__nccwpck_require__(8628)); var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); var _nil = _interopRequireDefault(__nccwpck_require__(5332)); var _version = _interopRequireDefault(__nccwpck_require__(1595)); var _validate = _interopRequireDefault(__nccwpck_require__(6900)); var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); var _parse = _interopRequireDefault(__nccwpck_require__(2746)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ 4569: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function md5(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return _crypto.default.createHash('md5').update(bytes).digest(); } var _default = md5; exports["default"] = _default; /***/ }), /***/ 5332: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _default = '00000000-0000-0000-0000-000000000000'; exports["default"] = _default; /***/ }), /***/ 2746: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(6900)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function parse(uuid) { if (!(0, _validate.default)(uuid)) { throw TypeError('Invalid UUID'); } let v; const arr = new Uint8Array(16); // Parse ########-....-....-....-............ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; arr[1] = v >>> 16 & 0xff; arr[2] = v >>> 8 & 0xff; arr[3] = v & 0xff; // Parse ........-####-....-....-............ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; arr[5] = v & 0xff; // Parse ........-....-####-....-............ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; arr[7] = v & 0xff; // Parse ........-....-....-####-............ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; arr[9] = v & 0xff; // Parse ........-....-....-....-############ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; arr[11] = v / 0x100000000 & 0xff; arr[12] = v >>> 24 & 0xff; arr[13] = v >>> 16 & 0xff; arr[14] = v >>> 8 & 0xff; arr[15] = v & 0xff; return arr; } var _default = parse; exports["default"] = _default; /***/ }), /***/ 814: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; exports["default"] = _default; /***/ }), /***/ 807: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = rng; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate let poolPtr = rnds8Pool.length; function rng() { if (poolPtr > rnds8Pool.length - 16) { _crypto.default.randomFillSync(rnds8Pool); poolPtr = 0; } return rnds8Pool.slice(poolPtr, poolPtr += 16); } /***/ }), /***/ 5274: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function sha1(bytes) { if (Array.isArray(bytes)) { bytes = Buffer.from(bytes); } else if (typeof bytes === 'string') { bytes = Buffer.from(bytes, 'utf8'); } return _crypto.default.createHash('sha1').update(bytes).digest(); } var _default = sha1; exports["default"] = _default; /***/ }), /***/ 8950: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(6900)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ const byteToHex = []; for (let i = 0; i < 256; ++i) { byteToHex.push((i + 0x100).toString(16).substr(1)); } function stringify(arr, offset = 0) { // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!(0, _validate.default)(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } var _default = stringify; exports["default"] = _default; /***/ }), /***/ 8628: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(807)); var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html let _nodeId; let _clockseq; // Previous uuid creation time let _lastMSecs = 0; let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { let i = buf && offset || 0; const b = buf || new Array(16); options = options || {}; let node = options.node || _nodeId; let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { const seedBytes = options.random || (options.rng || _rng.default)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (let n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf || (0, _stringify.default)(b); } var _default = v1; exports["default"] = _default; /***/ }), /***/ 6409: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(5998)); var _md = _interopRequireDefault(__nccwpck_require__(4569)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const v3 = (0, _v.default)('v3', 0x30, _md.default); var _default = v3; exports["default"] = _default; /***/ }), /***/ 5998: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = _default; exports.URL = exports.DNS = void 0; var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); var _parse = _interopRequireDefault(__nccwpck_require__(2746)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function stringToBytes(str) { str = unescape(encodeURIComponent(str)); // UTF8 escape const bytes = []; for (let i = 0; i < str.length; ++i) { bytes.push(str.charCodeAt(i)); } return bytes; } const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; exports.DNS = DNS; const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; exports.URL = URL; function _default(name, version, hashfunc) { function generateUUID(value, namespace, buf, offset) { if (typeof value === 'string') { value = stringToBytes(value); } if (typeof namespace === 'string') { namespace = (0, _parse.default)(namespace); } if (namespace.length !== 16) { throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); } // Compute hash of namespace and value, Per 4.3 // Future: Use spread syntax when supported on all platforms, e.g. `bytes = // hashfunc([...namespace, ... value])` let bytes = new Uint8Array(16 + value.length); bytes.set(namespace); bytes.set(value, namespace.length); bytes = hashfunc(bytes); bytes[6] = bytes[6] & 0x0f | version; bytes[8] = bytes[8] & 0x3f | 0x80; if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = bytes[i]; } return buf; } return (0, _stringify.default)(bytes); } // Function#name is not settable on some platforms (#270) try { generateUUID.name = name; // eslint-disable-next-line no-empty } catch (err) {} // For CommonJS default export support generateUUID.DNS = DNS; generateUUID.URL = URL; return generateUUID; } /***/ }), /***/ 5122: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _rng = _interopRequireDefault(__nccwpck_require__(807)); var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function v4(options, buf, offset) { options = options || {}; const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = rnds[i]; } return buf; } return (0, _stringify.default)(rnds); } var _default = v4; exports["default"] = _default; /***/ }), /***/ 9120: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _v = _interopRequireDefault(__nccwpck_require__(5998)); var _sha = _interopRequireDefault(__nccwpck_require__(5274)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const v5 = (0, _v.default)('v5', 0x50, _sha.default); var _default = v5; exports["default"] = _default; /***/ }), /***/ 6900: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _regex = _interopRequireDefault(__nccwpck_require__(814)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(uuid) { return typeof uuid === 'string' && _regex.default.test(uuid); } var _default = validate; exports["default"] = _default; /***/ }), /***/ 1595: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = void 0; var _validate = _interopRequireDefault(__nccwpck_require__(6900)); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function version(uuid) { if (!(0, _validate.default)(uuid)) { throw TypeError('Invalid UUID'); } return parseInt(uuid.substr(14, 1), 16); } var _default = version; exports["default"] = _default; /***/ }), /***/ 9491: /***/ ((module) => { "use strict"; module.exports = require("assert"); /***/ }), /***/ 6113: /***/ ((module) => { "use strict"; module.exports = require("crypto"); /***/ }), /***/ 2361: /***/ ((module) => { "use strict"; module.exports = require("events"); /***/ }), /***/ 7147: /***/ ((module) => { "use strict"; module.exports = require("fs"); /***/ }), /***/ 3685: /***/ ((module) => { "use strict"; module.exports = require("http"); /***/ }), /***/ 5687: /***/ ((module) => { "use strict"; module.exports = require("https"); /***/ }), /***/ 1808: /***/ ((module) => { "use strict"; module.exports = require("net"); /***/ }), /***/ 7561: /***/ ((module) => { "use strict"; module.exports = require("node:fs"); /***/ }), /***/ 612: /***/ ((module) => { "use strict"; module.exports = require("node:os"); /***/ }), /***/ 9411: /***/ ((module) => { "use strict"; module.exports = require("node:path"); /***/ }), /***/ 1041: /***/ ((module) => { "use strict"; module.exports = require("node:url"); /***/ }), /***/ 2037: /***/ ((module) => { "use strict"; module.exports = require("os"); /***/ }), /***/ 1017: /***/ ((module) => { "use strict"; module.exports = require("path"); /***/ }), /***/ 5477: /***/ ((module) => { "use strict"; module.exports = require("punycode"); /***/ }), /***/ 2781: /***/ ((module) => { "use strict"; module.exports = require("stream"); /***/ }), /***/ 4404: /***/ ((module) => { "use strict"; module.exports = require("tls"); /***/ }), /***/ 3837: /***/ ((module) => { "use strict"; module.exports = require("util"); /***/ }), /***/ 7314: /***/ ((module) => { "use strict"; // @ts-check const sliceSize = 1000; /** * Efficiently appends the source array to the destination array. * @param {Object[]} destination Destination Array. * @param {Object[]} source Source Array. * @returns void */ const appendToArray = (destination, source) => { // NOTE: destination.push(...source) throws "RangeError: Maximum call stack // size exceeded" for sufficiently lengthy source arrays let index = 0; let slice = null; while ((slice = source.slice(index, index + sliceSize)).length > 0) { destination.push(...slice); index += sliceSize; } }; appendToArray.sliceSize = sliceSize; module.exports = appendToArray; /***/ }), /***/ 9247: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check // @ts-ignore // eslint-disable-next-line camelcase, max-len, no-inline-comments, no-undef const dynamicRequire = (typeof require === "undefined") ? require : /* c8 ignore next */ eval("require"); // Capture native require implementation for dynamic loading of modules // Requires const path = __nccwpck_require__(9411); const { pathToFileURL } = __nccwpck_require__(1041); const markdownlintLibrary = __nccwpck_require__(8397); const { markdownlint, "readConfig": markdownlintReadConfig } = markdownlintLibrary.promises; const markdownlintRuleHelpers = __nccwpck_require__(2935); const appendToArray = __nccwpck_require__(7314); const mergeOptions = __nccwpck_require__(8446); const resolveAndRequire = __nccwpck_require__(5317); // Variables const packageName = "markdownlint-cli2"; const packageVersion = "0.5.1"; const libraryName = "markdownlint"; const libraryVersion = markdownlintLibrary.getVersion(); const dotOnlySubstitute = "*.{md,markdown}"; const utf8 = "utf8"; // No-op function const noop = () => null; // Gets a synchronous function to parse JSONC text const getJsoncParse = async () => { const { "default": stripJsonComments } = // eslint-disable-next-line max-len // eslint-disable-next-line no-inline-comments, node/no-unsupported-features/es-syntax await Promise.resolve(/* import() eager */).then(__nccwpck_require__.bind(__nccwpck_require__, 1519)); return (text) => JSON.parse(stripJsonComments(text)); }; // Synchronous function to parse YAML text const yamlParse = (text) => (__nccwpck_require__(4083).parse)(text); // Negate a glob const negateGlob = (glob) => `!${glob}`; // Return a posix path (even on Windows) const posixPath = (p) => p.split(path.sep).join(path.posix.sep); // Read a JSON(C) or YAML file and return the object const readConfig = (fs, dir, name, otherwise) => { const file = path.posix.join(dir, name); return () => fs.promises.access(file). then( () => getJsoncParse().then( (jsoncParse) => markdownlintReadConfig( file, [ jsoncParse, yamlParse ], fs ) ), otherwise ); }; // Import or resolve/require a module ID with a custom directory in the path const importOrRequireResolve = async (dir, id) => { if (typeof id === "string") { const expandId = markdownlintRuleHelpers.expandTildePath(id, __nccwpck_require__(612)); const errors = []; try { return resolveAndRequire(dynamicRequire, expandId, dir); } catch (error) { errors.push(error); } try { const fileUrlString = pathToFileURL(path.resolve(dir, expandId)).toString(); // eslint-disable-next-line max-len // eslint-disable-next-line no-inline-comments, node/no-unsupported-features/es-syntax const module = await import(/* webpackIgnore: true */ fileUrlString); return module.default; } catch (error) { errors.push(error); } // Use AggregateError once available in Node 15+ throw new Error(errors.map((error) => error.message).join(" / ")); } return id; }; // Import or require an array of modules by ID const importOrRequireIds = (dir, ids, noRequire) => ( Promise.all(noRequire ? [] : ids.map((id) => importOrRequireResolve(dir, id))) ); // Import or require an array of modules by ID (preserving parameters) const importOrRequireIdsAndParams = async (dir, idsAndParams, noRequire) => { if (noRequire) { return []; } const ids = idsAndParams.map((entry) => entry[0]); const modules = await importOrRequireIds(dir, ids); const modulesAndParams = idsAndParams. map((entry, i) => [ modules[i], ...entry.slice(1) ]); return modulesAndParams; }; // Import or require a JavaScript file and return the exported object const importOrRequireConfig = (fs, dir, name, noRequire, otherwise) => ( () => (noRequire // eslint-disable-next-line prefer-promise-reject-errors ? Promise.reject() : fs.promises.access(path.posix.join(dir, name)) ). then( () => importOrRequireResolve(dir, `./${name}`), otherwise ) ); // Read an options or config file in any format and return the object const readOptionsOrConfig = async (configPath, fs, noRequire) => { const basename = path.basename(configPath); const dirname = path.dirname(configPath); let options = null; let config = null; if (basename.endsWith(".markdownlint-cli2.jsonc")) { const jsoncParse = await getJsoncParse(); options = jsoncParse(await fs.promises.readFile(configPath, utf8)); } else if (basename.endsWith(".markdownlint-cli2.yaml")) { options = yamlParse(await fs.promises.readFile(configPath, utf8)); } else if ( basename.endsWith(".markdownlint-cli2.cjs") || basename.endsWith(".markdownlint-cli2.mjs") ) { options = await ( importOrRequireConfig(fs, dirname, basename, noRequire, noop)() ); } else if ( basename.endsWith(".markdownlint.jsonc") || basename.endsWith(".markdownlint.json") || basename.endsWith(".markdownlint.yaml") || basename.endsWith(".markdownlint.yml") ) { const jsoncParse = await getJsoncParse(); config = await markdownlintReadConfig(configPath, [ jsoncParse, yamlParse ], fs); } else if ( basename.endsWith(".markdownlint.cjs") || basename.endsWith(".markdownlint.mjs") ) { config = await ( importOrRequireConfig(fs, dirname, basename, noRequire, noop)() ); } else { throw new Error( `Configuration file "${configPath}" is unrecognized; ` + "its name should be (or end with) one of the supported types " + "(e.g., \".markdownlint.json\" or \"example.markdownlint-cli2.jsonc\")." ); } return options || { config }; }; // Filter a list of files to ignore by glob const removeIgnoredFiles = (dir, files, ignores) => { const micromatch = __nccwpck_require__(6228); return micromatch( files.map((file) => path.posix.relative(dir, file)), ignores ).map((file) => path.posix.join(dir, file)); }; // Process/normalize command-line arguments and return glob patterns const processArgv = (argv) => { const globPatterns = (argv || []).map( (glob) => { if (glob.startsWith(":")) { return glob; } // Escape RegExp special characters recognized by fast-glob // https://github.com/mrmlnc/fast-glob#advanced-syntax const specialCharacters = /\\(?![$()*+?[\]^])/gu; if (glob.startsWith("\\:")) { return `\\:${glob.slice(2).replace(specialCharacters, "/")}`; } return (glob.startsWith("#") ? `!${glob.slice(1)}` : glob). replace(specialCharacters, "/"); } ); if ((globPatterns.length === 1) && (globPatterns[0] === ".")) { // Substitute a more reasonable pattern globPatterns[0] = dotOnlySubstitute; } return globPatterns; }; // Show help if missing arguments const showHelp = (logMessage) => { /* eslint-disable max-len */ logMessage(`https://github.com/DavidAnson/markdownlint-cli2 Syntax: markdownlint-cli2 glob0 [glob1] [...] [globN] markdownlint-cli2-fix glob0 [glob1] [...] [globN] markdownlint-cli2-config config-file glob0 [glob1] [...] [globN] Glob expressions (from the globby library): - * matches any number of characters, but not / - ? matches a single character, but not / - ** matches any number of characters, including / - {} allows for a comma-separated list of "or" expressions - ! or # at the beginning of a pattern negate the match - : at the beginning identifies a literal file path Dot-only glob: - The command "markdownlint-cli2 ." would lint every file in the current directory tree which is probably not intended - Instead, it is mapped to "markdownlint-cli2 ${dotOnlySubstitute}" which lints all Markdown files in the current directory - To lint every file in the current directory tree, the command "markdownlint-cli2 **" can be used instead Configuration via: - .markdownlint-cli2.jsonc - .markdownlint-cli2.yaml - .markdownlint-cli2.cjs or .markdownlint-cli2.mjs - .markdownlint.jsonc or .markdownlint.json - .markdownlint.yaml or .markdownlint.yml - .markdownlint.cjs or .markdownlint.mjs Cross-platform compatibility: - UNIX and Windows shells expand globs according to different rules; quoting arguments is recommended - Some Windows shells don't handle single-quoted (') arguments well; double-quote (") is recommended - Shells that expand globs do not support negated patterns (!node_modules); quoting is required here - Some UNIX shells parse exclamation (!) in double-quotes; hashtag (#) is recommended in these cases - The path separator is forward slash (/) on all platforms; backslash (\\) is automatically converted The most compatible syntax for cross-platform support: $ markdownlint-cli2 "**/*.md" "#node_modules"` ); /* eslint-enable max-len */ }; // Get (creating if necessary) and process a directory's info object const getAndProcessDirInfo = (fs, tasks, dirToDirInfo, dir, relativeDir, noRequire, func) => { let dirInfo = dirToDirInfo[dir]; if (!dirInfo) { dirInfo = { dir, relativeDir, "parent": null, "files": [], "markdownlintConfig": null, "markdownlintOptions": null }; dirToDirInfo[dir] = dirInfo; // Load markdownlint-cli2 object(s) const markdownlintCli2Jsonc = path.posix.join(dir, ".markdownlint-cli2.jsonc"); const markdownlintCli2Yaml = path.posix.join(dir, ".markdownlint-cli2.yaml"); tasks.push( fs.promises.access(markdownlintCli2Jsonc). then( () => fs.promises. readFile(markdownlintCli2Jsonc, utf8). then( (content) => getJsoncParse(). then((jsoncParse) => jsoncParse(content)) ), () => fs.promises.access(markdownlintCli2Yaml). then( () => fs.promises. readFile(markdownlintCli2Yaml, utf8). then(yamlParse), importOrRequireConfig( fs, dir, ".markdownlint-cli2.cjs", noRequire, importOrRequireConfig( fs, dir, ".markdownlint-cli2.mjs", noRequire, noop ) ) ) ). then((options) => { dirInfo.markdownlintOptions = options; }) ); // Load markdownlint object(s) const readConfigs = readConfig( fs, dir, ".markdownlint.jsonc", readConfig( fs, dir, ".markdownlint.json", readConfig( fs, dir, ".markdownlint.yaml", readConfig( fs, dir, ".markdownlint.yml", importOrRequireConfig( fs, dir, ".markdownlint.cjs", noRequire, importOrRequireConfig( fs, dir, ".markdownlint.mjs", noRequire, noop ) ) ) ) ) ); tasks.push( readConfigs(). then((config) => { dirInfo.markdownlintConfig = config; }) ); } if (func) { func(dirInfo); } return dirInfo; }; // Get base markdownlint-cli2 options object const getBaseOptions = async ( fs, baseDir, relativeDir, globPatterns, options, fixDefault, noGlobs, noRequire ) => { const tasks = []; const dirToDirInfo = {}; getAndProcessDirInfo( fs, tasks, dirToDirInfo, baseDir, relativeDir, noRequire ); await Promise.all(tasks); // eslint-disable-next-line no-multi-assign const baseMarkdownlintOptions = dirToDirInfo[baseDir].markdownlintOptions = mergeOptions( mergeOptions(options, { "fix": fixDefault }), dirToDirInfo[baseDir].markdownlintOptions ); if (!noGlobs) { // Append any globs specified in markdownlint-cli2 configuration const globs = baseMarkdownlintOptions.globs || []; appendToArray(globPatterns, globs); } // Pass base ignore globs as globby patterns (best performance) const ignorePatterns = // eslint-disable-next-line unicorn/no-array-callback-reference (baseMarkdownlintOptions.ignores || []).map(negateGlob); appendToArray(globPatterns, ignorePatterns); return { baseMarkdownlintOptions, dirToDirInfo }; }; // Enumerate files from globs and build directory infos const enumerateFiles = // eslint-disable-next-line max-len async (fs, baseDirSystem, baseDir, globPatterns, dirToDirInfo, noErrors, noRequire) => { const tasks = []; const globbyOptions = { "absolute": true, "cwd": baseDir, "dot": true, "expandDirectories": false, fs }; if (noErrors) { globbyOptions.suppressErrors = true; } // Special-case literal files const literalFiles = []; const filteredGlobPatterns = globPatterns.filter( (globPattern) => { if (globPattern.startsWith(":")) { literalFiles.push( posixPath(path.resolve(baseDirSystem, globPattern.slice(1))) ); return false; } return true; } ).map((globPattern) => globPattern.replace(/^\\:/u, ":")); const baseMarkdownlintOptions = dirToDirInfo[baseDir].markdownlintOptions; const globsForIgnore = (baseMarkdownlintOptions.globs || []). filter((glob) => glob.startsWith("!")); const filteredLiteralFiles = ((literalFiles.length > 0) && (globsForIgnore.length > 0)) ? removeIgnoredFiles(baseDir, literalFiles, globsForIgnore) : literalFiles; // Manually expand directories to avoid globby call to dir-glob.sync const expandedDirectories = await Promise.all( filteredGlobPatterns.map((globPattern) => { const barePattern = globPattern.startsWith("!") ? globPattern.slice(1) : globPattern; const globPath = (path.posix.isAbsolute(barePattern) || path.isAbsolute(barePattern)) ? barePattern : path.posix.join(baseDir, barePattern); return fs.promises.stat(globPath). then((stats) => (stats.isDirectory() ? path.posix.join(globPattern, "**") : globPattern)). catch(() => globPattern); }) ); // Process glob patterns // eslint-disable-next-line max-len // eslint-disable-next-line no-inline-comments, node/no-unsupported-features/es-syntax const { globby } = await Promise.resolve(/* import() eager */).then(__nccwpck_require__.bind(__nccwpck_require__, 277)); const files = [ ...await globby(expandedDirectories, globbyOptions), ...filteredLiteralFiles ]; for (const file of files) { const dir = path.posix.dirname(file); getAndProcessDirInfo( fs, tasks, dirToDirInfo, dir, null, noRequire, (dirInfo) => { dirInfo.files.push(file); } ); } await Promise.all(tasks); }; // Enumerate (possibly missing) parent directories and update directory infos const enumerateParents = async (fs, baseDir, dirToDirInfo, noRequire) => { const tasks = []; // Create a lookup of baseDir and parents const baseDirParents = {}; let baseDirParent = baseDir; do { baseDirParents[baseDirParent] = true; baseDirParent = path.posix.dirname(baseDirParent); } while (!baseDirParents[baseDirParent]); // Visit parents of each dirInfo for (let lastDirInfo of Object.values(dirToDirInfo)) { let { dir } = lastDirInfo; let lastDir = dir; while ( !baseDirParents[dir] && (dir = path.posix.dirname(dir)) && (dir !== lastDir) ) { lastDir = dir; lastDirInfo = getAndProcessDirInfo( fs, tasks, dirToDirInfo, dir, null, noRequire, // eslint-disable-next-line no-loop-func (dirInfo) => { lastDirInfo.parent = dirInfo; } ); } // If dir not under baseDir, inject it as parent for configuration if (dir !== baseDir) { dirToDirInfo[dir].parent = dirToDirInfo[baseDir]; } } await Promise.all(tasks); }; // Create directory info objects by enumerating file globs const createDirInfos = // eslint-disable-next-line max-len async (fs, baseDirSystem, baseDir, globPatterns, dirToDirInfo, optionsOverride, noErrors, noRequire) => { await enumerateFiles( fs, baseDirSystem, baseDir, globPatterns, dirToDirInfo, noErrors, noRequire ); await enumerateParents( fs, baseDir, dirToDirInfo, noRequire ); // Merge file lists with identical configuration const dirs = Object.keys(dirToDirInfo); dirs.sort((a, b) => b.length - a.length); const dirInfos = []; const noConfigDirInfo = // eslint-disable-next-line unicorn/consistent-function-scoping (dirInfo) => ( dirInfo.parent && !dirInfo.markdownlintConfig && !dirInfo.markdownlintOptions ); const tasks = []; for (const dir of dirs) { const dirInfo = dirToDirInfo[dir]; if (noConfigDirInfo(dirInfo)) { if (dirInfo.parent) { appendToArray(dirInfo.parent.files, dirInfo.files); } dirToDirInfo[dir] = null; } else { const { markdownlintOptions, relativeDir } = dirInfo; if (markdownlintOptions && markdownlintOptions.customRules) { tasks.push( importOrRequireIds( relativeDir || dir, markdownlintOptions.customRules, noRequire ).then((customRules) => { // Expand nested arrays (for packages that export multiple rules) markdownlintOptions.customRules = customRules.flat(); }) ); } if (markdownlintOptions && markdownlintOptions.markdownItPlugins) { tasks.push( importOrRequireIdsAndParams( relativeDir || dir, markdownlintOptions.markdownItPlugins, noRequire ).then((markdownItPlugins) => { markdownlintOptions.markdownItPlugins = markdownItPlugins; }) ); } dirInfos.push(dirInfo); } } await Promise.all(tasks); for (const dirInfo of dirInfos) { while (dirInfo.parent && !dirToDirInfo[dirInfo.parent.dir]) { dirInfo.parent = dirInfo.parent.parent; } } // Verify dirInfos is simplified // if ( // dirInfos.filter( // (di) => di.parent && !dirInfos.includes(di.parent) // ).length > 0 // ) { // throw new Error("Extra parent"); // } // if ( // dirInfos.filter( // (di) => !di.parent && (di.dir !== baseDir) // ).length > 0 // ) { // throw new Error("Missing parent"); // } // if ( // dirInfos.filter( // (di) => di.parent && // !((di.markdownlintConfig ? 1 : 0) ^ (di.markdownlintOptions ? 1 : 0)) // ).length > 0 // ) { // throw new Error("Missing object"); // } // if (dirInfos.filter((di) => di.dir === "/").length > 0) { // throw new Error("Includes root"); // } // Merge configuration by inheritance for (const dirInfo of dirInfos) { let markdownlintOptions = dirInfo.markdownlintOptions || {}; let { markdownlintConfig } = dirInfo; let parent = dirInfo; // eslint-disable-next-line prefer-destructuring while ((parent = parent.parent)) { if (parent.markdownlintOptions) { markdownlintOptions = mergeOptions( parent.markdownlintOptions, markdownlintOptions ); } if ( !markdownlintConfig && parent.markdownlintConfig && !markdownlintOptions.config ) { // eslint-disable-next-line prefer-destructuring markdownlintConfig = parent.markdownlintConfig; } } dirInfo.markdownlintOptions = mergeOptions( markdownlintOptions, optionsOverride ); dirInfo.markdownlintConfig = markdownlintConfig; } return dirInfos; }; // Lint files in groups by shared configuration const lintFiles = async (fs, dirInfos, fileContents) => { const jsoncParse = await getJsoncParse(); const tasks = []; // For each dirInfo for (const dirInfo of dirInfos) { const { dir, files, markdownlintConfig, markdownlintOptions } = dirInfo; // Filter file/string inputs to only those in the dirInfo let filesAfterIgnores = files; if ( markdownlintOptions.ignores && (markdownlintOptions.ignores.length > 0) ) { // eslint-disable-next-line unicorn/no-array-callback-reference const ignores = markdownlintOptions.ignores.map(negateGlob); filesAfterIgnores = removeIgnoredFiles(dir, files, ignores); } const filteredFiles = filesAfterIgnores.filter( (file) => fileContents[file] === undefined ); const filteredStrings = {}; for (const file of filesAfterIgnores) { if (fileContents[file] !== undefined) { filteredStrings[file] = fileContents[file]; } } // Create markdownlint options object const options = { "files": filteredFiles, "strings": filteredStrings, "config": markdownlintConfig || markdownlintOptions.config, "configParsers": [ jsoncParse ], "customRules": markdownlintOptions.customRules, "frontMatter": markdownlintOptions.frontMatter ? new RegExp(markdownlintOptions.frontMatter, "u") : undefined, "handleRuleFailures": true, "markdownItPlugins": markdownlintOptions.markdownItPlugins, "noInlineConfig": Boolean(markdownlintOptions.noInlineConfig), "resultVersion": 3, fs }; // Invoke markdownlint // @ts-ignore let task = markdownlint(options); // For any fixable errors, read file, apply fixes, and write it back if (markdownlintOptions.fix) { task = task.then((results) => { options.files = []; const subTasks = []; const errorFiles = Object.keys(results); for (const fileName of errorFiles) { const errorInfos = results[fileName]. filter((errorInfo) => errorInfo.fixInfo); if (errorInfos.length > 0) { delete results[fileName]; options.files.push(fileName); subTasks.push(fs.promises.readFile(fileName, utf8). then((original) => { const fixed = markdownlintRuleHelpers. applyFixes(original, errorInfos); return fs.promises.writeFile(fileName, fixed, utf8); }) ); } } return Promise.all(subTasks). // @ts-ignore then(() => markdownlint(options)). then((fixResults) => ({ ...results, ...fixResults })); }); } // Queue tasks for this dirInfo tasks.push(task); } // Return result of all tasks return Promise.all(tasks); }; // Create summary of results const createSummary = (baseDir, taskResults) => { const summary = []; let counter = 0; for (const results of taskResults) { for (const fileName in results) { const errorInfos = results[fileName]; for (const errorInfo of errorInfos) { const fileNameRelative = path.posix.relative(baseDir, fileName); summary.push({ "fileName": fileNameRelative, ...errorInfo, counter }); counter++; } } } summary.sort((a, b) => ( a.fileName.localeCompare(b.fileName) || (a.lineNumber - b.lineNumber) || a.ruleNames[0].localeCompare(b.ruleNames[0]) || (a.counter - b.counter) )); for (const result of summary) { delete result.counter; } return summary; }; // Output summary via formatters const outputSummary = async ( baseDir, relativeDir, summary, outputFormatters, logMessage, logError ) => { const errorsPresent = (summary.length > 0); if (errorsPresent || outputFormatters) { const formatterOptions = { "directory": baseDir, "results": summary, logMessage, logError }; const dir = relativeDir || baseDir; const formattersAndParams = outputFormatters ? await importOrRequireIdsAndParams(dir, outputFormatters) : [ [ __nccwpck_require__(8552) ] ]; await Promise.all(formattersAndParams.map((formatterAndParams) => { const [ formatter, ...formatterParams ] = formatterAndParams; return formatter(formatterOptions, ...formatterParams); })); } return errorsPresent; }; // Main function const main = async (params) => { // Capture parameters const { directory, argv, optionsDefault, optionsOverride, fixDefault, fileContents, nonFileContents, noErrors, noGlobs, noRequire, name } = params; const logMessage = params.logMessage || noop; const logError = params.logError || noop; const fs = params.fs || __nccwpck_require__(7561); const baseDirSystem = (directory && path.resolve(directory)) || process.cwd(); const baseDir = posixPath(baseDirSystem); // Output banner logMessage( // eslint-disable-next-line max-len `${name || packageName} v${packageVersion} (${libraryName} v${libraryVersion})` ); // Read argv configuration file (if relevant and present) let optionsArgv = null; let relativeDir = null; const [ configPath ] = (argv || []); if ((name === "markdownlint-cli2-config") && configPath) { optionsArgv = await readOptionsOrConfig(configPath, fs, noRequire); relativeDir = path.dirname(configPath); } // Process arguments and get base options const globPatterns = processArgv(optionsArgv ? argv.slice(1) : argv); const { baseMarkdownlintOptions, dirToDirInfo } = await getBaseOptions( fs, baseDir, relativeDir, globPatterns, optionsArgv || optionsDefault, fixDefault, noGlobs, noRequire ); if ((globPatterns.length === 0) && !nonFileContents) { showHelp(logMessage); return 1; } // Include any file overrides or non-file content const resolvedFileContents = {}; for (const file in fileContents) { const resolvedFile = posixPath(path.resolve(baseDirSystem, file)); resolvedFileContents[resolvedFile] = fileContents[file]; } for (const nonFile in nonFileContents) { resolvedFileContents[nonFile] = nonFileContents[nonFile]; } appendToArray( dirToDirInfo[baseDir].files, Object.keys(nonFileContents || {}) ); // Output finding status const showProgress = !baseMarkdownlintOptions.noProgress; if (showProgress) { logMessage(`Finding: ${globPatterns.join(" ")}`); } // Create linting tasks const dirInfos = await createDirInfos( fs, baseDirSystem, baseDir, globPatterns, dirToDirInfo, optionsOverride, noErrors, noRequire ); // Output linting status if (showProgress) { let fileCount = 0; for (const dirInfo of dirInfos) { fileCount += dirInfo.files.length; } logMessage(`Linting: ${fileCount} file(s)`); } // Lint files const lintResults = await lintFiles(fs, dirInfos, resolvedFileContents); // Output summary const summary = createSummary(baseDir, lintResults); if (showProgress) { logMessage(`Summary: ${summary.length} error(s)`); } const outputFormatters = (optionsOverride && optionsOverride.outputFormatters) || baseMarkdownlintOptions.outputFormatters; const errorsPresent = await outputSummary( baseDir, relativeDir, summary, outputFormatters, logMessage, logError ); // Return result return errorsPresent ? 1 : 0; }; // Run function const run = (overrides) => { (async () => { try { const defaultParams = { "argv": process.argv.slice(2), "logMessage": console.log, "logError": console.error }; const params = { ...defaultParams, ...overrides }; process.exitCode = await main(params); } catch (error) { console.error(error); process.exitCode = 2; } })(); }; // Export functions module.exports = { main, run }; // Run if invoked as a CLI // @ts-ignore if (false) {} /***/ }), /***/ 8446: /***/ ((module) => { "use strict"; // @ts-check /** * Merges two options objects by combining config and replacing properties. * @param {Object} first First options object. * @param {Object} second Second options object. * @returns {Object} Merged options object. */ const mergeOptions = (first, second) => { const merged = { ...first, ...second }; const firstConfig = first && first.config; const secondConfig = second && second.config; if (firstConfig || secondConfig) { merged.config = { ...firstConfig, ...secondConfig }; } return merged; }; module.exports = mergeOptions; /***/ }), /***/ 5317: /***/ ((module) => { "use strict"; // @ts-check /** * Wrapper for calling Node's require.resolve/require with an additional path. * @param {Object} req Node's require implementation (or equivalent). * @param {String} id Package identifier to require. * @param {String} dir Directory to include when resolving paths. * @returns {Object} Exported module content. */ const resolveAndRequire = (req, id, dir) => { const resolvePaths = req.resolve.paths ? req.resolve.paths("") : []; const paths = [ dir, ...resolvePaths ]; const resolved = req.resolve(id, { paths }); return req(resolved); }; module.exports = resolveAndRequire; /***/ }), /***/ 2260: /***/ ((module) => { "use strict"; // @ts-check const map = new Map(); module.exports.set = (keyValuePairs) => { for (const [ key, value ] of Object.entries(keyValuePairs)) { map.set(key, value); } }; module.exports.clear = () => map.clear(); module.exports.codeBlockAndSpanRanges = () => map.get("codeBlockAndSpanRanges"); module.exports.flattenedLists = () => map.get("flattenedLists"); module.exports.htmlElementRanges = () => map.get("htmlElementRanges"); module.exports.lineMetadata = () => map.get("lineMetadata"); module.exports.referenceLinkImageData = () => map.get("referenceLinkImageData"); /***/ }), /***/ 983: /***/ ((module) => { "use strict"; // @ts-check module.exports.deprecatedRuleNames = [ "MD002", "MD006" ]; module.exports.homepage = "https://github.com/DavidAnson/markdownlint"; module.exports.version = "0.26.2"; /***/ }), /***/ 8397: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const path = __nccwpck_require__(1017); const { promisify } = __nccwpck_require__(3837); const markdownIt = __nccwpck_require__(8561); const { deprecatedRuleNames } = __nccwpck_require__(983); const rules = __nccwpck_require__(1796); const helpers = __nccwpck_require__(2935); const cache = __nccwpck_require__(2260); // @ts-ignore // eslint-disable-next-line camelcase, max-len, no-inline-comments, no-undef const dynamicRequire = (typeof require === "undefined") ? require : /* c8 ignore next */ eval("require"); // Capture native require implementation for dynamic loading of modules /** * Validate the list of rules for structure and reuse. * * @param {Rule[]} ruleList List of rules. * @param {boolean} synchronous Whether to execute synchronously. * @returns {Error | null} Error message if validation fails. */ function validateRuleList(ruleList, synchronous) { let result = null; if (ruleList.length === rules.length) { // No need to validate if only using built-in rules return result; } const allIds = {}; for (const [ index, rule ] of ruleList.entries()) { const customIndex = index - rules.length; // eslint-disable-next-line no-inner-declarations, jsdoc/require-jsdoc function newError(property) { return new Error( "Property '" + property + "' of custom rule at index " + customIndex + " is incorrect."); } for (const property of [ "names", "tags" ]) { const value = rule[property]; if (!result && (!value || !Array.isArray(value) || (value.length === 0) || !value.every(helpers.isString) || value.some(helpers.isEmptyString))) { result = newError(property); } } for (const propertyInfo of [ [ "description", "string" ], [ "function", "function" ] ]) { const property = propertyInfo[0]; const value = rule[property]; if (!result && (!value || (typeof value !== propertyInfo[1]))) { result = newError(property); } } if ( !result && rule.information && (Object.getPrototypeOf(rule.information) !== URL.prototype) ) { result = newError("information"); } if ( !result && (rule.asynchronous !== undefined) && (typeof rule.asynchronous !== "boolean") ) { result = newError("asynchronous"); } if (!result && rule.asynchronous && synchronous) { result = new Error( "Custom rule " + rule.names.join("/") + " at index " + customIndex + " is asynchronous and can not be used in a synchronous context." ); } if (!result) { for (const name of rule.names) { const nameUpper = name.toUpperCase(); if (!result && (allIds[nameUpper] !== undefined)) { result = new Error("Name '" + name + "' of custom rule at index " + customIndex + " is already used as a name or tag."); } allIds[nameUpper] = true; } for (const tag of rule.tags) { const tagUpper = tag.toUpperCase(); if (!result && allIds[tagUpper]) { result = new Error("Tag '" + tag + "' of custom rule at index " + customIndex + " is already used as a name."); } allIds[tagUpper] = false; } } } return result; } /** * Creates a LintResults instance with toString for pretty display. * * @param {Rule[]} ruleList List of rules. * @returns {LintResults} New LintResults instance. */ function newResults(ruleList) { const lintResults = {}; // eslint-disable-next-line jsdoc/require-jsdoc function toString(useAlias) { let ruleNameToRule = null; const results = []; const keys = Object.keys(lintResults); keys.sort(); for (const file of keys) { const fileResults = lintResults[file]; if (Array.isArray(fileResults)) { for (const result of fileResults) { const ruleMoniker = result.ruleNames ? result.ruleNames.join("/") : (result.ruleName + "/" + result.ruleAlias); results.push( file + ": " + result.lineNumber + ": " + ruleMoniker + " " + result.ruleDescription + (result.errorDetail ? " [" + result.errorDetail + "]" : "") + (result.errorContext ? " [Context: \"" + result.errorContext + "\"]" : "")); } } else { if (!ruleNameToRule) { ruleNameToRule = {}; for (const rule of ruleList) { const ruleName = rule.names[0].toUpperCase(); ruleNameToRule[ruleName] = rule; } } for (const [ ruleName, ruleResults ] of Object.entries(fileResults)) { const rule = ruleNameToRule[ruleName.toUpperCase()]; for (const lineNumber of ruleResults) { // @ts-ignore const nameIndex = Math.min(useAlias ? 1 : 0, rule.names.length - 1); const result = file + ": " + lineNumber + ": " + // @ts-ignore rule.names[nameIndex] + " " + // @ts-ignore rule.description; results.push(result); } } } } return results.join("\n"); } Object.defineProperty(lintResults, "toString", { "value": toString }); // @ts-ignore return lintResults; } /** * Remove front matter (if present at beginning of content). * * @param {string} content Markdown content. * @param {RegExp} frontMatter Regular expression to match front matter. * @returns {Object} Trimmed content and front matter lines. */ function removeFrontMatter(content, frontMatter) { let frontMatterLines = []; if (frontMatter) { const frontMatterMatch = content.match(frontMatter); if (frontMatterMatch && !frontMatterMatch.index) { const contentMatched = frontMatterMatch[0]; content = content.slice(contentMatched.length); frontMatterLines = contentMatched.split(helpers.newLineRe); if ((frontMatterLines.length > 0) && (frontMatterLines[frontMatterLines.length - 1] === "")) { frontMatterLines.length--; } } } return { "content": content, "frontMatterLines": frontMatterLines }; } /** * Freeze all freeze-able members of a token and its children. * * @param {MarkdownItToken} token A markdown-it token. * @returns {void} */ function freezeToken(token) { if (token.attrs) { for (const attr of token.attrs) { Object.freeze(attr); } Object.freeze(token.attrs); } if (token.children) { for (const child of token.children) { freezeToken(child); } Object.freeze(token.children); } if (token.map) { Object.freeze(token.map); } Object.freeze(token); } /** * Annotate tokens with line/lineNumber and freeze them. * * @param {MarkdownItToken[]} tokens Array of markdown-it tokens. * @param {string[]} lines Lines of Markdown content. * @returns {void} */ function annotateAndFreezeTokens(tokens, lines) { let trMap = null; for (const token of tokens) { // Provide missing maps for table content if (token.type === "tr_open") { trMap = token.map; } else if (token.type === "tr_close") { trMap = null; } if (!token.map && trMap) { token.map = [ ...trMap ]; } // Update token metadata if (token.map) { token.line = lines[token.map[0]]; token.lineNumber = token.map[0] + 1; // Trim bottom of token to exclude whitespace lines while (token.map[1] && !((lines[token.map[1] - 1] || "").trim())) { token.map[1]--; } } // Annotate children with lineNumber if (token.children) { const codeSpanExtraLines = []; if (token.children.some((child) => child.type === "code_inline")) { helpers.forEachInlineCodeSpan(token.content, (code) => { codeSpanExtraLines.push(code.split(helpers.newLineRe).length - 1); }); } let lineNumber = token.lineNumber; for (const child of token.children) { child.lineNumber = lineNumber; child.line = lines[lineNumber - 1]; if ((child.type === "softbreak") || (child.type === "hardbreak")) { lineNumber++; } else if (child.type === "code_inline") { lineNumber += codeSpanExtraLines.shift(); } } } freezeToken(token); } Object.freeze(tokens); } /** * Map rule names/tags to canonical rule name. * * @param {Rule[]} ruleList List of rules. * @returns {Object.} Map of alias to rule name. */ function mapAliasToRuleNames(ruleList) { const aliasToRuleNames = {}; // const tagToRuleNames = {}; for (const rule of ruleList) { const ruleName = rule.names[0].toUpperCase(); // The following is useful for updating README.md: // console.log( // "* **[" + ruleName + "](doc/Rules.md#" + ruleName.toLowerCase() + // ")** *" + rule.names.slice(1).join("/") + "* - " + rule.description); for (const name of rule.names) { const nameUpper = name.toUpperCase(); aliasToRuleNames[nameUpper] = [ ruleName ]; } for (const tag of rule.tags) { const tagUpper = tag.toUpperCase(); const ruleNames = aliasToRuleNames[tagUpper] || []; ruleNames.push(ruleName); aliasToRuleNames[tagUpper] = ruleNames; // tagToRuleNames[tag] = ruleName; } } // The following is useful for updating README.md: // Object.keys(tagToRuleNames).sort().forEach(function forTag(tag) { // console.log("* **" + tag + "** - " + // aliasToRuleNames[tag.toUpperCase()].join(", ")); // }); // @ts-ignore return aliasToRuleNames; } /** * Apply (and normalize) configuration object. * * @param {Rule[]} ruleList List of rules. * @param {Configuration} config Configuration object. * @param {Object.} aliasToRuleNames Map of alias to rule * names. * @returns {Configuration} Effective configuration. */ function getEffectiveConfig(ruleList, config, aliasToRuleNames) { const defaultKey = Object.keys(config).filter( (key) => key.toUpperCase() === "DEFAULT" ); const ruleDefault = (defaultKey.length === 0) || !!config[defaultKey[0]]; const effectiveConfig = {}; for (const rule of ruleList) { const ruleName = rule.names[0].toUpperCase(); effectiveConfig[ruleName] = ruleDefault; } for (const ruleName of deprecatedRuleNames) { effectiveConfig[ruleName] = false; } for (const key of Object.keys(config)) { let value = config[key]; if (value) { if (!(value instanceof Object)) { value = {}; } } else { value = false; } const keyUpper = key.toUpperCase(); for (const ruleName of (aliasToRuleNames[keyUpper] || [])) { effectiveConfig[ruleName] = value; } } return effectiveConfig; } /** * Parse the content of a configuration file. * * @param {string} name Name of the configuration file. * @param {string} content Configuration content. * @param {ConfigurationParser[] | null} [parsers] Parsing function(s). * @returns {Object} Configuration object and error message. */ function parseConfiguration(name, content, parsers) { let config = null; let message = ""; const errors = []; let index = 0; // Try each parser (parsers || [ JSON.parse ]).every((parser) => { try { config = parser(content); } catch (error) { errors.push(`Parser ${index++}: ${error.message}`); } return !config; }); // Message if unable to parse if (!config) { errors.unshift(`Unable to parse '${name}'`); message = errors.join("; "); } return { config, message }; } /** * Create a mapping of enabled rules per line. * * @param {Rule[]} ruleList List of rules. * @param {string[]} lines List of content lines. * @param {string[]} frontMatterLines List of front matter lines. * @param {boolean} noInlineConfig Whether to allow inline configuration. * @param {Configuration} config Configuration object. * @param {ConfigurationParser[] | null} configParsers Configuration parsers. * @param {Object.} aliasToRuleNames Map of alias to rule * names. * @returns {Object} Effective configuration and enabled rules per line number. */ function getEnabledRulesPerLineNumber( ruleList, lines, frontMatterLines, noInlineConfig, config, configParsers, aliasToRuleNames) { // Shared variables let enabledRules = {}; let capturedRules = {}; const allRuleNames = []; const enabledRulesPerLineNumber = new Array(1 + frontMatterLines.length); // Helper functions // eslint-disable-next-line jsdoc/require-jsdoc function handleInlineConfig(input, forEachMatch, forEachLine) { for (const [ lineIndex, line ] of input.entries()) { if (!noInlineConfig) { let match = null; while ((match = helpers.inlineCommentStartRe.exec(line))) { const action = match[2].toUpperCase(); const startIndex = match.index + match[1].length; const endIndex = line.indexOf("-->", startIndex); if (endIndex === -1) { break; } const parameter = line.slice(startIndex, endIndex); forEachMatch(action, parameter, lineIndex + 1); } } if (forEachLine) { forEachLine(); } } } // eslint-disable-next-line jsdoc/require-jsdoc function configureFile(action, parameter) { if (action === "CONFIGURE-FILE") { const { "config": parsed } = parseConfiguration( "CONFIGURE-FILE", parameter, configParsers ); if (parsed) { config = { ...config, ...parsed }; } } } // eslint-disable-next-line jsdoc/require-jsdoc function applyEnableDisable(action, parameter, state) { state = { ...state }; const enabled = (action.startsWith("ENABLE")); const trimmed = parameter && parameter.trim(); const items = trimmed ? trimmed.toUpperCase().split(/\s+/) : allRuleNames; for (const nameUpper of items) { for (const ruleName of (aliasToRuleNames[nameUpper] || [])) { state[ruleName] = enabled; } } return state; } // eslint-disable-next-line jsdoc/require-jsdoc function enableDisableFile(action, parameter) { if ((action === "ENABLE-FILE") || (action === "DISABLE-FILE")) { enabledRules = applyEnableDisable(action, parameter, enabledRules); } } // eslint-disable-next-line jsdoc/require-jsdoc function captureRestoreEnableDisable(action, parameter) { if (action === "CAPTURE") { capturedRules = enabledRules; } else if (action === "RESTORE") { enabledRules = capturedRules; } else if ((action === "ENABLE") || (action === "DISABLE")) { enabledRules = applyEnableDisable(action, parameter, enabledRules); } } // eslint-disable-next-line jsdoc/require-jsdoc function updateLineState() { enabledRulesPerLineNumber.push(enabledRules); } // eslint-disable-next-line jsdoc/require-jsdoc function disableLineNextLine(action, parameter, lineNumber) { const disableLine = (action === "DISABLE-LINE"); const disableNextLine = (action === "DISABLE-NEXT-LINE"); if (disableLine || disableNextLine) { const nextLineNumber = frontMatterLines.length + lineNumber + (disableNextLine ? 1 : 0); enabledRulesPerLineNumber[nextLineNumber] = applyEnableDisable( action, parameter, enabledRulesPerLineNumber[nextLineNumber] || {} ); } } // Handle inline comments handleInlineConfig([ lines.join("\n") ], configureFile); const effectiveConfig = getEffectiveConfig( ruleList, config, aliasToRuleNames); for (const rule of ruleList) { const ruleName = rule.names[0].toUpperCase(); allRuleNames.push(ruleName); enabledRules[ruleName] = !!effectiveConfig[ruleName]; } capturedRules = enabledRules; handleInlineConfig(lines, enableDisableFile); handleInlineConfig(lines, captureRestoreEnableDisable, updateLineState); handleInlineConfig(lines, disableLineNextLine); // Return results return { effectiveConfig, enabledRulesPerLineNumber }; } /** * Lints a string containing Markdown content. * * @param {Rule[]} ruleList List of rules. * @param {string} name Identifier for the content. * @param {string} content Markdown content. * @param {Object} md Instance of markdown-it. * @param {Configuration} config Configuration object. * @param {ConfigurationParser[] | null} configParsers Configuration parsers. * @param {RegExp} frontMatter Regular expression for front matter. * @param {boolean} handleRuleFailures Whether to handle exceptions in rules. * @param {boolean} noInlineConfig Whether to allow inline configuration. * @param {number} resultVersion Version of the LintResults object to return. * @param {Function} callback Callback (err, result) function. * @returns {void} */ function lintContent( ruleList, name, content, md, config, configParsers, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, callback) { // Remove UTF-8 byte order marker (if present) content = content.replace(/^\uFEFF/, ""); // Remove front matter const removeFrontMatterResult = removeFrontMatter(content, frontMatter); const { frontMatterLines } = removeFrontMatterResult; content = removeFrontMatterResult.content; // Get enabled rules per line (with HTML comments present) const { effectiveConfig, enabledRulesPerLineNumber } = getEnabledRulesPerLineNumber( ruleList, content.split(helpers.newLineRe), frontMatterLines, noInlineConfig, config, configParsers, mapAliasToRuleNames(ruleList) ); // Hide the content of HTML comments from rules, etc. content = helpers.clearHtmlCommentText(content); // Parse content into tokens and lines const tokens = md.parse(content, {}); const lines = content.split(helpers.newLineRe); annotateAndFreezeTokens(tokens, lines); // Create (frozen) parameters for rules const paramsBase = { name, tokens, "lines": Object.freeze(lines), "frontMatterLines": Object.freeze(frontMatterLines) }; const lineMetadata = helpers.getLineMetadata(paramsBase); const codeBlockAndSpanRanges = helpers.codeBlockAndSpanRanges(paramsBase, lineMetadata); const flattenedLists = helpers.flattenLists(paramsBase.tokens); const htmlElementRanges = helpers.htmlElementRanges(paramsBase, lineMetadata); const referenceLinkImageData = helpers.getReferenceLinkImageData(lineMetadata); cache.set({ codeBlockAndSpanRanges, flattenedLists, htmlElementRanges, lineMetadata, referenceLinkImageData }); // Function to run for each rule let results = []; // eslint-disable-next-line jsdoc/require-jsdoc function forRule(rule) { // Configure rule const ruleName = rule.names[0].toUpperCase(); const params = { ...paramsBase, "config": effectiveConfig[ruleName] }; // eslint-disable-next-line jsdoc/require-jsdoc function throwError(property) { throw new Error( "Property '" + property + "' of onError parameter is incorrect."); } // eslint-disable-next-line jsdoc/require-jsdoc function onError(errorInfo) { if (!errorInfo || !helpers.isNumber(errorInfo.lineNumber) || (errorInfo.lineNumber < 1) || (errorInfo.lineNumber > lines.length)) { throwError("lineNumber"); } const lineNumber = errorInfo.lineNumber + frontMatterLines.length; if (!enabledRulesPerLineNumber[lineNumber][ruleName]) { return; } if (errorInfo.detail && !helpers.isString(errorInfo.detail)) { throwError("detail"); } if (errorInfo.context && !helpers.isString(errorInfo.context)) { throwError("context"); } if (errorInfo.range && (!Array.isArray(errorInfo.range) || (errorInfo.range.length !== 2) || !helpers.isNumber(errorInfo.range[0]) || (errorInfo.range[0] < 1) || !helpers.isNumber(errorInfo.range[1]) || (errorInfo.range[1] < 1) || ((errorInfo.range[0] + errorInfo.range[1] - 1) > lines[errorInfo.lineNumber - 1].length))) { throwError("range"); } const fixInfo = errorInfo.fixInfo; const cleanFixInfo = {}; if (fixInfo) { if (!helpers.isObject(fixInfo)) { throwError("fixInfo"); } if (fixInfo.lineNumber !== undefined) { if ((!helpers.isNumber(fixInfo.lineNumber) || (fixInfo.lineNumber < 1) || (fixInfo.lineNumber > lines.length))) { throwError("fixInfo.lineNumber"); } cleanFixInfo.lineNumber = fixInfo.lineNumber + frontMatterLines.length; } const effectiveLineNumber = fixInfo.lineNumber || errorInfo.lineNumber; if (fixInfo.editColumn !== undefined) { if ((!helpers.isNumber(fixInfo.editColumn) || (fixInfo.editColumn < 1) || (fixInfo.editColumn > lines[effectiveLineNumber - 1].length + 1))) { throwError("fixInfo.editColumn"); } cleanFixInfo.editColumn = fixInfo.editColumn; } if (fixInfo.deleteCount !== undefined) { if ((!helpers.isNumber(fixInfo.deleteCount) || (fixInfo.deleteCount < -1) || (fixInfo.deleteCount > lines[effectiveLineNumber - 1].length))) { throwError("fixInfo.deleteCount"); } cleanFixInfo.deleteCount = fixInfo.deleteCount; } if (fixInfo.insertText !== undefined) { if (!helpers.isString(fixInfo.insertText)) { throwError("fixInfo.insertText"); } cleanFixInfo.insertText = fixInfo.insertText; } } results.push({ lineNumber, "ruleName": rule.names[0], "ruleNames": rule.names, "ruleDescription": rule.description, "ruleInformation": rule.information ? rule.information.href : null, "errorDetail": errorInfo.detail || null, "errorContext": errorInfo.context || null, "errorRange": errorInfo.range ? [ ...errorInfo.range ] : null, "fixInfo": fixInfo ? cleanFixInfo : null }); } // Call (possibly external) rule function to report errors const catchCallsOnError = (error) => onError({ "lineNumber": 1, "detail": `This rule threw an exception: ${error.message || error}` }); const invokeRuleFunction = () => rule.function(params, onError); if (rule.asynchronous) { // Asynchronous rule, ensure it returns a Promise const ruleFunctionPromise = Promise.resolve().then(invokeRuleFunction); return handleRuleFailures ? ruleFunctionPromise.catch(catchCallsOnError) : ruleFunctionPromise; } // Synchronous rule try { invokeRuleFunction(); } catch (error) { if (handleRuleFailures) { catchCallsOnError(error); } else { throw error; } } return null; } // eslint-disable-next-line jsdoc/require-jsdoc function formatResults() { // Sort results by rule name by line number results.sort((a, b) => ( a.ruleName.localeCompare(b.ruleName) || a.lineNumber - b.lineNumber )); if (resultVersion < 3) { // Remove fixInfo and multiple errors for the same rule and line number const noPrevious = { "ruleName": null, "lineNumber": -1 }; results = results.filter((error, index, array) => { delete error.fixInfo; const previous = array[index - 1] || noPrevious; return ( (error.ruleName !== previous.ruleName) || (error.lineNumber !== previous.lineNumber) ); }); } if (resultVersion === 0) { // Return a dictionary of rule->[line numbers] const dictionary = {}; for (const error of results) { const ruleLines = dictionary[error.ruleName] || []; ruleLines.push(error.lineNumber); dictionary[error.ruleName] = ruleLines; } // @ts-ignore results = dictionary; } else if (resultVersion === 1) { // Use ruleAlias instead of ruleNames for (const error of results) { error.ruleAlias = error.ruleNames[1] || error.ruleName; delete error.ruleNames; } } else { // resultVersion 2 or 3: Remove unwanted ruleName for (const error of results) { delete error.ruleName; } } return results; } // Run all rules const ruleListAsync = ruleList.filter((rule) => rule.asynchronous); const ruleListSync = ruleList.filter((rule) => !rule.asynchronous); const ruleListAsyncFirst = [ ...ruleListAsync, ...ruleListSync ]; const callbackSuccess = () => callback(null, formatResults()); const callbackError = (error) => callback(error instanceof Error ? error : new Error(error)); try { const ruleResults = ruleListAsyncFirst.map(forRule); if (ruleListAsync.length > 0) { Promise.all(ruleResults.slice(0, ruleListAsync.length)) .then(callbackSuccess) .catch(callbackError); } else { callbackSuccess(); } } catch (error) { callbackError(error); } finally { cache.clear(); } } /** * Lints a file containing Markdown content. * * @param {Rule[]} ruleList List of rules. * @param {string} file Path of file to lint. * @param {Object} md Instance of markdown-it. * @param {Configuration} config Configuration object. * @param {ConfigurationParser[] | null} configParsers Configuration parsers. * @param {RegExp} frontMatter Regular expression for front matter. * @param {boolean} handleRuleFailures Whether to handle exceptions in rules. * @param {boolean} noInlineConfig Whether to allow inline configuration. * @param {number} resultVersion Version of the LintResults object to return. * @param {Object} fs File system implementation. * @param {boolean} synchronous Whether to execute synchronously. * @param {Function} callback Callback (err, result) function. * @returns {void} */ function lintFile( ruleList, file, md, config, configParsers, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, fs, synchronous, callback) { // eslint-disable-next-line jsdoc/require-jsdoc function lintContentWrapper(err, content) { if (err) { return callback(err); } return lintContent( ruleList, file, content, md, config, configParsers, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, callback ); } // Make a/synchronous call to read file if (synchronous) { lintContentWrapper(null, fs.readFileSync(file, "utf8")); } else { fs.readFile(file, "utf8", lintContentWrapper); } } /** * Lint files and strings specified in the Options object. * * @param {Options} options Options object. * @param {boolean} synchronous Whether to execute synchronously. * @param {Function} callback Callback (err, result) function. * @returns {void} */ function lintInput(options, synchronous, callback) { // Normalize inputs options = options || {}; callback = callback || function noop() {}; // eslint-disable-next-line unicorn/prefer-spread const ruleList = rules.concat(options.customRules || []); const ruleErr = validateRuleList(ruleList, synchronous); if (ruleErr) { callback(ruleErr); return; } let files = []; if (Array.isArray(options.files)) { files = [ ...options.files ]; } else if (options.files) { files = [ String(options.files) ]; } const strings = options.strings || {}; const stringsKeys = Object.keys(strings); const config = options.config || { "default": true }; const configParsers = options.configParsers || null; const frontMatter = (options.frontMatter === undefined) ? helpers.frontMatterRe : options.frontMatter; const handleRuleFailures = !!options.handleRuleFailures; const noInlineConfig = !!options.noInlineConfig; const resultVersion = (options.resultVersion === undefined) ? 3 : options.resultVersion; const md = markdownIt({ "html": true }); const markdownItPlugins = options.markdownItPlugins || []; for (const plugin of markdownItPlugins) { // @ts-ignore md.use(...plugin); } const fs = options.fs || __nccwpck_require__(7147); const results = newResults(ruleList); let done = false; let concurrency = 0; // eslint-disable-next-line jsdoc/require-jsdoc function lintWorker() { let currentItem = null; // eslint-disable-next-line jsdoc/require-jsdoc function lintWorkerCallback(err, result) { concurrency--; if (err) { done = true; return callback(err); } results[currentItem] = result; if (!synchronous) { lintWorker(); } return null; } if (done) { // Abort for error or nothing left to do } else if (files.length > 0) { // Lint next file concurrency++; currentItem = files.shift(); lintFile( ruleList, currentItem, md, config, configParsers, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, fs, synchronous, lintWorkerCallback ); } else if ((currentItem = stringsKeys.shift())) { // Lint next string concurrency++; lintContent( ruleList, currentItem, strings[currentItem] || "", md, config, configParsers, frontMatter, handleRuleFailures, noInlineConfig, resultVersion, lintWorkerCallback ); } else if (concurrency === 0) { // Finish done = true; return callback(null, results); } return null; } if (synchronous) { while (!done) { lintWorker(); } } else { // Testing on a Raspberry Pi 4 Model B with an artificial 5ms file access // delay suggests that a concurrency factor of 8 can eliminate the impact // of that delay (i.e., total time is the same as with no delay). lintWorker(); lintWorker(); lintWorker(); lintWorker(); lintWorker(); lintWorker(); lintWorker(); lintWorker(); } } /** * Lint specified Markdown files. * * @param {Options} options Configuration options. * @param {LintCallback} callback Callback (err, result) function. * @returns {void} */ function markdownlint(options, callback) { return lintInput(options, false, callback); } const markdownlintPromisify = promisify && promisify(markdownlint); /** * Lint specified Markdown files. * * @param {Options} options Configuration options. * @returns {Promise} Results object. */ function markdownlintPromise(options) { // @ts-ignore return markdownlintPromisify(options); } /** * Lint specified Markdown files synchronously. * * @param {Options} options Configuration options. * @returns {LintResults} Results object. */ function markdownlintSync(options) { let results = {}; lintInput(options, true, function callback(error, res) { if (error) { throw error; } results = res; }); // @ts-ignore return results; } /** * Resolve referenced "extends" path in a configuration file * using path.resolve() with require.resolve() as a fallback. * * @param {string} configFile Configuration file name. * @param {string} referenceId Referenced identifier to resolve. * @param {Object} fs File system implementation. * @param {ResolveConfigExtendsCallback} callback Callback (err, result) * function. * @returns {void} */ function resolveConfigExtends(configFile, referenceId, fs, callback) { const configFileDirname = path.dirname(configFile); const resolvedExtendsFile = path.resolve(configFileDirname, referenceId); fs.access(resolvedExtendsFile, (err) => { if (err) { // Not a file, try require.resolve try { return callback(null, dynamicRequire.resolve( referenceId, { "paths": [ configFileDirname ] } )); } catch { // Unable to resolve, use resolvedExtendsFile } } return callback(null, resolvedExtendsFile); }); } /** * Resolve referenced "extends" path in a configuration file * using path.resolve() with require.resolve() as a fallback. * * @param {string} configFile Configuration file name. * @param {string} referenceId Referenced identifier to resolve. * @param {Object} fs File system implementation. * @returns {string} Resolved path to file. */ function resolveConfigExtendsSync(configFile, referenceId, fs) { const configFileDirname = path.dirname(configFile); const resolvedExtendsFile = path.resolve(configFileDirname, referenceId); try { fs.accessSync(resolvedExtendsFile); return resolvedExtendsFile; } catch { // Not a file, try require.resolve } try { return dynamicRequire.resolve( referenceId, { "paths": [ configFileDirname ] } ); } catch { // Unable to resolve, return resolvedExtendsFile } return resolvedExtendsFile; } /** * Read specified configuration file. * * @param {string} file Configuration file name. * @param {ConfigurationParser[] | ReadConfigCallback} parsers Parsing * function(s). * @param {Object} [fs] File system implementation. * @param {ReadConfigCallback} [callback] Callback (err, result) function. * @returns {void} */ function readConfig(file, parsers, fs, callback) { if (!callback) { if (fs) { callback = fs; fs = null; } else { // @ts-ignore callback = parsers; // @ts-ignore parsers = null; } } if (!fs) { fs = __nccwpck_require__(7147); } // Read file const os = __nccwpck_require__(2037); file = helpers.expandTildePath(file, os); fs.readFile(file, "utf8", (err, content) => { if (err) { // @ts-ignore return callback(err); } // Try to parse file // @ts-ignore const { config, message } = parseConfiguration(file, content, parsers); if (!config) { // @ts-ignore return callback(new Error(message)); } // Extend configuration const configExtends = config.extends; if (configExtends) { delete config.extends; return resolveConfigExtends( file, helpers.expandTildePath(configExtends, os), fs, (_, resolvedExtends) => readConfig( // @ts-ignore resolvedExtends, parsers, fs, (errr, extendsConfig) => { if (errr) { // @ts-ignore return callback(errr); } // @ts-ignore return callback(null, { ...extendsConfig, ...config }); } ) ); } // @ts-ignore return callback(null, config); }); } const readConfigPromisify = promisify && promisify(readConfig); /** * Read specified configuration file. * * @param {string} file Configuration file name. * @param {ConfigurationParser[]} [parsers] Parsing function(s). * @param {Object} [fs] File system implementation. * @returns {Promise} Configuration object. */ function readConfigPromise(file, parsers, fs) { // @ts-ignore return readConfigPromisify(file, parsers, fs); } /** * Read specified configuration file synchronously. * * @param {string} file Configuration file name. * @param {ConfigurationParser[]} [parsers] Parsing function(s). * @param {Object} [fs] File system implementation. * @returns {Configuration} Configuration object. * @throws An Error if processing fails. */ function readConfigSync(file, parsers, fs) { if (!fs) { fs = __nccwpck_require__(7147); } // Read file const os = __nccwpck_require__(2037); file = helpers.expandTildePath(file, os); const content = fs.readFileSync(file, "utf8"); // Try to parse file const { config, message } = parseConfiguration(file, content, parsers); if (!config) { throw new Error(message); } // Extend configuration const configExtends = config.extends; if (configExtends) { delete config.extends; const resolvedExtends = resolveConfigExtendsSync( file, helpers.expandTildePath(configExtends, os), fs ); return { ...readConfigSync(resolvedExtends, parsers, fs), ...config }; } return config; } /** * Gets the (semantic) version of the library. * * @returns {string} SemVer string. */ function getVersion() { return (__nccwpck_require__(983).version); } // Export a/synchronous/Promise APIs markdownlint.sync = markdownlintSync; markdownlint.readConfig = readConfig; markdownlint.readConfigSync = readConfigSync; markdownlint.getVersion = getVersion; markdownlint.promises = { "markdownlint": markdownlintPromise, "readConfig": readConfigPromise }; module.exports = markdownlint; // Type declarations /** * Function to implement rule logic. * * @callback RuleFunction * @param {RuleParams} params Rule parameters. * @param {RuleOnError} onError Error-reporting callback. * @returns {void} */ /** * Rule parameters. * * @typedef {Object} RuleParams * @property {string} name File/string name. * @property {MarkdownItToken[]} tokens Token objects from markdown-it. * @property {string[]} lines File/string lines. * @property {string[]} frontMatterLines Front matter lines. * @property {RuleConfiguration} config Rule configuration. */ /** * Markdown-It token. * * @typedef {Object} MarkdownItToken * @property {string[][]} attrs HTML attributes. * @property {boolean} block Block-level token. * @property {MarkdownItToken[]} children Child nodes. * @property {string} content Tag contents. * @property {boolean} hidden Ignore element. * @property {string} info Fence info. * @property {number} level Nesting level. * @property {number[]} map Beginning/ending line numbers. * @property {string} markup Markup text. * @property {Object} meta Arbitrary data. * @property {number} nesting Level change. * @property {string} tag HTML tag name. * @property {string} type Token type. * @property {number} lineNumber Line number (1-based). * @property {string} line Line content. */ /** * Error-reporting callback. * * @callback RuleOnError * @param {RuleOnErrorInfo} onErrorInfo Error information. * @returns {void} */ /** * Fix information for RuleOnError callback. * * @typedef {Object} RuleOnErrorInfo * @property {number} lineNumber Line number (1-based). * @property {string} [detail] Detail about the error. * @property {string} [context] Context for the error. * @property {number[]} [range] Column number (1-based) and length. * @property {RuleOnErrorFixInfo} [fixInfo] Fix information. */ /** * Fix information for RuleOnErrorInfo. * * @typedef {Object} RuleOnErrorFixInfo * @property {number} [lineNumber] Line number (1-based). * @property {number} [editColumn] Column of the fix (1-based). * @property {number} [deleteCount] Count of characters to delete. * @property {string} [insertText] Text to insert (after deleting). */ /** * Rule definition. * * @typedef {Object} Rule * @property {string[]} names Rule name(s). * @property {string} description Rule description. * @property {URL} [information] Link to more information. * @property {string[]} tags Rule tag(s). * @property {boolean} [asynchronous] True if asynchronous. * @property {RuleFunction} function Rule implementation. */ /** * Configuration options. * * @typedef {Object} Options * @property {Configuration} [config] Configuration object. * @property {ConfigurationParser[]} [configParsers] Configuration parsers. * @property {Rule[] | Rule} [customRules] Custom rules. * @property {string[] | string} [files] Files to lint. * @property {RegExp} [frontMatter] Front matter pattern. * @property {Object} [fs] File system implementation. * @property {boolean} [handleRuleFailures] True to catch exceptions. * @property {Plugin[]} [markdownItPlugins] Additional plugins. * @property {boolean} [noInlineConfig] True to ignore HTML directives. * @property {number} [resultVersion] Results object version. * @property {Object.} [strings] Strings to lint. */ /** * A markdown-it plugin. * * @typedef {Array} Plugin */ /** * Function to pretty-print lint results. * * @callback ToStringCallback * @param {boolean} [ruleAliases] True to use rule aliases. * @returns {string} */ /** * Lint results (for resultVersion 3). * * @typedef {Object.} LintResults * @property {ToStringCallback} toString String representation. */ /** * Lint error. * * @typedef {Object} LintError * @property {number} lineNumber Line number (1-based). * @property {string[]} ruleNames Rule name(s). * @property {string} ruleDescription Rule description. * @property {string} ruleInformation Link to more information. * @property {string} errorDetail Detail about the error. * @property {string} errorContext Context for the error. * @property {number[]} errorRange Column number (1-based) and length. * @property {FixInfo} [fixInfo] Fix information. */ /** * Fix information. * * @typedef {Object} FixInfo * @property {number} [lineNumber] Line number (1-based). * @property {number} [editColumn] Column of the fix (1-based). * @property {number} [deleteCount] Count of characters to delete. * @property {string} [insertText] Text to insert (after deleting). */ /** * Called with the result of the lint function. * * @callback LintCallback * @param {Error | null} err Error object or null. * @param {LintResults} [results] Lint results. * @returns {void} */ /** * Configuration object for linting rules. For a detailed schema, see * {@link ../schema/markdownlint-config-schema.json}. * * @typedef {Object.} Configuration */ /** * Rule configuration object. * * @typedef {boolean | Object} RuleConfiguration Rule configuration. */ /** * Parses a configuration string and returns a configuration object. * * @callback ConfigurationParser * @param {string} text Configuration string. * @returns {Configuration} */ /** * Called with the result of the readConfig function. * * @callback ReadConfigCallback * @param {Error | null} err Error object or null. * @param {Configuration} [config] Configuration object. * @returns {void} */ /** * Called with the result of the resolveConfigExtends function. * * @callback ResolveConfigExtendsCallback * @param {Error | null} err Error object or null. * @param {string} [path] Resolved path to file. * @returns {void} */ /***/ }), /***/ 9651: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, filterTokens } = __nccwpck_require__(2935); module.exports = { "names": [ "MD001", "heading-increment", "header-increment" ], "description": "Heading levels should only increment by one level at a time", "tags": [ "headings", "headers" ], "function": function MD001(params, onError) { let prevLevel = 0; filterTokens(params, "heading_open", function forToken(token) { const level = Number.parseInt(token.tag.slice(1), 10); if (prevLevel && (level > prevLevel)) { addErrorDetailIf(onError, token.lineNumber, "h" + (prevLevel + 1), "h" + level); } prevLevel = level; }); } }; /***/ }), /***/ 4545: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf } = __nccwpck_require__(2935); module.exports = { "names": [ "MD002", "first-heading-h1", "first-header-h1" ], "description": "First heading should be a top-level heading", "tags": [ "headings", "headers" ], "function": function MD002(params, onError) { const level = Number(params.config.level || 1); const tag = "h" + level; params.tokens.every(function forToken(token) { if (token.type === "heading_open") { addErrorDetailIf(onError, token.lineNumber, tag, token.tag); return false; } return true; }); } }; /***/ }), /***/ 9277: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, filterTokens, headingStyleFor } = __nccwpck_require__(2935); module.exports = { "names": [ "MD003", "heading-style", "header-style" ], "description": "Heading style", "tags": [ "headings", "headers" ], "function": function MD003(params, onError) { let style = String(params.config.style || "consistent"); filterTokens(params, "heading_open", function forToken(token) { const styleForToken = headingStyleFor(token); if (style === "consistent") { style = styleForToken; } if (styleForToken !== style) { const h12 = /h[12]/.test(token.tag); const setextWithAtx = (style === "setext_with_atx") && ((h12 && (styleForToken === "setext")) || (!h12 && (styleForToken === "atx"))); const setextWithAtxClosed = (style === "setext_with_atx_closed") && ((h12 && (styleForToken === "setext")) || (!h12 && (styleForToken === "atx_closed"))); if (!setextWithAtx && !setextWithAtxClosed) { let expected = style; if (style === "setext_with_atx") { expected = h12 ? "setext" : "atx"; } else if (style === "setext_with_atx_closed") { expected = h12 ? "setext" : "atx_closed"; } addErrorDetailIf(onError, token.lineNumber, expected, styleForToken); } } }); } }; /***/ }), /***/ 3755: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, listItemMarkerRe, unorderedListStyleFor } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); const expectedStyleToMarker = { "dash": "-", "plus": "+", "asterisk": "*" }; const differentItemStyle = { "dash": "plus", "plus": "asterisk", "asterisk": "dash" }; const validStyles = Object.keys(expectedStyleToMarker); module.exports = { "names": [ "MD004", "ul-style" ], "description": "Unordered list style", "tags": [ "bullet", "ul" ], "function": function MD004(params, onError) { const style = String(params.config.style || "consistent"); let expectedStyle = style; const nestingStyles = []; for (const list of flattenedLists()) { if (list.unordered) { if (expectedStyle === "consistent") { expectedStyle = unorderedListStyleFor(list.items[0]); } for (const item of list.items) { const itemStyle = unorderedListStyleFor(item); if (style === "sublist") { const nesting = list.nesting; if (!nestingStyles[nesting]) { nestingStyles[nesting] = (itemStyle === nestingStyles[nesting - 1]) ? differentItemStyle[itemStyle] : itemStyle; } expectedStyle = nestingStyles[nesting]; } if (!validStyles.includes(expectedStyle)) { expectedStyle = validStyles[0]; } let range = null; let fixInfo = null; const match = item.line.match(listItemMarkerRe); if (match) { const column = match.index + 1; const length = match[0].length; range = [ column, length ]; fixInfo = { "editColumn": match[1].length + 1, "deleteCount": 1, "insertText": expectedStyleToMarker[expectedStyle] }; } addErrorDetailIf( onError, item.lineNumber, expectedStyle, itemStyle, null, null, range, fixInfo ); } } } } }; /***/ }), /***/ 3354: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError, addErrorDetailIf, indentFor, listItemMarkerRe, orderedListItemMarkerRe, rangeFromRegExp } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); module.exports = { "names": [ "MD005", "list-indent" ], "description": "Inconsistent indentation for list items at the same level", "tags": [ "bullet", "ul", "indentation" ], "function": function MD005(params, onError) { for (const list of flattenedLists()) { const expectedIndent = list.indent; let expectedEnd = 0; let actualEnd = -1; let endMatching = false; for (const item of list.items) { const { line, lineNumber } = item; const actualIndent = indentFor(item); let match = null; if (list.unordered) { addErrorDetailIf( onError, lineNumber, expectedIndent, actualIndent, null, null, rangeFromRegExp(line, listItemMarkerRe) // No fixInfo; MD007 handles this scenario better ); } else if ((match = orderedListItemMarkerRe.exec(line))) { actualEnd = match[0].length; expectedEnd = expectedEnd || actualEnd; const markerLength = match[1].length + 1; if ((expectedIndent !== actualIndent) || endMatching) { if (expectedEnd === actualEnd) { endMatching = true; } else { const detail = endMatching ? `Expected: (${expectedEnd}); Actual: (${actualEnd})` : `Expected: ${expectedIndent}; Actual: ${actualIndent}`; const expected = endMatching ? expectedEnd - markerLength : expectedIndent; const actual = endMatching ? actualEnd - markerLength : actualIndent; addError( onError, lineNumber, detail, null, rangeFromRegExp(line, listItemMarkerRe), { "editColumn": Math.min(actual, expected) + 1, "deleteCount": Math.max(actual - expected, 0), "insertText": "".padEnd(Math.max(expected - actual, 0)) } ); } } } } } } }; /***/ }), /***/ 725: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, listItemMarkerRe, rangeFromRegExp } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); module.exports = { "names": [ "MD006", "ul-start-left" ], "description": "Consider starting bulleted lists at the beginning of the line", "tags": [ "bullet", "ul", "indentation" ], "function": function MD006(params, onError) { for (const list of flattenedLists()) { if (list.unordered && !list.nesting && (list.indent !== 0)) { for (const item of list.items) { const { lineNumber, line } = item; addErrorDetailIf( onError, lineNumber, 0, list.indent, null, null, rangeFromRegExp(line, listItemMarkerRe), { "deleteCount": line.length - line.trimStart().length }); } } } } }; /***/ }), /***/ 8121: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, indentFor, listItemMarkerRe } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); module.exports = { "names": [ "MD007", "ul-indent" ], "description": "Unordered list indentation", "tags": [ "bullet", "ul", "indentation" ], "function": function MD007(params, onError) { const indent = Number(params.config.indent || 2); const startIndented = !!params.config.start_indented; const startIndent = Number(params.config.start_indent || indent); for (const list of flattenedLists()) { if (list.unordered && list.parentsUnordered) { for (const item of list.items) { const { lineNumber, line } = item; const expectedIndent = (startIndented ? startIndent : 0) + (list.nesting * indent); const actualIndent = indentFor(item); let range = null; let editColumn = 1; const match = line.match(listItemMarkerRe); if (match) { range = [ 1, match[0].length ]; editColumn += match[1].length - actualIndent; } addErrorDetailIf( onError, lineNumber, expectedIndent, actualIndent, null, null, range, { editColumn, "deleteCount": actualIndent, "insertText": "".padEnd(expectedIndent) }); } } } } }; /***/ }), /***/ 7315: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError, filterTokens, forEachLine, includesSorted, numericSortAscending } = __nccwpck_require__(2935); const { lineMetadata } = __nccwpck_require__(2260); module.exports = { "names": [ "MD009", "no-trailing-spaces" ], "description": "Trailing spaces", "tags": [ "whitespace" ], "function": function MD009(params, onError) { let brSpaces = params.config.br_spaces; brSpaces = Number((brSpaces === undefined) ? 2 : brSpaces); const listItemEmptyLines = !!params.config.list_item_empty_lines; const strict = !!params.config.strict; const listItemLineNumbers = []; if (listItemEmptyLines) { filterTokens(params, "list_item_open", (token) => { for (let i = token.map[0]; i < token.map[1]; i++) { listItemLineNumbers.push(i + 1); } }); listItemLineNumbers.sort(numericSortAscending); } const paragraphLineNumbers = []; const codeInlineLineNumbers = []; if (strict) { filterTokens(params, "paragraph_open", (token) => { for (let i = token.map[0]; i < token.map[1] - 1; i++) { paragraphLineNumbers.push(i + 1); } }); const addLineNumberRange = (start, end) => { for (let i = start; i < end; i++) { codeInlineLineNumbers.push(i); } }; filterTokens(params, "inline", (token) => { let start = 0; for (const child of token.children) { if (start > 0) { addLineNumberRange(start, child.lineNumber); start = 0; } if (child.type === "code_inline") { start = child.lineNumber; } } if (start > 0) { addLineNumberRange(start, token.map[1]); } }); } const expected = (brSpaces < 2) ? 0 : brSpaces; forEachLine(lineMetadata(), (line, lineIndex, inCode) => { const lineNumber = lineIndex + 1; const trailingSpaces = line.length - line.trimEnd().length; if ( trailingSpaces && !inCode && !includesSorted(listItemLineNumbers, lineNumber) && ( (expected !== trailingSpaces) || (strict && (!includesSorted(paragraphLineNumbers, lineNumber) || includesSorted(codeInlineLineNumbers, lineNumber))) ) ) { const column = line.length - trailingSpaces + 1; addError( onError, lineNumber, "Expected: " + (expected === 0 ? "" : "0 or ") + expected + "; Actual: " + trailingSpaces, undefined, [ column, trailingSpaces ], { "editColumn": column, "deleteCount": trailingSpaces }); } }); } }; /***/ }), /***/ 1016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError, filterTokens, forEachLine, withinAnyRange } = __nccwpck_require__(2935); const { codeBlockAndSpanRanges, lineMetadata } = __nccwpck_require__(2260); const tabRe = /\t+/g; module.exports = { "names": [ "MD010", "no-hard-tabs" ], "description": "Hard tabs", "tags": [ "whitespace", "hard_tab" ], "function": function MD010(params, onError) { const codeBlocks = params.config.code_blocks; const includeCode = (codeBlocks === undefined) ? true : !!codeBlocks; const ignoreCodeLanguages = new Set( (params.config.ignore_code_languages || []) .map((language) => language.toLowerCase()) ); const spacesPerTab = params.config.spaces_per_tab; const spaceMultiplier = (spacesPerTab === undefined) ? 1 : Math.max(0, Number(spacesPerTab)); const exclusions = includeCode ? [] : codeBlockAndSpanRanges(); filterTokens(params, "fence", (token) => { const language = token.info.trim().toLowerCase(); if (ignoreCodeLanguages.has(language)) { for (let i = token.map[0] + 1; i < token.map[1] - 1; i++) { exclusions.push([ i, 0, params.lines[i].length ]); } } }); forEachLine(lineMetadata(), (line, lineIndex, inCode) => { if (includeCode || !inCode) { let match = null; while ((match = tabRe.exec(line)) !== null) { const { index } = match; const column = index + 1; const length = match[0].length; if (!withinAnyRange(exclusions, lineIndex, index, length)) { addError( onError, lineIndex + 1, "Column: " + column, null, [ column, length ], { "editColumn": column, "deleteCount": length, "insertText": "".padEnd(length * spaceMultiplier) } ); } } } }); } }; /***/ }), /***/ 3753: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError, forEachLine, withinAnyRange } = __nccwpck_require__(2935); const { codeBlockAndSpanRanges, lineMetadata } = __nccwpck_require__(2260); const reversedLinkRe = /(^|[^\\])\(([^)]+)\)\[([^\]^][^\]]*)](?!\()/g; module.exports = { "names": [ "MD011", "no-reversed-links" ], "description": "Reversed link syntax", "tags": [ "links" ], "function": function MD011(params, onError) { const exclusions = codeBlockAndSpanRanges(); forEachLine(lineMetadata(), (line, lineIndex, inCode, onFence) => { if (!inCode && !onFence) { let match = null; while ((match = reversedLinkRe.exec(line)) !== null) { const [ reversedLink, preChar, linkText, linkDestination ] = match; const index = match.index + preChar.length; const length = match[0].length - preChar.length; if ( !linkText.endsWith("\\") && !linkDestination.endsWith("\\") && !withinAnyRange(exclusions, lineIndex, index, length) ) { addError( onError, lineIndex + 1, reversedLink.slice(preChar.length), null, [ index + 1, length ], { "editColumn": index + 1, "deleteCount": length, "insertText": `[${linkText}](${linkDestination})` } ); } } } }); } }; /***/ }), /***/ 6454: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, forEachLine } = __nccwpck_require__(2935); const { lineMetadata } = __nccwpck_require__(2260); module.exports = { "names": [ "MD012", "no-multiple-blanks" ], "description": "Multiple consecutive blank lines", "tags": [ "whitespace", "blank_lines" ], "function": function MD012(params, onError) { const maximum = Number(params.config.maximum || 1); let count = 0; forEachLine(lineMetadata(), (line, lineIndex, inCode) => { count = (inCode || (line.trim().length > 0)) ? 0 : count + 1; if (maximum < count) { addErrorDetailIf( onError, lineIndex + 1, maximum, count, null, null, null, { "deleteCount": -1 }); } }); } }; /***/ }), /***/ 1518: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, filterTokens, forEachHeading, forEachLine, includesSorted, linkReferenceDefinitionRe } = __nccwpck_require__(2935); const { lineMetadata } = __nccwpck_require__(2260); const longLineRePrefix = "^.{"; const longLineRePostfixRelaxed = "}.*\\s.*$"; const longLineRePostfixStrict = "}.+$"; const linkOrImageOnlyLineRe = /^[es]*(lT?L|I)[ES]*$/; const sternModeRe = /^([#>\s]*\s)?\S*$/; const tokenTypeMap = { "em_open": "e", "em_close": "E", "image": "I", "link_open": "l", "link_close": "L", "strong_open": "s", "strong_close": "S", "text": "T" }; module.exports = { "names": [ "MD013", "line-length" ], "description": "Line length", "tags": [ "line_length" ], "function": function MD013(params, onError) { const lineLength = Number(params.config.line_length || 80); const headingLineLength = Number(params.config.heading_line_length || lineLength); const codeLineLength = Number(params.config.code_block_line_length || lineLength); const strict = !!params.config.strict; const stern = !!params.config.stern; const longLineRePostfix = (strict || stern) ? longLineRePostfixStrict : longLineRePostfixRelaxed; const longLineRe = new RegExp(longLineRePrefix + lineLength + longLineRePostfix); const longHeadingLineRe = new RegExp(longLineRePrefix + headingLineLength + longLineRePostfix); const longCodeLineRe = new RegExp(longLineRePrefix + codeLineLength + longLineRePostfix); const codeBlocks = params.config.code_blocks; const includeCodeBlocks = (codeBlocks === undefined) ? true : !!codeBlocks; const tables = params.config.tables; const includeTables = (tables === undefined) ? true : !!tables; let headings = params.config.headings; if (headings === undefined) { headings = params.config.headers; } const includeHeadings = (headings === undefined) ? true : !!headings; const headingLineNumbers = []; forEachHeading(params, (heading) => { headingLineNumbers.push(heading.lineNumber); }); const linkOnlyLineNumbers = []; filterTokens(params, "inline", (token) => { let childTokenTypes = ""; for (const child of token.children) { if (child.type !== "text" || child.content !== "") { childTokenTypes += tokenTypeMap[child.type] || "x"; } } if (linkOrImageOnlyLineRe.test(childTokenTypes)) { linkOnlyLineNumbers.push(token.lineNumber); } }); forEachLine(lineMetadata(), (line, lineIndex, inCode, onFence, inTable) => { const lineNumber = lineIndex + 1; const isHeading = includesSorted(headingLineNumbers, lineNumber); const length = inCode ? codeLineLength : (isHeading ? headingLineLength : lineLength); const lengthRe = inCode ? longCodeLineRe : (isHeading ? longHeadingLineRe : longLineRe); if ((includeCodeBlocks || !inCode) && (includeTables || !inTable) && (includeHeadings || !isHeading) && (strict || (!(stern && sternModeRe.test(line)) && !includesSorted(linkOnlyLineNumbers, lineNumber) && !linkReferenceDefinitionRe.test(line))) && lengthRe.test(line)) { addErrorDetailIf( onError, lineNumber, length, line.length, null, null, [ length + 1, line.length - length ]); } }); } }; /***/ }), /***/ 3463: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens } = __nccwpck_require__(2935); const dollarCommandRe = /^(\s*)(\$\s+)/; module.exports = { "names": [ "MD014", "commands-show-output" ], "description": "Dollar signs used before commands without showing output", "tags": [ "code" ], "function": function MD014(params, onError) { for (const type of [ "code_block", "fence" ]) { filterTokens(params, type, (token) => { const margin = (token.type === "fence") ? 1 : 0; const dollarInstances = []; let allDollars = true; for (let i = token.map[0] + margin; i < token.map[1] - margin; i++) { const line = params.lines[i]; const lineTrim = line.trim(); if (lineTrim) { const match = dollarCommandRe.exec(line); if (match) { const column = match[1].length + 1; const length = match[2].length; dollarInstances.push([ i, lineTrim, column, length ]); } else { allDollars = false; } } } if (allDollars) { for (const instance of dollarInstances) { const [ i, lineTrim, column, length ] = instance; addErrorContext( onError, i + 1, lineTrim, null, null, [ column, length ], { "editColumn": column, "deleteCount": length } ); } } }); } } }; /***/ }), /***/ 5496: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, forEachLine } = __nccwpck_require__(2935); const { lineMetadata } = __nccwpck_require__(2260); module.exports = { "names": [ "MD018", "no-missing-space-atx" ], "description": "No space after hash on atx style heading", "tags": [ "headings", "headers", "atx", "spaces" ], "function": function MD018(params, onError) { forEachLine(lineMetadata(), (line, lineIndex, inCode) => { if (!inCode && /^#+[^# \t]/.test(line) && !/#\s*$/.test(line) && !line.startsWith("#️⃣")) { const hashCount = /^#+/.exec(line)[0].length; addErrorContext( onError, lineIndex + 1, line.trim(), null, null, [ 1, hashCount + 1 ], { "editColumn": hashCount + 1, "insertText": " " } ); } }); } }; /***/ }), /***/ 6478: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens, headingStyleFor } = __nccwpck_require__(2935); module.exports = { "names": [ "MD019", "no-multiple-space-atx" ], "description": "Multiple spaces after hash on atx style heading", "tags": [ "headings", "headers", "atx", "spaces" ], "function": function MD019(params, onError) { filterTokens(params, "heading_open", (token) => { if (headingStyleFor(token) === "atx") { const { line, lineNumber } = token; const match = /^(#+)([ \t]{2,})(?:\S)/.exec(line); if (match) { const [ , { "length": hashLength }, { "length": spacesLength } ] = match; addErrorContext( onError, lineNumber, line.trim(), null, null, [ 1, hashLength + spacesLength + 1 ], { "editColumn": hashLength + 1, "deleteCount": spacesLength - 1 } ); } } }); } }; /***/ }), /***/ 9915: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, forEachLine } = __nccwpck_require__(2935); const { lineMetadata } = __nccwpck_require__(2260); module.exports = { "names": [ "MD020", "no-missing-space-closed-atx" ], "description": "No space inside hashes on closed atx style heading", "tags": [ "headings", "headers", "atx_closed", "spaces" ], "function": function MD020(params, onError) { forEachLine(lineMetadata(), (line, lineIndex, inCode) => { if (!inCode) { const match = /^(#+)([ \t]*)([^#]*?[^#\\])([ \t]*)((?:\\#)?)(#+)(\s*)$/.exec(line); if (match) { const [ , leftHash, { "length": leftSpaceLength }, content, { "length": rightSpaceLength }, rightEscape, rightHash, { "length": trailSpaceLength } ] = match; const leftHashLength = leftHash.length; const rightHashLength = rightHash.length; const left = !leftSpaceLength; const right = !rightSpaceLength || rightEscape; const rightEscapeReplacement = rightEscape ? `${rightEscape} ` : ""; if (left || right) { const range = left ? [ 1, leftHashLength + 1 ] : [ line.length - trailSpaceLength - rightHashLength, rightHashLength + 1 ]; addErrorContext( onError, lineIndex + 1, line.trim(), left, right, range, { "editColumn": 1, "deleteCount": line.length, "insertText": `${leftHash} ${content} ${rightEscapeReplacement}${rightHash}` } ); } } } }); } }; /***/ }), /***/ 4898: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens, headingStyleFor } = __nccwpck_require__(2935); const closedAtxRe = /^(#+)([ \t]+)([^ \t]|[^ \t].*[^ \t])([ \t]+)(#+)(\s*)$/; module.exports = { "names": [ "MD021", "no-multiple-space-closed-atx" ], "description": "Multiple spaces inside hashes on closed atx style heading", "tags": [ "headings", "headers", "atx_closed", "spaces" ], "function": function MD021(params, onError) { filterTokens(params, "heading_open", (token) => { if (headingStyleFor(token) === "atx_closed") { const { line, lineNumber } = token; const match = closedAtxRe.exec(line); if (match) { const [ , leftHash, { "length": leftSpaceLength }, content, { "length": rightSpaceLength }, rightHash, { "length": trailSpaceLength } ] = match; const left = leftSpaceLength > 1; const right = rightSpaceLength > 1; if (left || right) { const length = line.length; const leftHashLength = leftHash.length; const rightHashLength = rightHash.length; const range = left ? [ 1, leftHashLength + leftSpaceLength + 1 ] : [ length - trailSpaceLength - rightHashLength - rightSpaceLength, rightSpaceLength + rightHashLength + 1 ]; addErrorContext( onError, lineNumber, line.trim(), left, right, range, { "editColumn": 1, "deleteCount": length, "insertText": `${leftHash} ${content} ${rightHash}` } ); } } } }); } }; /***/ }), /***/ 5164: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, filterTokens, isBlankLine } = __nccwpck_require__(2935); module.exports = { "names": [ "MD022", "blanks-around-headings", "blanks-around-headers" ], "description": "Headings should be surrounded by blank lines", "tags": [ "headings", "headers", "blank_lines" ], "function": function MD022(params, onError) { let linesAbove = params.config.lines_above; linesAbove = Number((linesAbove === undefined) ? 1 : linesAbove); let linesBelow = params.config.lines_below; linesBelow = Number((linesBelow === undefined) ? 1 : linesBelow); const { lines } = params; filterTokens(params, "heading_open", (token) => { const [ topIndex, nextIndex ] = token.map; let actualAbove = 0; for (let i = 0; i < linesAbove; i++) { if (isBlankLine(lines[topIndex - i - 1])) { actualAbove++; } } addErrorDetailIf( onError, topIndex + 1, linesAbove, actualAbove, "Above", lines[topIndex].trim(), null, { "insertText": "".padEnd(linesAbove - actualAbove, "\n") }); let actualBelow = 0; for (let i = 0; i < linesBelow; i++) { if (isBlankLine(lines[nextIndex + i])) { actualBelow++; } } addErrorDetailIf( onError, topIndex + 1, linesBelow, actualBelow, "Below", lines[topIndex].trim(), null, { "lineNumber": nextIndex + 1, "insertText": "".padEnd(linesBelow - actualBelow, "\n") }); }); } }; /***/ }), /***/ 1829: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens } = __nccwpck_require__(2935); const spaceBeforeHeadingRe = /^((?:\s+)|(?:[>\s]+\s\s))[^>\s]/; module.exports = { "names": [ "MD023", "heading-start-left", "header-start-left" ], "description": "Headings must start at the beginning of the line", "tags": [ "headings", "headers", "spaces" ], "function": function MD023(params, onError) { filterTokens(params, "heading_open", function forToken(token) { const { lineNumber, line } = token; const match = line.match(spaceBeforeHeadingRe); if (match) { const [ prefixAndFirstChar, prefix ] = match; let deleteCount = prefix.length; const prefixLengthNoSpace = prefix.trimEnd().length; if (prefixLengthNoSpace) { deleteCount -= prefixLengthNoSpace - 1; } addErrorContext( onError, lineNumber, line, null, null, [ 1, prefixAndFirstChar.length ], { "editColumn": prefixLengthNoSpace + 1, "deleteCount": deleteCount }); } }); } }; /***/ }), /***/ 7177: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, forEachHeading } = __nccwpck_require__(2935); module.exports = { "names": [ "MD024", "no-duplicate-heading", "no-duplicate-header" ], "description": "Multiple headings with the same content", "tags": [ "headings", "headers" ], "function": function MD024(params, onError) { const siblingsOnly = !!params.config.siblings_only || !!params.config.allow_different_nesting || false; const knownContents = [ null, [] ]; let lastLevel = 1; let knownContent = knownContents[lastLevel]; forEachHeading(params, (heading, content) => { if (siblingsOnly) { const newLevel = heading.tag.slice(1); while (lastLevel < newLevel) { lastLevel++; knownContents[lastLevel] = []; } while (lastLevel > newLevel) { knownContents[lastLevel] = []; lastLevel--; } knownContent = knownContents[newLevel]; } if (knownContent.includes(content)) { addErrorContext(onError, heading.lineNumber, heading.line.trim()); } else { knownContent.push(content); } }); } }; /***/ }), /***/ 692: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens, frontMatterHasTitle } = __nccwpck_require__(2935); module.exports = { "names": [ "MD025", "single-title", "single-h1" ], "description": "Multiple top-level headings in the same document", "tags": [ "headings", "headers" ], "function": function MD025(params, onError) { const level = Number(params.config.level || 1); const tag = "h" + level; const foundFrontMatterTitle = frontMatterHasTitle( params.frontMatterLines, params.config.front_matter_title ); let hasTopLevelHeading = false; filterTokens(params, "heading_open", function forToken(token) { if (token.tag === tag) { if (hasTopLevelHeading || foundFrontMatterTitle) { addErrorContext(onError, token.lineNumber, token.line.trim()); } else if (token.lineNumber === 1) { hasTopLevelHeading = true; } } }); } }; /***/ }), /***/ 1629: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError, allPunctuationNoQuestion, escapeForRegExp, forEachHeading } = __nccwpck_require__(2935); const endOfLineHtmlEntityRe = /&#?[0-9a-zA-Z]+;$/; module.exports = { "names": [ "MD026", "no-trailing-punctuation" ], "description": "Trailing punctuation in heading", "tags": [ "headings", "headers" ], "function": function MD026(params, onError) { let punctuation = params.config.punctuation; punctuation = String( (punctuation === undefined) ? allPunctuationNoQuestion : punctuation ); const trailingPunctuationRe = new RegExp("\\s*[" + escapeForRegExp(punctuation) + "]+$"); forEachHeading(params, (heading) => { const { line, lineNumber } = heading; const trimmedLine = line.replace(/([^\s#])[\s#]+$/, "$1"); const match = trailingPunctuationRe.exec(trimmedLine); if (match && !endOfLineHtmlEntityRe.test(trimmedLine)) { const fullMatch = match[0]; const column = match.index + 1; const length = fullMatch.length; addError( onError, lineNumber, `Punctuation: '${fullMatch}'`, null, [ column, length ], { "editColumn": column, "deleteCount": length } ); } }); } }; /***/ }), /***/ 6325: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, newLineRe } = __nccwpck_require__(2935); const spaceAfterBlockQuoteRe = /^((?:\s*>)+)(\s{2,})\S/; module.exports = { "names": [ "MD027", "no-multiple-space-blockquote" ], "description": "Multiple spaces after blockquote symbol", "tags": [ "blockquote", "whitespace", "indentation" ], "function": function MD027(params, onError) { let blockquoteNesting = 0; let listItemNesting = 0; for (const token of params.tokens) { const { content, lineNumber, type } = token; if (type === "blockquote_open") { blockquoteNesting++; } else if (type === "blockquote_close") { blockquoteNesting--; } else if (type === "list_item_open") { listItemNesting++; } else if (type === "list_item_close") { listItemNesting--; } else if ((type === "inline") && blockquoteNesting) { const lineCount = content.split(newLineRe).length; for (let i = 0; i < lineCount; i++) { const line = params.lines[lineNumber + i - 1]; const match = line.match(spaceAfterBlockQuoteRe); if (match) { const [ fullMatch, { "length": blockquoteLength }, { "length": spaceLength } ] = match; if (!listItemNesting || (fullMatch[fullMatch.length - 1] === ">")) { addErrorContext( onError, lineNumber + i, line, null, null, [ 1, fullMatch.length ], { "editColumn": blockquoteLength + 1, "deleteCount": spaceLength - 1 } ); } } } } } } }; /***/ }), /***/ 7542: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError } = __nccwpck_require__(2935); module.exports = { "names": [ "MD028", "no-blanks-blockquote" ], "description": "Blank line inside blockquote", "tags": [ "blockquote", "whitespace" ], "function": function MD028(params, onError) { let prevToken = {}; let prevLineNumber = null; for (const token of params.tokens) { if ((token.type === "blockquote_open") && (prevToken.type === "blockquote_close")) { for ( let lineNumber = prevLineNumber; lineNumber < token.lineNumber; lineNumber++) { addError(onError, lineNumber); } } prevToken = token; if (token.type === "blockquote_open") { prevLineNumber = token.map[1] + 1; } } } }; /***/ }), /***/ 3404: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, listItemMarkerRe, orderedListItemMarkerRe, rangeFromRegExp } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); const listStyleExamples = { "one": "1/1/1", "ordered": "1/2/3", "zero": "0/0/0" }; module.exports = { "names": [ "MD029", "ol-prefix" ], "description": "Ordered list item prefix", "tags": [ "ol" ], "function": function MD029(params, onError) { const style = String(params.config.style || "one_or_ordered"); const filteredLists = flattenedLists().filter((list) => !list.unordered); for (const list of filteredLists) { const { items } = list; let current = 1; let incrementing = false; // Check for incrementing number pattern 1/2/3 or 0/1/2 if (items.length >= 2) { const first = orderedListItemMarkerRe.exec(items[0].line); const second = orderedListItemMarkerRe.exec(items[1].line); if (first && second) { const [ , firstNumber ] = first; const [ , secondNumber ] = second; if ((secondNumber !== "1") || (firstNumber === "0")) { incrementing = true; if (firstNumber === "0") { current = 0; } } } } // Determine effective style let listStyle = style; if (listStyle === "one_or_ordered") { listStyle = incrementing ? "ordered" : "one"; } // Force expected value for 0/0/0 and 1/1/1 patterns if (listStyle === "zero") { current = 0; } else if (listStyle === "one") { current = 1; } // Validate each list item marker for (const item of items) { const match = orderedListItemMarkerRe.exec(item.line); if (match) { addErrorDetailIf(onError, item.lineNumber, String(current), match[1], "Style: " + listStyleExamples[listStyle], null, rangeFromRegExp(item.line, listItemMarkerRe)); if (listStyle === "ordered") { current++; } } } } } }; /***/ }), /***/ 2549: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); module.exports = { "names": [ "MD030", "list-marker-space" ], "description": "Spaces after list markers", "tags": [ "ol", "ul", "whitespace" ], "function": function MD030(params, onError) { const ulSingle = Number(params.config.ul_single || 1); const olSingle = Number(params.config.ol_single || 1); const ulMulti = Number(params.config.ul_multi || 1); const olMulti = Number(params.config.ol_multi || 1); for (const list of flattenedLists()) { const lineCount = list.lastLineIndex - list.open.map[0]; const allSingle = lineCount === list.items.length; const expectedSpaces = list.unordered ? (allSingle ? ulSingle : ulMulti) : (allSingle ? olSingle : olMulti); for (const item of list.items) { const { line, lineNumber } = item; const match = /^[\s>]*\S+(\s*)/.exec(line); const [ { "length": matchLength }, { "length": actualSpaces } ] = match; if (matchLength < line.length) { let fixInfo = null; if (expectedSpaces !== actualSpaces) { fixInfo = { "editColumn": matchLength - actualSpaces + 1, "deleteCount": actualSpaces, "insertText": "".padEnd(expectedSpaces) }; } addErrorDetailIf( onError, lineNumber, expectedSpaces, actualSpaces, null, null, [ 1, matchLength ], fixInfo ); } } } } }; /***/ }), /***/ 2202: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, forEachLine, isBlankLine } = __nccwpck_require__(2935); const { lineMetadata } = __nccwpck_require__(2260); const codeFencePrefixRe = /^(.*?)[`~]/; module.exports = { "names": [ "MD031", "blanks-around-fences" ], "description": "Fenced code blocks should be surrounded by blank lines", "tags": [ "code", "blank_lines" ], "function": function MD031(params, onError) { const listItems = params.config.list_items; const includeListItems = (listItems === undefined) ? true : !!listItems; const { lines } = params; forEachLine(lineMetadata(), (line, i, inCode, onFence, inTable, inItem) => { const onTopFence = (onFence > 0); const onBottomFence = (onFence < 0); if ((includeListItems || !inItem) && ((onTopFence && !isBlankLine(lines[i - 1])) || (onBottomFence && !isBlankLine(lines[i + 1])))) { const [ , prefix ] = line.match(codeFencePrefixRe) || []; const fixInfo = (prefix === undefined) ? null : { "lineNumber": i + (onTopFence ? 1 : 2), "insertText": `${prefix.replace(/[^>]/g, " ").trim()}\n` }; addErrorContext( onError, i + 1, lines[i].trim(), null, null, null, fixInfo); } }); } }; /***/ }), /***/ 3474: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, blockquotePrefixRe, isBlankLine } = __nccwpck_require__(2935); const { flattenedLists } = __nccwpck_require__(2260); module.exports = { "names": [ "MD032", "blanks-around-lists" ], "description": "Lists should be surrounded by blank lines", "tags": [ "bullet", "ul", "ol", "blank_lines" ], "function": function MD032(params, onError) { const { lines } = params; const filteredLists = flattenedLists().filter((list) => !list.nesting); for (const list of filteredLists) { const firstIndex = list.open.map[0]; if (!isBlankLine(lines[firstIndex - 1])) { const line = lines[firstIndex]; const quotePrefix = line.match(blockquotePrefixRe)[0].trimEnd(); addErrorContext( onError, firstIndex + 1, line.trim(), null, null, null, { "insertText": `${quotePrefix}\n` }); } const lastIndex = list.lastLineIndex - 1; if (!isBlankLine(lines[lastIndex + 1])) { const line = lines[lastIndex]; const quotePrefix = line.match(blockquotePrefixRe)[0].trimEnd(); addErrorContext( onError, lastIndex + 1, line.trim(), null, null, null, { "lineNumber": lastIndex + 2, "insertText": `${quotePrefix}\n` }); } } } }; /***/ }), /***/ 77: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addError, forEachLine, htmlElementRe, withinAnyRange, unescapeMarkdown } = __nccwpck_require__(2935); const { codeBlockAndSpanRanges, lineMetadata } = __nccwpck_require__(2260); const linkDestinationRe = /]\(\s*$/; // See https://spec.commonmark.org/0.29/#autolinks const emailAddressRe = // eslint-disable-next-line max-len /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; module.exports = { "names": [ "MD033", "no-inline-html" ], "description": "Inline HTML", "tags": [ "html" ], "function": function MD033(params, onError) { let allowedElements = params.config.allowed_elements; allowedElements = Array.isArray(allowedElements) ? allowedElements : []; allowedElements = allowedElements.map((element) => element.toLowerCase()); const exclusions = codeBlockAndSpanRanges(); forEachLine(lineMetadata(), (line, lineIndex, inCode) => { let match = null; // eslint-disable-next-line no-unmodified-loop-condition while (!inCode && ((match = htmlElementRe.exec(line)) !== null)) { const [ tag, content, element ] = match; if ( !allowedElements.includes(element.toLowerCase()) && !tag.endsWith("\\>") && !emailAddressRe.test(content) && !withinAnyRange(exclusions, lineIndex, match.index, match[0].length) ) { const prefix = line.substring(0, match.index); if (!linkDestinationRe.test(prefix)) { const unescaped = unescapeMarkdown(prefix + "<", "_"); if (!unescaped.endsWith("_")) { addError(onError, lineIndex + 1, "Element: " + element, undefined, [ match.index + 1, tag.length ]); } } } } }); } }; /***/ }), /***/ 4721: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, bareUrlRe, filterTokens } = __nccwpck_require__(2935); module.exports = { "names": [ "MD034", "no-bare-urls" ], "description": "Bare URL used", "tags": [ "links", "url" ], "function": function MD034(params, onError) { filterTokens(params, "inline", (token) => { let inLink = false; for (const child of token.children) { const { content, line, lineNumber, type } = child; let match = null; if (type === "link_open") { inLink = true; } else if (type === "link_close") { inLink = false; } else if ((type === "text") && !inLink) { while ((match = bareUrlRe.exec(content)) !== null) { const [ bareUrl ] = match; const matchIndex = match.index; const bareUrlLength = bareUrl.length; // Allow "[https://example.com]" to avoid conflicts with // MD011/no-reversed-links; allow quoting as another way // of deliberately including a bare URL const leftChar = content[matchIndex - 1]; const rightChar = content[matchIndex + bareUrlLength]; if ( !((leftChar === "[") && (rightChar === "]")) && !((leftChar === "\"") && (rightChar === "\"")) && !((leftChar === "'") && (rightChar === "'")) ) { const index = line.indexOf(content); const range = (index === -1) ? null : [ index + matchIndex + 1, bareUrlLength ]; const fixInfo = range ? { "editColumn": range[0], "deleteCount": range[1], "insertText": `<${bareUrl}>` } : null; addErrorContext( onError, lineNumber, bareUrl, null, null, range, fixInfo ); } } } } }); } }; /***/ }), /***/ 2997: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorDetailIf, filterTokens } = __nccwpck_require__(2935); module.exports = { "names": [ "MD035", "hr-style" ], "description": "Horizontal rule style", "tags": [ "hr" ], "function": function MD035(params, onError) { let style = String(params.config.style || "consistent").trim(); filterTokens(params, "hr", (token) => { const { line, lineNumber } = token; let { markup } = token; const match = line.match(/[_*\-\s\t]+$/); if (match) { markup = match[0].trim(); } if (style === "consistent") { style = markup; } addErrorDetailIf(onError, lineNumber, style, markup); }); } }; /***/ }), /***/ 338: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, allPunctuation } = __nccwpck_require__(2935); module.exports = { "names": [ "MD036", "no-emphasis-as-heading", "no-emphasis-as-header" ], "description": "Emphasis used instead of a heading", "tags": [ "headings", "headers", "emphasis" ], "function": function MD036(params, onError) { let punctuation = params.config.punctuation; punctuation = String((punctuation === undefined) ? allPunctuation : punctuation); const re = new RegExp("[" + punctuation + "]$"); // eslint-disable-next-line jsdoc/require-jsdoc function base(token) { if (token.type === "paragraph_open") { return function inParagraph(t) { // Always paragraph_open/inline/paragraph_close, const children = t.children.filter(function notEmptyText(child) { return (child.type !== "text") || (child.content !== ""); }); if ((children.length === 3) && ((children[0].type === "strong_open") || (children[0].type === "em_open")) && (children[1].type === "text") && !re.test(children[1].content)) { addErrorContext(onError, t.lineNumber, children[1].content); } return base; }; } else if (token.type === "blockquote_open") { return function inBlockquote(t) { if (t.type !== "blockquote_close") { return inBlockquote; } return base; }; } else if (token.type === "list_item_open") { return function inListItem(t) { if (t.type !== "list_item_close") { return inListItem; } return base; }; } return base; } let state = base; for (const token of params.tokens) { state = state(token); } } }; /***/ }), /***/ 2905: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, emphasisMarkersInContent, forEachLine, isBlankLine, withinAnyRange } = __nccwpck_require__(2935); const { htmlElementRanges, lineMetadata } = __nccwpck_require__(2260); const emphasisRe = /(^|[^\\]|\\\\)(?:(\*\*?\*?)|(__?_?))/g; const embeddedUnderscoreRe = /([A-Za-z0-9])_([A-Za-z0-9])/g; const asteriskListItemMarkerRe = /^([\s>]*)\*(\s+)/; const leftSpaceRe = /^\s+/; const rightSpaceRe = /\s+$/; const tablePipeRe = /\|/; module.exports = { "names": [ "MD037", "no-space-in-emphasis" ], "description": "Spaces inside emphasis markers", "tags": [ "whitespace", "emphasis" ], "function": function MD037(params, onError) { const exclusions = htmlElementRanges(); // eslint-disable-next-line init-declarations let effectiveEmphasisLength, emphasisIndex, emphasisKind, emphasisLength, pendingError = null; // eslint-disable-next-line jsdoc/require-jsdoc function resetRunTracking() { emphasisIndex = -1; emphasisLength = 0; emphasisKind = ""; effectiveEmphasisLength = 0; pendingError = null; } // eslint-disable-next-line jsdoc/require-jsdoc function handleRunEnd( line, lineIndex, contextLength, match, matchIndex, inTable ) { // Close current run let content = line.substring(emphasisIndex, matchIndex); if (!emphasisLength) { content = content.trimStart(); } if (!match) { content = content.trimEnd(); } const leftSpace = leftSpaceRe.test(content); const rightSpace = rightSpaceRe.test(content); if ( (leftSpace || rightSpace) && (!inTable || !tablePipeRe.test(content)) ) { // Report the violation const contextStart = emphasisIndex - emphasisLength; const contextEnd = matchIndex + contextLength; const column = contextStart + 1; const length = contextEnd - contextStart; if (!withinAnyRange(exclusions, lineIndex, column, length)) { const context = line.substring(contextStart, contextEnd); const leftMarker = line.substring(contextStart, emphasisIndex); const rightMarker = match ? (match[2] || match[3]) : ""; const fixedText = `${leftMarker}${content.trim()}${rightMarker}`; return [ onError, lineIndex + 1, context, leftSpace, rightSpace, [ column, length ], { "editColumn": column, "deleteCount": length, "insertText": fixedText } ]; } } return null; } // Initialize const ignoreMarkersByLine = emphasisMarkersInContent(params); resetRunTracking(); forEachLine( lineMetadata(), (line, lineIndex, inCode, onFence, inTable, inItem, onBreak, inMath) => { const onItemStart = (inItem === 1); if ( inCode || onFence || inTable || onBreak || onItemStart || isBlankLine(line) ) { // Emphasis resets when leaving a block resetRunTracking(); } if ( inCode || onFence || onBreak || inMath ) { // Emphasis has no meaning here return; } let patchedLine = line.replace(embeddedUnderscoreRe, "$1 $2"); if (onItemStart) { // Trim overlapping '*' list item marker patchedLine = patchedLine.replace(asteriskListItemMarkerRe, "$1 $2"); } let match = null; // Match all emphasis-looking runs in the line... while ((match = emphasisRe.exec(patchedLine))) { const ignoreMarkersForLine = ignoreMarkersByLine[lineIndex]; const matchIndex = match.index + match[1].length; if (ignoreMarkersForLine.includes(matchIndex)) { // Ignore emphasis markers inside code spans and links continue; } const matchLength = match[0].length - match[1].length; const matchKind = (match[2] || match[3])[0]; if (emphasisIndex === -1) { // New run emphasisIndex = matchIndex + matchLength; emphasisLength = matchLength; emphasisKind = matchKind; effectiveEmphasisLength = matchLength; } else if (matchKind === emphasisKind) { // Matching emphasis markers if (matchLength === effectiveEmphasisLength) { // Ending an existing run, report any pending error if (pendingError) { // @ts-ignore addErrorContext(...pendingError); pendingError = null; } const error = handleRunEnd( line, lineIndex, effectiveEmphasisLength, match, matchIndex, inTable ); if (error) { // @ts-ignore addErrorContext(...error); } // Reset resetRunTracking(); } else if (matchLength === 3) { // Swap internal run length (1->2 or 2->1) effectiveEmphasisLength = matchLength - effectiveEmphasisLength; } else if (effectiveEmphasisLength === 3) { // Downgrade internal run (3->1 or 3->2) effectiveEmphasisLength -= matchLength; } else { // Upgrade to internal run (1->3 or 2->3) effectiveEmphasisLength += matchLength; } // Back up one character so RegExp has a chance to match the // next marker (ex: "**star**_underscore_") if (emphasisRe.lastIndex > 1) { emphasisRe.lastIndex--; } } else if (emphasisRe.lastIndex > 1) { // Back up one character so RegExp has a chance to match the // mis-matched marker (ex: "*text_*") emphasisRe.lastIndex--; } } if (emphasisIndex !== -1) { pendingError = pendingError || handleRunEnd(line, lineIndex, 0, null, line.length, inTable); // Adjust for pending run on new line emphasisIndex = 0; emphasisLength = 0; } } ); } }; /***/ }), /***/ 6054: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens, forEachInlineCodeSpan, newLineRe } = __nccwpck_require__(2935); const leftSpaceRe = /^\s([^`]|$)/; const rightSpaceRe = /[^`]\s$/; const spaceInsideCodeInline = (token) => ( (token.type === "code_inline") && (leftSpaceRe.test(token.content) || rightSpaceRe.test(token.content)) ); module.exports = { "names": [ "MD038", "no-space-in-code" ], "description": "Spaces inside code span elements", "tags": [ "whitespace", "code" ], "function": function MD038(params, onError) { filterTokens(params, "inline", (token) => { if (token.children.some(spaceInsideCodeInline)) { const tokenLines = params.lines.slice(token.map[0], token.map[1]); forEachInlineCodeSpan( tokenLines.join("\n"), (code, lineIndex, columnIndex, tickCount) => { let rangeIndex = columnIndex - tickCount; let rangeLength = code.length + (2 * tickCount); let rangeLineOffset = 0; let fixIndex = columnIndex; let fixLength = code.length; const codeLines = code.split(newLineRe); const left = leftSpaceRe.test(code); const right = !left && rightSpaceRe.test(code); if (right && (codeLines.length > 1)) { rangeIndex = 0; rangeLineOffset = codeLines.length - 1; fixIndex = 0; } if (left || right) { const codeLinesRange = codeLines[rangeLineOffset]; if (codeLines.length > 1) { rangeLength = codeLinesRange.length + tickCount; fixLength = codeLinesRange.length; } const context = tokenLines[lineIndex + rangeLineOffset] .substring(rangeIndex, rangeIndex + rangeLength); const codeLinesRangeTrim = codeLinesRange.trim(); const fixText = (codeLinesRangeTrim.startsWith("`") ? " " : "") + codeLinesRangeTrim + (codeLinesRangeTrim.endsWith("`") ? " " : ""); addErrorContext( onError, token.lineNumber + lineIndex + rangeLineOffset, context, left, right, [ rangeIndex + 1, rangeLength ], { "editColumn": fixIndex + 1, "deleteCount": fixLength, "insertText": fixText } ); } }); } }); } }; /***/ }), /***/ 8596: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens } = __nccwpck_require__(2935); const spaceInLinkRe = /\[(?:\s+(?:[^\]]*?)\s*|(?:[^\]]*?)\s+)](?=((?:\([^)]*\))|(?:\[[^\]]*\])))/; module.exports = { "names": [ "MD039", "no-space-in-links" ], "description": "Spaces inside link text", "tags": [ "whitespace", "links" ], "function": function MD039(params, onError) { filterTokens(params, "inline", (token) => { const { children } = token; let { lineNumber } = token; let inLink = false; let linkText = ""; let lineIndex = 0; for (const child of children) { const { content, markup, type } = child; if (type === "link_open") { inLink = true; linkText = ""; } else if (type === "link_close") { inLink = false; const left = linkText.trimStart().length !== linkText.length; const right = linkText.trimEnd().length !== linkText.length; if (left || right) { const line = params.lines[lineNumber - 1]; let range = null; let fixInfo = null; const match = line.slice(lineIndex).match(spaceInLinkRe); if (match) { const column = match.index + lineIndex + 1; const length = match[0].length; range = [ column, length ]; fixInfo = { "editColumn": column + 1, "deleteCount": length - 2, "insertText": linkText.trim() }; lineIndex = column + length - 1; } addErrorContext( onError, lineNumber, `[${linkText}]`, left, right, range, fixInfo ); } } else if ((type === "softbreak") || (type === "hardbreak")) { lineNumber++; lineIndex = 0; } else if (inLink) { linkText += type.endsWith("_inline") ? `${markup}${content}${markup}` : (content || markup); } } }); } }; /***/ }), /***/ 320: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, filterTokens } = __nccwpck_require__(2935); module.exports = { "names": [ "MD040", "fenced-code-language" ], "description": "Fenced code blocks should have a language specified", "tags": [ "code", "language" ], "function": function MD040(params, onError) { filterTokens(params, "fence", function forToken(token) { if (!token.info.trim()) { addErrorContext(onError, token.lineNumber, token.line); } }); } }; /***/ }), /***/ 8679: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; // @ts-check const { addErrorContext, frontMatterHasTitle } = __nccwpck_require__(2935); module.exports = { "names": [ "MD041", "first-line-heading", "first-line-h1" ], "description": "First line in a file should be a top-level heading", "tags": [ "headings", "headers" ], "function": function MD041(params, onError) { const level = Number(params.config.level || 1); const tag = "h" + level; const foundFrontMatterTitle = frontMatterHasTitle( params.frontMatterLines, params.config.front_matter_title ); if (!foundFrontMatterTitle) { const htmlHeadingRe = new RegExp(`^]`, "i"); params.tokens.every((token) => { let isError = false; if (token.type === "html_block") { if (token.content.startsWith("