0
0
Fork 0
mirror of https://github.com/DavidAnson/markdownlint-cli2-action.git synced 2024-10-16 12:07:01 +02:00
markdownlint-cli2-action/dist/index.js
2023-01-02 16:04:35 -08:00

34879 lines
No EOL
1 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/******/ (() => { // 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}</${tag}>`;
}
/**
* 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>} 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 (<hr>) 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 (<br>) 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
};
/***/ }),
/***/ 4460:
/***/ ((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');
};
/***/ }),
/***/ 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__(4460);
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 () {
if (queue.idle()) {
return new Promise(function (resolve) {
resolve()
})
}
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 <https://github.com/jonschlinkert/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;
/***/ }),
/***/ 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_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/
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 = '/'
// Do not use ternary expression here, since "istanbul ignore next" is buggy
let TMP_KEY_IGNORE = 'node-ignore'
/* istanbul ignore else */
if (typeof Symbol !== 'undefined') {
TMP_KEY_IGNORE = Symbol.for('node-ignore')
}
const KEY_IGNORE = TMP_KEY_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
: '\\/.+'
],
// normal intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule,
// coz trailing single wildcard will be handed by [trailing wildcard]
/(^|[^\\]+)(\\\*)+(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
(_, p1, p2) => {
// 1.
// > An asterisk "*" matches anything except a slash.
// 2.
// > Other consecutive asterisks are considered regular asterisks
// > and will match according to the previous rules.
const unescaped = p2.replace(/\\\*/g, '[^\\/]*')
return p1 + unescaped
}
],
[
// 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)
&& !REGEX_INVALID_TRAILING_BACKSLASH.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> | 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 <https://github.com/jonschlinkert/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 <https://github.com/jonschlinkert/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 <https://github.com/jonschlinkert/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 = '<![A-Z]+\\s+[^>]*>';
var cdata = '<!\\[CDATA\\[[\\s\\S]*?\\]\\]>';
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 = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;'
};
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:
// İ, ϴ, ẞ, Ω, , Å - 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;<compat> 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398
// 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L;<compat> 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
* (`<br />`). 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 `<br>`.
* - __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 <pre... internal wrapper is skipped.
*
* ##### Example
*
* ```javascript
* // commonmark mode
* var md = require('markdown-it')('commonmark');
*
* // default mode
* var md = require('markdown-it')();
*
* // enable everything
* var md = require('markdown-it')({
* html: true,
* linkify: true,
* typographer: true
* });
* ```
*
* ##### Syntax highlighting
*
* ```js
* var hljs = require('highlight.js') // https://highlightjs.org/
*
* 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 ''; // use external default escaping
* }
* });
* ```
*
* Or with full wrapper override (if you need assign class to `<pre>`):
*
* ```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 '<pre class="hljs"><code>' +
* hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
* '</code></pre>';
* } catch (__) {}
* }
*
* return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
* }
* });
* ```
*
**/
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 `<p>` 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 (<br />)
breaks: false, // Convert '\n' in paragraphs into <br>
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 <pre... internal wrapper is skipped.
//
// function (/*str, lang*/) { return ''; }
//
highlight: null,
maxNesting: 20 // Internal protection, recursion limit
},
components: {
core: {
rules: [
'normalize',
'block',
'inline',
'text_join'
]
},
block: {
rules: [
'blockquote',
'code',
'fence',
'heading',
'hr',
'html_block',
'lheading',
'list',
'reference',
'paragraph'
]
},
inline: {
rules: [
'autolink',
'backticks',
'emphasis',
'entity',
'escape',
'html_inline',
'image',
'link',
'newline',
'text'
],
rules2: [
'balance_pairs',
'emphasis',
'fragments_join'
]
}
}
};
/***/ }),
/***/ 1007:
/***/ ((module) => {
"use strict";
// markdown-it default options
module.exports = {
options: {
html: false, // Enable HTML tags in source
xhtmlOut: false, // Use '/' to close single tags (<br />)
breaks: false, // Convert '\n' in paragraphs into <br>
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 <pre... internal wrapper is skipped.
//
// function (/*str, lang*/) { return ''; }
//
highlight: null,
maxNesting: 100 // Internal protection, recursion limit
},
components: {
core: {},
block: {},
inline: {}
}
};
/***/ }),
/***/ 6719:
/***/ ((module) => {
"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 (<br />)
breaks: false, // Convert '\n' in paragraphs into <br>
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 <pre... internal wrapper is skipped.
//
// function (/*str, lang*/) { return ''; }
//
highlight: null,
maxNesting: 20 // Internal protection, recursion limit
},
components: {
core: {
rules: [
'normalize',
'block',
'inline',
'text_join'
]
},
block: {
rules: [
'paragraph'
]
},
inline: {
rules: [
'text'
],
rules2: [
'balance_pairs',
'fragments_join'
]
}
}
};
/***/ }),
/***/ 3041:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"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 '<code' + slf.renderAttrs(token) + '>' +
escapeHtml(tokens[idx].content) +
'</code>';
};
default_rules.code_block = function (tokens, idx, options, env, slf) {
var token = tokens[idx];
return '<pre' + slf.renderAttrs(token) + '><code>' +
escapeHtml(tokens[idx].content) +
'</code></pre>\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('<pre') === 0) {
return highlighted + '\n';
}
// If language exists, inject class gently, without modifying original token.
// May be, one day we will add .deepClone() for token and simplify this part, but
// now we prefer to keep things local.
if (info) {
i = token.attrIndex('class');
tmpAttrs = token.attrs ? token.attrs.slice() : [];
if (i < 0) {
tmpAttrs.push([ 'class', options.langPrefix + langName ]);
} else {
tmpAttrs[i] = tmpAttrs[i].slice();
tmpAttrs[i][1] += ' ' + options.langPrefix + langName;
}
// Fake token just to render attributes
tmpToken = {
attrs: tmpAttrs
};
return '<pre><code' + slf.renderAttrs(tmpToken) + '>'
+ highlighted
+ '</code></pre>\n';
}
return '<pre><code' + slf.renderAttrs(token) + '>'
+ highlighted
+ '</code></pre>\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 ? '<br />\n' : '<br>\n';
};
default_rules.softbreak = function (tokens, idx, options /*, env */) {
return options.breaks ? (options.xhtmlOut ? '<br />\n' : '<br>\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 '<b>'; };
* md.renderer.rules.strong_close = function () { return '</b>'; };
*
* 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. `<img`
result += (token.nesting === -1 ? '</' : '<') + token.tag;
// Encode attributes, e.g. `<img src="foo"`
result += this.renderAttrs(token);
// Add a slash for self-closing tags, e.g. `<img src="foo" /`
if (token.nesting === 0 && options.xhtmlOut) {
result += ' /';
}
// Check if we need to add a newline after this tag
if (token.block) {
needLf = true;
if (token.nesting === 1) {
if (idx + 1 < tokens.length) {
nextToken = tokens[idx + 1];
if (nextToken.type === 'inline' || nextToken.hidden) {
// Block-level tag containing an inline tag.
//
needLf = false;
} else if (nextToken.nesting === -1 && nextToken.tag === token.tag) {
// Opening tag + closing tag of the same type. E.g. `<li></li>`.
//
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 ],
[ /^<![A-Z]/, />/, true ],
[ /^<!\[CDATA\[/, /\]\]>/, true ],
[ new RegExp('^</?(' + block_names.join('|') + ')(?=(\\s|/?>|$))', '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 /^<a[>\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:<a href="//example.com/">//example.com/</a>
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 ?.... → ?.., !.... → !..)
// ???????? → ???, !!!!! → !!!, `,,` → `,`
// -- → &ndash;, --- → &mdash;
//
// 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 '<protocol:...>'
/*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.
//
// `<em><em>whatever</em></em>` -> `<strong>whatever</strong>`
//
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 - &#123;, &#xAF;, &quot;, ...
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 /^<a[>\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](<src> "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]( <href> "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]( <href> "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]( <href> "title" )
// ^^ skipping these spaces
start = pos;
for (; pos < max; pos++) {
code = state.src.charCodeAt(pos);
if (!isSpace(code) && code !== 0x0A) { break; }
}
// [link]( <href> "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]( <href> "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](<to> "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]( <href> "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]( <href> "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]( <href> "title" )
// ^^ skipping these spaces
start = pos;
for (; pos < max; pos++) {
code = state.src.charCodeAt(pos);
if (!isSpace(code) && code !== 0x0A) { break; }
}
// [link]( <href> "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]( <href> "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 <a> 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\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
/(<!--\s*markdownlint-(disable|enable|capture|restore|disable-file|enable-file|disable-line|disable-next-line|configure-file))(?:\s|-->)/gi;
module.exports.inlineCommentStartRe = inlineCommentStartRe;
// Regular expression for matching HTML elements
const htmlElementRe = /<(([A-Za-z][A-Za-z\d-]*)(?:\s[^`>]*)?)\/?>/g;
module.exports.htmlElementRe = htmlElementRe;
// Regular expressions for range matching
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 endComment = "-->";
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<a, 0 otherwise.
*/
module.exports.numericSortAscending = function numericSortAscending(a, b) {
return a - b;
};
// Returns true iff the sorted array contains the specified element
module.exports.includesSorted = function includesSorted(array, element) {
let left = 0;
let right = array.length - 1;
while (left <= right) {
// eslint-disable-next-line no-bitwise
const mid = (left + right) >> 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 = "<!--";
const htmlCommentEnd = "-->";
const safeCommentCharacter = ".";
const startsWithPipeRe = /^ *\|/;
const notCrLfRe = /[^\r\n]/g;
const notSpaceCrLfRe = /[^ \r\n]/g;
const trailingSpaceRe = / +[\r\n]/g;
const replaceTrailingSpace = (s) => s.replace(notCrLfRe, safeCommentCharacter);
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) {
const content = text.slice(i + htmlCommentBegin.length, j);
const lastLf = text.lastIndexOf("\n", i) + 1;
const preText = text.slice(lastLf, i);
const isBlock = preText.trim().length === 0;
const couldBeTable = startsWithPipeRe.test(preText);
const spansTableCells = couldBeTable && content.includes("\n");
const isValid =
isBlock ||
!(
spansTableCells ||
content.startsWith(">") ||
content.startsWith("->") ||
content.endsWith("-") ||
content.includes("--")
);
// If a valid block/inline comment...
if (isValid) {
const clearedContent = content
.replace(notSpaceCrLfRe, safeCommentCharacter)
.replace(trailingSpaceRe, replaceTrailingSpace);
text =
text.slice(0, i + htmlCommentBegin.length) +
clearedContent +
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.
*
* @param {Object} params RuleParams instance.
* @param {string} type Token type identifier.
* @param {Function} handler Callback function.
* @returns {void}
*/
function forEachInlineChild(params, type, handler) {
filterTokens(params, "inline", (token) => {
for (const child of token.children.filter((c) => c.type === type)) {
handler(child, token);
}
});
}
module.exports.forEachInlineChild = forEachInlineChild;
// 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 = [];
// Match with htmlElementRe
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 ]);
}
});
// Match with html_inline
forEachInlineChild(params, "html_inline", (token, parent) => {
const parentContent = parent.content;
let tokenContent = token.content;
const parentIndex = parentContent.indexOf(tokenContent);
let deltaLines = 0;
let indent = 0;
for (let i = parentIndex - 1; i >= 0; i--) {
if (parentContent[i] === "\n") {
deltaLines++;
} else if (deltaLines === 0) {
indent++;
}
}
let lineIndex = token.lineNumber - 1 + deltaLines;
do {
const index = tokenContent.indexOf("\n");
const length = (index === -1) ? tokenContent.length : index;
exclusions.push([ lineIndex, indent, length ]);
tokenContent = tokenContent.slice(length + 1);
lineIndex++;
indent = 0;
} while (tokenContent.length > 0);
});
// Return results
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 Map();
const definitions = new Map();
const duplicateDefinitions = [];
const definitionLineIndices = [];
// 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);
}
const labelLength = linkReferenceDefinitionMatch[0].length;
exclusions.push([ 0, lineOffsets[lineIndex], labelLength ]);
const hasDefinition = line.slice(labelLength).trim().length > 0;
definitionLineIndices.push(lineIndex);
if (!hasDefinition) {
definitionLineIndices.push(lineIndex + 1);
}
}
}
});
// 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);
const referenceDatum = [
lineIndex,
referenceIndex,
matchString.length,
matchText.length,
(matchLabel || "").length
];
if (shortcutLink) {
// Track separately due to ambiguity in "text [text] text"
const shortcutData = shortcuts.get(label) || [];
shortcutData.push(referenceDatum);
shortcuts.set(label, shortcutData);
} else {
// Track reference and location
const referenceData = references.get(label) || [];
referenceData.push(referenceDatum);
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,
definitionLineIndices
};
}
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__(612));
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;
/**
* RegExp.exec-style implementation of function expressions.
*
* @param {Function} funcExp Function that takes string and returns
* [index, length] or null.
* @param {string} input String to search.
* @returns {string[] | null} RegExp.exec-style [match] with an index property.
*/
function funcExpExec(funcExp, input) {
// Start or resume match
// @ts-ignore
const lastIndex = funcExp.lastIndex || 0;
const result = funcExp(input.slice(lastIndex));
if (result) {
// Update lastIndex and return match
const [ subIndex, length ] = result;
const index = lastIndex + subIndex;
// @ts-ignore
funcExp.lastIndex = index + length;
const match = [ input.slice(index, index + length) ];
// @ts-ignore
match.index = index;
return match;
}
// Reset lastIndex and return no match
// @ts-ignore
funcExp.lastIndex = 0;
return null;
}
module.exports.funcExpExec = funcExpExec;
const urlFeProtocolRe = /(?:http|ftp)s?:\/\//i;
const urlFeAutolinkTerminalsRe = / |$/;
const urlFeBareTerminalsRe = /[ ,!`'"\]]|$/;
const urlFeNonTerminalsRe = "-#/";
const urlFePunctuationRe = /\p{Punctuation}/u;
const urlFePrefixToPostfix = new Map([
[ " ", " " ],
[ "`", "`" ],
[ "'", "'" ],
[ "\"", "\"" ],
[ "", "" ],
[ "“", "”" ],
[ "«", "»" ],
[ "*", "*" ],
[ "_", "_" ],
[ "(", ")" ],
[ "[", "]" ],
[ "{", "}" ],
[ "<", ">" ],
[ ">", "<" ]
]);
/**
* Function expression that matches URLs.
*
* @param {string} input Substring to search for a URL.
* @returns {Array | null} [index, length] of URL or null.
*/
function urlFe(input) {
// Find start of URL by searching for protocol
const match = input.match(urlFeProtocolRe);
if (match) {
// Look for matching pre/postfix characters (ex: <...>)
const start = match.index || 0;
const length = match[0].length;
const prefix = input[start - 1] || " ";
const postfix = urlFePrefixToPostfix.get(prefix);
// @ts-ignore
let endPostfix = input.indexOf(postfix, start + length);
if (endPostfix === -1) {
endPostfix = input.length;
}
// Look for characters that terminate a URL
const terminalsRe =
(prefix === "<") ? urlFeAutolinkTerminalsRe : urlFeBareTerminalsRe;
const endTerminal = start + input.slice(start).search(terminalsRe);
// Determine tentative end of URL
let end = Math.min(endPostfix, endTerminal);
if (prefix === " ") {
// If the URL used " " as pre/postfix characters, trim the end
if (input[end - 1] === ")") {
// Trim any ")" beyond the last "(...)" pair
const lastOpenParen = input.lastIndexOf("(", end - 2);
if (lastOpenParen <= start) {
end--;
} else {
const nextCloseParen = input.indexOf(")", lastOpenParen + 1);
end = nextCloseParen + 1;
}
} else {
// Trim unwanted punctuation
while (
!urlFeNonTerminalsRe.includes(input[end - 1]) &&
urlFePunctuationRe.test(input[end - 1])
) {
end--;
}
}
}
return [ start, end - start ];
}
// No match
return null;
}
module.exports.urlFe = urlFe;
/***/ }),
/***/ 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<string>} `list` List of strings to match.
* @param {String|Array<string>} `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 <https://feross.org/opensource> */
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 <https://feross.org/opensource> */
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 <https://github.com/micromatch/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");
/***/ }),
/***/ 7261:
/***/ ((module) => {
"use strict";
module.exports = require("node:util");
/***/ }),
/***/ 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.6.0";
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 no-inline-comments
await Promise.resolve(/* import() eager */).then(__nccwpck_require__.bind(__nccwpck_require__, 6177));
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 no-inline-comments
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 no-inline-comments
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, yamlParse ],
"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.fixableRuleNames = [
"MD004", "MD005", "MD006", "MD007", "MD009", "MD010",
"MD011", "MD012", "MD014", "MD018", "MD019", "MD020",
"MD021", "MD022", "MD023", "MD026", "MD027", "MD030",
"MD031", "MD032", "MD034", "MD037", "MD038", "MD039",
"MD044", "MD047", "MD049", "MD050", "MD051", "MD053"
];
module.exports.homepage = "https://github.com/DavidAnson/markdownlint";
module.exports.version = "0.27.0";
/***/ }),
/***/ 8397:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const path = __nccwpck_require__(9411);
const { promisify } = __nccwpck_require__(7261);
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.<string, string[]>} 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.<string, string[]>} 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.<string, string[]>} 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__(7561);
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<LintResults>} 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__(7561);
}
// Read file
const os = __nccwpck_require__(612);
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>} 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__(7561);
}
// Read file
const os = __nccwpck_require__(612);
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.<string, string>} [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.<string, LintError[]>} 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.<string, RuleConfiguration>} 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),
undefined,
[ 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 } = __nccwpck_require__(2935);
const { lineMetadata, referenceLinkImageData } = __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);
}
});
const { definitionLineIndices } = referenceLinkImageData();
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) &&
!includesSorted(definitionLineIndices, lineIndex) &&
(strict ||
(!(stern && sternModeRe.test(line)) &&
!includesSorted(linkOnlyLineNumbers, lineNumber))) &&
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, blockquotePrefixRe, filterTokens, isBlankLine } =
__nccwpck_require__(2935);
const getBlockQuote = (str, count) => (
(str || "")
.match(blockquotePrefixRe)[0]
.trimEnd()
// eslint-disable-next-line unicorn/prefer-spread
.concat("\n")
.repeat(count)
);
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":
getBlockQuote(lines[topIndex - 1], linesAbove - actualAbove)
});
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":
getBlockQuote(lines[nextIndex], linesBelow - actualBelow)
});
});
}
};
/***/ }),
/***/ 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 = /&#?[\da-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, referenceLinkImageData } =
__nccwpck_require__(2260);
const linkDestinationRe = /\]\(\s*$/;
// See https://spec.commonmark.org/0.29/#autolinks
const emailAddressRe =
// eslint-disable-next-line max-len
/^[\w.!#$%&'*+/=?^`{|}~-]+@[a-zA-Z\d](?:[a-zA-Z\d-]{0,61}[a-zA-Z\d])?(?:\.[a-zA-Z\d](?:[a-zA-Z\d-]{0,61}[a-zA-Z\d])?)*$/;
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();
const { references, definitionLineIndices } = referenceLinkImageData();
for (const datas of references.values()) {
for (const data of datas) {
const [ lineIndex, index, , textLength, labelLength ] = data;
if (labelLength > 0) {
exclusions.push([ lineIndex, index + 3 + textLength, labelLength ]);
}
}
}
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, tag.length) &&
!definitionLineIndices.includes(lineIndex)
) {
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, filterTokens, funcExpExec, urlFe, withinAnyRange } =
__nccwpck_require__(2935);
const { codeBlockAndSpanRanges, htmlElementRanges, referenceLinkImageData } =
__nccwpck_require__(2260);
const htmlLinkRe = /<a(?:\s[^>]*)?>[^<>]*<\/a\s*>/gi;
module.exports = {
"names": [ "MD034", "no-bare-urls" ],
"description": "Bare URL used",
"tags": [ "links", "url" ],
"function": function MD034(params, onError) {
const { lines } = params;
const codeExclusions = [
...codeBlockAndSpanRanges(),
...htmlElementRanges()
];
filterTokens(params, "html_block", (token) => {
for (let i = token.map[0]; i < token.map[1]; i++) {
codeExclusions.push([ i, 0, lines[i].length ]);
}
});
const { definitionLineIndices } = referenceLinkImageData();
for (const [ lineIndex, line ] of lines.entries()) {
if (definitionLineIndices[0] === lineIndex) {
definitionLineIndices.shift();
} else {
let match = null;
const lineExclusions = [];
while ((match = htmlLinkRe.exec(line)) !== null) {
lineExclusions.push([ lineIndex, match.index, match[0].length ]);
}
while ((match = funcExpExec(urlFe, line)) !== null) {
const [ bareUrl ] = match;
// @ts-ignore
const matchIndex = match.index;
const bareUrlLength = bareUrl.length;
const prefix = line.slice(0, matchIndex);
const postfix = line.slice(matchIndex + bareUrlLength);
if (
// Allow <...> to avoid reporting non-bare links
!(prefix.endsWith("<") && postfix.startsWith(">")) &&
// Allow >...</ to avoid reporting <code>...</code>
!(prefix.endsWith(">") && postfix.startsWith("</")) &&
// Allow "..." and '...' to allow quoting a bare link
!(prefix.endsWith("\"") && postfix.startsWith("\"")) &&
!(prefix.endsWith("'") && postfix.startsWith("'")) &&
// Allow ](... to avoid reporting Markdown-style links
!(/\]\(\s*$/.test(prefix)) &&
// Allow [...] to avoid MD011/no-reversed-links and nested links
!(/\[[^\]]*$/.test(prefix) && /^[^[]*\]/.test(postfix)) &&
!withinAnyRange(
lineExclusions, lineIndex, matchIndex, bareUrlLength
) &&
!withinAnyRange(
codeExclusions, lineIndex, matchIndex, bareUrlLength
)
) {
const range = [
matchIndex + 1,
bareUrlLength
];
const fixInfo = {
"editColumn": range[0],
"deleteCount": range[1],
"insertText": `<${bareUrl}>`
};
addErrorContext(
onError,
lineIndex + 1,
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]+$/);
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 = /(^|[^\\]|\\\\)(?:(\*{1,3})|(_{1,3}))/g;
const embeddedUnderscoreRe = /([A-Za-z\d])_([A-Za-z\d])/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)\](?=(\([^)]*\)|\[[^\]]*\]))/;
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 { addError, 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) {
let allowed = params.config.allowed_languages;
allowed = Array.isArray(allowed) ? allowed : [];
const languageOnly = !!params.config.language_only;
filterTokens(params, "fence", function forToken(token) {
const lang = token.info.trim().split(/\s+/u).shift();
if (lang === "") {
addErrorContext(onError, token.lineNumber, token.line);
} else if ((allowed.length > 0) && !allowed.includes(lang)) {
addError(
onError,
token.lineNumber,
`"${lang}" is not allowed`
);
}
if (languageOnly && (token.info !== lang)) {
addError(
onError,
token.lineNumber,
`Info string contains more than language: "${token.info}"`
);
}
});
}
};
/***/ }),
/***/ 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(`^<h${level}[ />]`, "i");
params.tokens.every((token) => {
let isError = false;
if (token.type === "html_block") {
if (token.content.startsWith("<!--")) {
// Ignore leading HTML comments
return true;
} else if (!htmlHeadingRe.test(token.content)) {
// Something other than an HTML heading
isError = true;
}
} else if ((token.type !== "heading_open") || (token.tag !== tag)) {
// Something other than a Markdown heading
isError = true;
}
if (isError) {
addErrorContext(onError, token.lineNumber, token.line);
}
return false;
});
}
}
};
/***/ }),
/***/ 7022:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addErrorContext, escapeForRegExp, filterTokens } =
__nccwpck_require__(2935);
module.exports = {
"names": [ "MD042", "no-empty-links" ],
"description": "No empty links",
"tags": [ "links" ],
"function": function MD042(params, onError) {
filterTokens(params, "inline", function forToken(token) {
let inLink = false;
let linkText = "";
let emptyLink = false;
for (const child of token.children) {
if (child.type === "link_open") {
inLink = true;
linkText = "";
for (const attr of child.attrs) {
if (attr[0] === "href" && (!attr[1] || (attr[1] === "#"))) {
emptyLink = true;
}
}
} else if (child.type === "link_close") {
inLink = false;
if (emptyLink) {
let context = `[${linkText}]`;
let range = null;
const match = child.line.match(
new RegExp(`${escapeForRegExp(context)}\\((?:|#|<>)\\)`)
);
if (match) {
context = match[0];
range = [ match.index + 1, match[0].length ];
}
addErrorContext(
onError, child.lineNumber, context, null, null, range
);
emptyLink = false;
}
} else if (inLink) {
linkText += child.content;
}
}
});
}
};
/***/ }),
/***/ 9539:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addErrorContext, addErrorDetailIf, forEachHeading } =
__nccwpck_require__(2935);
module.exports = {
"names": [ "MD043", "required-headings", "required-headers" ],
"description": "Required heading structure",
"tags": [ "headings", "headers" ],
"function": function MD043(params, onError) {
const requiredHeadings = params.config.headings || params.config.headers;
const matchCase = params.config.match_case || false;
if (Array.isArray(requiredHeadings)) {
const levels = {};
for (const level of [ 1, 2, 3, 4, 5, 6 ]) {
levels["h" + level] = "######".substr(-level);
}
let i = 0;
let matchAny = false;
let hasError = false;
let anyHeadings = false;
const getExpected = () => requiredHeadings[i++] || "[None]";
const handleCase = (str) => (matchCase ? str : str.toLowerCase());
forEachHeading(params, (heading, content) => {
if (!hasError) {
anyHeadings = true;
const actual = levels[heading.tag] + " " + content;
const expected = getExpected();
if (expected === "*") {
const nextExpected = getExpected();
if (handleCase(nextExpected) !== handleCase(actual)) {
matchAny = true;
i--;
}
} else if (expected === "+") {
matchAny = true;
} else if (handleCase(expected) === handleCase(actual)) {
matchAny = false;
} else if (matchAny) {
i--;
} else {
addErrorDetailIf(onError, heading.lineNumber,
expected, actual);
hasError = true;
}
}
});
const extraHeadings = requiredHeadings.length - i;
if (
!hasError &&
((extraHeadings > 1) ||
((extraHeadings === 1) && (requiredHeadings[i] !== "*"))) &&
(anyHeadings || !requiredHeadings.every((heading) => heading === "*"))
) {
addErrorContext(onError, params.lines.length,
requiredHeadings[i]);
}
}
}
};
/***/ }),
/***/ 9992:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addErrorDetailIf, escapeForRegExp, forEachLine, forEachLink,
funcExpExec, linkReferenceDefinitionRe, urlFe, withinAnyRange } =
__nccwpck_require__(2935);
const { codeBlockAndSpanRanges, htmlElementRanges, lineMetadata } =
__nccwpck_require__(2260);
module.exports = {
"names": [ "MD044", "proper-names" ],
"description": "Proper names should have the correct capitalization",
"tags": [ "spelling" ],
"function": function MD044(params, onError) {
let names = params.config.names;
names = Array.isArray(names) ? names : [];
names.sort((a, b) => (b.length - a.length) || a.localeCompare(b));
const codeBlocks = params.config.code_blocks;
const includeCodeBlocks =
(codeBlocks === undefined) ? true : !!codeBlocks;
const htmlElements = params.config.html_elements;
const includeHtmlElements =
(htmlElements === undefined) ? true : !!htmlElements;
const exclusions = [];
forEachLine(lineMetadata(), (line, lineIndex) => {
if (linkReferenceDefinitionRe.test(line)) {
exclusions.push([ lineIndex, 0, line.length ]);
} else {
let match = null;
while ((match = funcExpExec(urlFe, line)) !== null) {
// @ts-ignore
exclusions.push([ lineIndex, match.index, match[0].length ]);
}
forEachLink(line, (index, _, text, destination) => {
if (destination) {
exclusions.push(
[ lineIndex, index + text.length, destination.length ]
);
}
});
}
});
if (!includeCodeBlocks) {
exclusions.push(...codeBlockAndSpanRanges());
}
if (!includeHtmlElements) {
exclusions.push(...htmlElementRanges());
}
for (const name of names) {
const escapedName = escapeForRegExp(name);
const startNamePattern = /^\W/.test(name) ? "" : "\\b_*";
const endNamePattern = /\W$/.test(name) ? "" : "_*\\b";
const namePattern =
`(${startNamePattern})(${escapedName})${endNamePattern}`;
const nameRe = new RegExp(namePattern, "gi");
forEachLine(lineMetadata(), (line, lineIndex, inCode, onFence) => {
if (includeCodeBlocks || (!inCode && !onFence)) {
let match = null;
while ((match = nameRe.exec(line)) !== null) {
const [ , leftMatch, nameMatch ] = match;
const index = match.index + leftMatch.length;
const length = nameMatch.length;
if (
!withinAnyRange(exclusions, lineIndex, index, length) &&
!names.includes(nameMatch)
) {
addErrorDetailIf(
onError,
lineIndex + 1,
name,
nameMatch,
null,
null,
[ index + 1, length ],
{
"editColumn": index + 1,
"deleteCount": length,
"insertText": name
}
);
}
exclusions.push([ lineIndex, index, length ]);
}
}
});
}
}
};
/***/ }),
/***/ 5239:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addError, forEachInlineChild } = __nccwpck_require__(2935);
module.exports = {
"names": [ "MD045", "no-alt-text" ],
"description": "Images should have alternate text (alt text)",
"tags": [ "accessibility", "images" ],
"function": function MD045(params, onError) {
forEachInlineChild(params, "image", function forToken(token) {
if (token.content === "") {
addError(onError, token.lineNumber);
}
});
}
};
/***/ }),
/***/ 4843:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addErrorDetailIf } = __nccwpck_require__(2935);
const tokenTypeToStyle = {
"fence": "fenced",
"code_block": "indented"
};
module.exports = {
"names": [ "MD046", "code-block-style" ],
"description": "Code block style",
"tags": [ "code" ],
"function": function MD046(params, onError) {
let expectedStyle = String(params.config.style || "consistent");
const codeBlocksAndFences = params.tokens.filter(
(token) => (token.type === "code_block") || (token.type === "fence")
);
for (const token of codeBlocksAndFences) {
const { lineNumber, type } = token;
if (expectedStyle === "consistent") {
expectedStyle = tokenTypeToStyle[type];
}
addErrorDetailIf(
onError,
lineNumber,
expectedStyle,
tokenTypeToStyle[type]);
}
}
};
/***/ }),
/***/ 8345:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addError, isBlankLine } = __nccwpck_require__(2935);
module.exports = {
"names": [ "MD047", "single-trailing-newline" ],
"description": "Files should end with a single newline character",
"tags": [ "blank_lines" ],
"function": function MD047(params, onError) {
const lastLineNumber = params.lines.length;
const lastLine = params.lines[lastLineNumber - 1];
if (!isBlankLine(lastLine)) {
addError(
onError,
lastLineNumber,
null,
null,
[ lastLine.length, 1 ],
{
"insertText": "\n",
"editColumn": lastLine.length + 1
}
);
}
}
};
/***/ }),
/***/ 9755:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addErrorDetailIf, fencedCodeBlockStyleFor } = __nccwpck_require__(2935);
module.exports = {
"names": [ "MD048", "code-fence-style" ],
"description": "Code fence style",
"tags": [ "code" ],
"function": function MD048(params, onError) {
const style = String(params.config.style || "consistent");
let expectedStyle = style;
const fenceTokens = params.tokens.filter((token) => token.type === "fence");
for (const fenceToken of fenceTokens) {
const { lineNumber, markup } = fenceToken;
if (expectedStyle === "consistent") {
expectedStyle = fencedCodeBlockStyleFor(markup);
}
addErrorDetailIf(
onError,
lineNumber,
expectedStyle,
fencedCodeBlockStyleFor(markup)
);
}
}
};
/***/ }),
/***/ 7390:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addError, emphasisOrStrongStyleFor, forEachInlineChild,
getNextChildToken, getRangeAndFixInfoIfFound } = __nccwpck_require__(2935);
const impl = (params, onError, tagPrefix, asterisk, underline, style) => {
let lastLineNumber = -1;
const instances = new Map();
forEachInlineChild(params, `${tagPrefix}_open`, (token, parent) => {
const { lineNumber, markup } = token;
const markupStyle = emphasisOrStrongStyleFor(markup);
if (style === "consistent") {
style = markupStyle;
}
if (style !== markupStyle) {
let rangeAndFixInfo = {};
const contentToken = getNextChildToken(
parent, token, "text", `${tagPrefix}_close`
);
if (contentToken) {
const { content } = contentToken;
const actual = `${markup}${content}${markup}`;
const expectedMarkup =
(style === "asterisk") ? asterisk : underline;
const expected = `${expectedMarkup}${content}${expectedMarkup}`;
if (lastLineNumber !== lineNumber) {
lastLineNumber = lineNumber;
instances.clear();
}
const instance = (instances.get(expected) || 0) + 1;
instances.set(expected, instance);
rangeAndFixInfo = getRangeAndFixInfoIfFound(
params.lines,
lineNumber - 1,
actual,
expected,
instance
);
}
addError(
onError,
lineNumber,
`Expected: ${style}; Actual: ${markupStyle}`,
null,
rangeAndFixInfo.range,
rangeAndFixInfo.fixInfo
);
}
});
};
module.exports = [
{
"names": [ "MD049", "emphasis-style" ],
"description": "Emphasis style should be consistent",
"tags": [ "emphasis" ],
"function": function MD049(params, onError) {
const style = String(params.config.style || "consistent");
return impl(params, onError, "em", "*", "_", style);
}
},
{
"names": [ "MD050", "strong-style" ],
"description": "Strong style should be consistent",
"tags": [ "emphasis" ],
"function": function MD050(params, onError) {
const style = String(params.config.style || "consistent");
return impl(params, onError, "strong", "**", "__", style);
}
}
];
/***/ }),
/***/ 6469:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addError, addErrorDetailIf, escapeForRegExp, filterTokens,
forEachInlineChild, forEachHeading, htmlElementRe } = __nccwpck_require__(2935);
// Regular expression for identifying HTML anchor names
const idRe = /\sid\s*=\s*['"]?([^'"\s>]+)/iu;
const nameRe = /\sname\s*=\s*['"]?([^'"\s>]+)/iu;
/**
* Converts a Markdown heading into an HTML fragment according to the rules
* used by GitHub.
*
* @param {Object} inline Inline token for heading.
* @returns {string} Fragment string for heading.
*/
function convertHeadingToHTMLFragment(inline) {
const inlineText = inline.children
.filter((token) => token.type !== "html_inline")
.map((token) => token.content)
.join("");
return "#" + encodeURIComponent(
inlineText
.toLowerCase()
// RegExp source with Ruby's \p{Word} expanded into its General Categories
// eslint-disable-next-line max-len
// https://github.com/gjtorikian/html-pipeline/blob/main/lib/html/pipeline/toc_filter.rb
// https://ruby-doc.org/core-3.0.2/Regexp.html
.replace(
/[^\p{Letter}\p{Mark}\p{Number}\p{Connector_Punctuation}\- ]/gu,
""
)
.replace(/ /gu, "-")
);
}
module.exports = {
"names": [ "MD051", "link-fragments" ],
"description": "Link fragments should be valid",
"tags": [ "links" ],
"function": function MD051(params, onError) {
const fragments = new Map();
// Process headings
forEachHeading(params, (heading, content, inline) => {
const fragment = convertHeadingToHTMLFragment(inline);
const count = fragments.get(fragment) || 0;
if (count) {
fragments.set(`${fragment}-${count}`, 0);
}
fragments.set(fragment, count + 1);
});
// Process HTML anchors
const processHtmlToken = (token) => {
let match = null;
while ((match = htmlElementRe.exec(token.content)) !== null) {
const [ tag, , element ] = match;
const anchorMatch = idRe.exec(tag) ||
(element.toLowerCase() === "a" && nameRe.exec(tag));
if (anchorMatch) {
fragments.set(`#${anchorMatch[1]}`, 0);
}
}
};
filterTokens(params, "html_block", processHtmlToken);
forEachInlineChild(params, "html_inline", processHtmlToken);
// Process link fragments
forEachInlineChild(params, "link_open", (token) => {
const { attrs, lineNumber, line } = token;
const href = attrs.find((attr) => attr[0] === "href");
const id = href && href[1];
if (id && (id.length > 1) && (id[0] === "#") && !fragments.has(id)) {
let context = id;
let range = null;
let fixInfo = null;
const match = line.match(
new RegExp(`\\[.*?\\]\\(${escapeForRegExp(context)}\\)`)
);
if (match) {
[ context ] = match;
const index = match.index;
const length = context.length;
range = [ index + 1, length ];
fixInfo = {
"editColumn": index + (length - id.length),
"deleteCount": id.length,
"insertText": null
};
}
const idLower = id.toLowerCase();
const mixedCaseKey = [ ...fragments.keys() ]
.find((key) => idLower === key.toLowerCase());
if (mixedCaseKey) {
(fixInfo || {}).insertText = mixedCaseKey;
addErrorDetailIf(
onError,
lineNumber,
mixedCaseKey,
id,
undefined,
context,
range,
fixInfo
);
} else {
addError(
onError,
lineNumber,
undefined,
context,
// @ts-ignore
range
);
}
}
});
}
};
/***/ }),
/***/ 1210:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addError } = __nccwpck_require__(2935);
const { referenceLinkImageData } = __nccwpck_require__(2260);
module.exports = {
"names": [ "MD052", "reference-links-images" ],
"description":
"Reference links and images should use a label that is defined",
"tags": [ "images", "links" ],
"function": function MD052(params, onError) {
const { lines } = params;
const { references, definitions } = referenceLinkImageData();
// Look for links/images that use an undefined link reference
for (const reference of references.entries()) {
const [ label, datas ] = reference;
if (!definitions.has(label)) {
for (const data of datas) {
const [ lineIndex, index, length ] = data;
// Context will be incomplete if reporting for a multi-line link
const context = lines[lineIndex].slice(index, index + length);
addError(
onError,
lineIndex + 1,
`Missing link or image reference definition: "${label}"`,
context,
[ index + 1, context.length ]
);
}
}
}
}
};
/***/ }),
/***/ 8815:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { addError, ellipsify, linkReferenceDefinitionRe } =
__nccwpck_require__(2935);
const { referenceLinkImageData } = __nccwpck_require__(2260);
module.exports = {
"names": [ "MD053", "link-image-reference-definitions" ],
"description": "Link and image reference definitions should be needed",
"tags": [ "images", "links" ],
"function": function MD053(params, onError) {
const ignored = new Set(params.config.ignored_definitions || [ "//" ]);
const lines = params.lines;
const { references, shortcuts, definitions, duplicateDefinitions } =
referenceLinkImageData();
const singleLineDefinition = (line) => (
line.replace(linkReferenceDefinitionRe, "").trim().length > 0
);
const deleteFixInfo = {
"deleteCount": -1
};
// Look for unused link references (unreferenced by any link/image)
for (const definition of definitions.entries()) {
const [ label, lineIndex ] = definition;
if (
!ignored.has(label) &&
!references.has(label) &&
!shortcuts.has(label)
) {
const line = lines[lineIndex];
addError(
onError,
lineIndex + 1,
`Unused link or image reference definition: "${label}"`,
ellipsify(line),
[ 1, line.length ],
singleLineDefinition(line) ? deleteFixInfo : 0
);
}
}
// Look for duplicate link references (defined more than once)
for (const duplicateDefinition of duplicateDefinitions) {
const [ label, lineIndex ] = duplicateDefinition;
if (!ignored.has(label)) {
const line = lines[lineIndex];
addError(
onError,
lineIndex + 1,
`Duplicate link or image reference definition: "${label}"`,
ellipsify(line),
[ 1, line.length ],
singleLineDefinition(line) ? deleteFixInfo : 0
);
}
}
}
};
/***/ }),
/***/ 1796:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
"use strict";
// @ts-check
const { homepage, version } = __nccwpck_require__(983);
const rules = [
__nccwpck_require__(9651),
__nccwpck_require__(4545),
__nccwpck_require__(9277),
__nccwpck_require__(3755),
__nccwpck_require__(3354),
__nccwpck_require__(725),
__nccwpck_require__(8121),
__nccwpck_require__(7315),
__nccwpck_require__(1016),
__nccwpck_require__(3753),
__nccwpck_require__(6454),
__nccwpck_require__(1518),
__nccwpck_require__(3463),
__nccwpck_require__(5496),
__nccwpck_require__(6478),
__nccwpck_require__(9915),
__nccwpck_require__(4898),
__nccwpck_require__(5164),
__nccwpck_require__(1829),
__nccwpck_require__(7177),
__nccwpck_require__(692),
__nccwpck_require__(1629),
__nccwpck_require__(6325),
__nccwpck_require__(7542),
__nccwpck_require__(3404),
__nccwpck_require__(2549),
__nccwpck_require__(2202),
__nccwpck_require__(3474),
__nccwpck_require__(77),
__nccwpck_require__(4721),
__nccwpck_require__(2997),
__nccwpck_require__(338),
__nccwpck_require__(2905),
__nccwpck_require__(6054),
__nccwpck_require__(8596),
__nccwpck_require__(320),
__nccwpck_require__(8679),
__nccwpck_require__(7022),
__nccwpck_require__(9539),
__nccwpck_require__(9992),
__nccwpck_require__(5239),
__nccwpck_require__(4843),
__nccwpck_require__(8345),
__nccwpck_require__(9755),
...__nccwpck_require__(7390),
__nccwpck_require__(6469),
__nccwpck_require__(1210),
__nccwpck_require__(8815)
];
for (const rule of rules) {
const name = rule.names[0].toLowerCase();
// eslint-disable-next-line dot-notation
rule["information"] =
new URL(`${homepage}/blob/v${version}/doc/${name}.md`);
}
module.exports = rules;
/***/ }),
/***/ 8109:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Scalar = __nccwpck_require__(9338);
var resolveBlockMap = __nccwpck_require__(2986);
var resolveBlockSeq = __nccwpck_require__(2289);
var resolveFlowCollection = __nccwpck_require__(45);
function composeCollection(CN, ctx, token, tagToken, onError) {
let coll;
switch (token.type) {
case 'block-map': {
coll = resolveBlockMap.resolveBlockMap(CN, ctx, token, onError);
break;
}
case 'block-seq': {
coll = resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError);
break;
}
case 'flow-collection': {
coll = resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError);
break;
}
}
if (!tagToken)
return coll;
const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));
if (!tagName)
return coll;
// Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841
const Coll = coll.constructor;
if (tagName === '!' || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
const expType = Node.isMap(coll) ? 'map' : 'seq';
let tag = ctx.schema.tags.find(t => t.collection === expType && t.tag === tagName);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt && kt.collection === expType) {
ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
tag = kt;
}
else {
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);
coll.tag = tagName;
return coll;
}
}
const res = tag.resolve(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options);
const node = Node.isNode(res)
? res
: new Scalar.Scalar(res);
node.range = coll.range;
node.tag = tagName;
if (tag?.format)
node.format = tag.format;
return node;
}
exports.composeCollection = composeCollection;
/***/ }),
/***/ 5050:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Document = __nccwpck_require__(42);
var composeNode = __nccwpck_require__(8676);
var resolveEnd = __nccwpck_require__(1250);
var resolveProps = __nccwpck_require__(6985);
function composeDoc(options, directives, { offset, start, value, end }, onError) {
const opts = Object.assign({ _directives: directives }, options);
const doc = new Document.Document(undefined, opts);
const ctx = {
atRoot: true,
directives: doc.directives,
options: doc.options,
schema: doc.schema
};
const props = resolveProps.resolveProps(start, {
indicator: 'doc-start',
next: value ?? end?.[0],
offset,
onError,
startOnNewline: true
});
if (props.found) {
doc.directives.docStart = true;
if (value &&
(value.type === 'block-map' || value.type === 'block-seq') &&
!props.hasNewline)
onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');
}
doc.contents = value
? composeNode.composeNode(ctx, value, props, onError)
: composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
const contentEnd = doc.contents.range[2];
const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);
if (re.comment)
doc.comment = re.comment;
doc.range = [offset, contentEnd, re.offset];
return doc;
}
exports.composeDoc = composeDoc;
/***/ }),
/***/ 8676:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Alias = __nccwpck_require__(5639);
var composeCollection = __nccwpck_require__(8109);
var composeScalar = __nccwpck_require__(4766);
var resolveEnd = __nccwpck_require__(1250);
var utilEmptyScalarPosition = __nccwpck_require__(8781);
const CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError) {
const { spaceBefore, comment, anchor, tag } = props;
let node;
let isSrcToken = true;
switch (token.type) {
case 'alias':
node = composeAlias(ctx, token, onError);
if (anchor || tag)
onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');
break;
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
case 'block-scalar':
node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
break;
case 'block-map':
case 'block-seq':
case 'flow-collection':
node = composeCollection.composeCollection(CN, ctx, token, tag, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
break;
default: {
const message = token.type === 'error'
? token.message
: `Unsupported token (type: ${token.type})`;
onError(token, 'UNEXPECTED_TOKEN', message);
node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError);
isSrcToken = false;
}
}
if (anchor && node.anchor === '')
onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
if (token.type === 'scalar' && token.source === '')
node.comment = comment;
else
node.commentBefore = comment;
}
// @ts-expect-error Type checking misses meaning of isSrcToken
if (ctx.options.keepSourceTokens && isSrcToken)
node.srcToken = token;
return node;
}
function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
const token = {
type: 'scalar',
offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
indent: -1,
source: ''
};
const node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor) {
node.anchor = anchor.source.substring(1);
if (node.anchor === '')
onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');
}
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
node.comment = comment;
node.range[2] = end;
}
return node;
}
function composeAlias({ options }, { offset, source, end }, onError) {
const alias = new Alias.Alias(source.substring(1));
if (alias.source === '')
onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');
if (alias.source.endsWith(':'))
onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);
const valueEnd = offset + source.length;
const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
alias.range = [offset, valueEnd, re.offset];
if (re.comment)
alias.comment = re.comment;
return alias;
}
exports.composeEmptyNode = composeEmptyNode;
exports.composeNode = composeNode;
/***/ }),
/***/ 4766:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Scalar = __nccwpck_require__(9338);
var resolveBlockScalar = __nccwpck_require__(9485);
var resolveFlowScalar = __nccwpck_require__(7578);
function composeScalar(ctx, token, tagToken, onError) {
const { value, type, comment, range } = token.type === 'block-scalar'
? resolveBlockScalar.resolveBlockScalar(token, ctx.options.strict, onError)
: resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
const tagName = tagToken
? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))
: null;
const tag = tagToken && tagName
? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError)
: token.type === 'scalar'
? findScalarTagByTest(ctx, value, token, onError)
: ctx.schema[Node.SCALAR];
let scalar;
try {
const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);
scalar = Node.isScalar(res) ? res : new Scalar.Scalar(res);
}
catch (error) {
const msg = error instanceof Error ? error.message : String(error);
onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);
scalar = new Scalar.Scalar(value);
}
scalar.range = range;
scalar.source = value;
if (type)
scalar.type = type;
if (tagName)
scalar.tag = tagName;
if (tag.format)
scalar.format = tag.format;
if (comment)
scalar.comment = comment;
return scalar;
}
function findScalarTagByName(schema, value, tagName, tagToken, onError) {
if (tagName === '!')
return schema[Node.SCALAR]; // non-specific tag
const matchWithTest = [];
for (const tag of schema.tags) {
if (!tag.collection && tag.tag === tagName) {
if (tag.default && tag.test)
matchWithTest.push(tag);
else
return tag;
}
}
for (const tag of matchWithTest)
if (tag.test?.test(value))
return tag;
const kt = schema.knownTags[tagName];
if (kt && !kt.collection) {
// Ensure that the known tag is available for stringifying,
// but does not get used by default.
schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));
return kt;
}
onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');
return schema[Node.SCALAR];
}
function findScalarTagByTest({ directives, schema }, value, token, onError) {
const tag = schema.tags.find(tag => tag.default && tag.test?.test(value)) || schema[Node.SCALAR];
if (schema.compat) {
const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??
schema[Node.SCALAR];
if (tag.tag !== compat.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat.tag);
const msg = `Value may be parsed as either ${ts} or ${cs}`;
onError(token, 'TAG_RESOLVE_FAILED', msg, true);
}
}
return tag;
}
exports.composeScalar = composeScalar;
/***/ }),
/***/ 9493:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var directives = __nccwpck_require__(5400);
var Document = __nccwpck_require__(42);
var errors = __nccwpck_require__(4236);
var Node = __nccwpck_require__(1399);
var composeDoc = __nccwpck_require__(5050);
var resolveEnd = __nccwpck_require__(1250);
function getErrorPos(src) {
if (typeof src === 'number')
return [src, src + 1];
if (Array.isArray(src))
return src.length === 2 ? src : [src[0], src[1]];
const { offset, source } = src;
return [offset, offset + (typeof source === 'string' ? source.length : 1)];
}
function parsePrelude(prelude) {
let comment = '';
let atComment = false;
let afterEmptyLine = false;
for (let i = 0; i < prelude.length; ++i) {
const source = prelude[i];
switch (source[0]) {
case '#':
comment +=
(comment === '' ? '' : afterEmptyLine ? '\n\n' : '\n') +
(source.substring(1) || ' ');
atComment = true;
afterEmptyLine = false;
break;
case '%':
if (prelude[i + 1]?.[0] !== '#')
i += 1;
atComment = false;
break;
default:
// This may be wrong after doc-end, but in that case it doesn't matter
if (!atComment)
afterEmptyLine = true;
atComment = false;
}
}
return { comment, afterEmptyLine };
}
/**
* Compose a stream of CST nodes into a stream of YAML Documents.
*
* ```ts
* import { Composer, Parser } from 'yaml'
*
* const src: string = ...
* const tokens = new Parser().parse(src)
* const docs = new Composer().compose(tokens)
* ```
*/
class Composer {
constructor(options = {}) {
this.doc = null;
this.atDirectives = false;
this.prelude = [];
this.errors = [];
this.warnings = [];
this.onError = (source, code, message, warning) => {
const pos = getErrorPos(source);
if (warning)
this.warnings.push(new errors.YAMLWarning(pos, code, message));
else
this.errors.push(new errors.YAMLParseError(pos, code, message));
};
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
this.directives = new directives.Directives({ version: options.version || '1.2' });
this.options = options;
}
decorate(doc, afterDoc) {
const { comment, afterEmptyLine } = parsePrelude(this.prelude);
//console.log({ dc: doc.comment, prelude, comment })
if (comment) {
const dc = doc.contents;
if (afterDoc) {
doc.comment = doc.comment ? `${doc.comment}\n${comment}` : comment;
}
else if (afterEmptyLine || doc.directives.docStart || !dc) {
doc.commentBefore = comment;
}
else if (Node.isCollection(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (Node.isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}\n${cb}` : comment;
}
else {
const cb = dc.commentBefore;
dc.commentBefore = cb ? `${comment}\n${cb}` : comment;
}
}
if (afterDoc) {
Array.prototype.push.apply(doc.errors, this.errors);
Array.prototype.push.apply(doc.warnings, this.warnings);
}
else {
doc.errors = this.errors;
doc.warnings = this.warnings;
}
this.prelude = [];
this.errors = [];
this.warnings = [];
}
/**
* Current stream status information.
*
* Mostly useful at the end of input for an empty stream.
*/
streamInfo() {
return {
comment: parsePrelude(this.prelude).comment,
directives: this.directives,
errors: this.errors,
warnings: this.warnings
};
}
/**
* Compose tokens into documents.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*compose(tokens, forceDoc = false, endOffset = -1) {
for (const token of tokens)
yield* this.next(token);
yield* this.end(forceDoc, endOffset);
}
/** Advance the composer by one CST token. */
*next(token) {
if (process.env.LOG_STREAM)
console.dir(token, { depth: null });
switch (token.type) {
case 'directive':
this.directives.add(token.source, (offset, message, warning) => {
const pos = getErrorPos(token);
pos[0] += offset;
this.onError(pos, 'BAD_DIRECTIVE', message, warning);
});
this.prelude.push(token.source);
this.atDirectives = true;
break;
case 'document': {
const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
if (this.atDirectives && !doc.directives.docStart)
this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');
this.decorate(doc, false);
if (this.doc)
yield this.doc;
this.doc = doc;
this.atDirectives = false;
break;
}
case 'byte-order-mark':
case 'space':
break;
case 'comment':
case 'newline':
this.prelude.push(token.source);
break;
case 'error': {
const msg = token.source
? `${token.message}: ${JSON.stringify(token.source)}`
: token.message;
const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);
if (this.atDirectives || !this.doc)
this.errors.push(error);
else
this.doc.errors.push(error);
break;
}
case 'doc-end': {
if (!this.doc) {
const msg = 'Unexpected doc-end without preceding document';
this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));
break;
}
this.doc.directives.docEnd = true;
const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
this.decorate(this.doc, true);
if (end.comment) {
const dc = this.doc.comment;
this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment;
}
this.doc.range[2] = end.offset;
break;
}
default:
this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));
}
}
/**
* Call at end of input to yield any remaining document.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*end(forceDoc = false, endOffset = -1) {
if (this.doc) {
this.decorate(this.doc, true);
yield this.doc;
this.doc = null;
}
else if (forceDoc) {
const opts = Object.assign({ _directives: this.directives }, this.options);
const doc = new Document.Document(undefined, opts);
if (this.atDirectives)
this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');
doc.range = [0, endOffset, endOffset];
this.decorate(doc, false);
yield doc;
}
}
}
exports.Composer = Composer;
/***/ }),
/***/ 2986:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Pair = __nccwpck_require__(246);
var YAMLMap = __nccwpck_require__(6011);
var resolveProps = __nccwpck_require__(6985);
var utilContainsNewline = __nccwpck_require__(976);
var utilFlowIndentCheck = __nccwpck_require__(3669);
var utilMapIncludes = __nccwpck_require__(6899);
const startColMsg = 'All mapping items must start at the same column';
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError) {
const map = new YAMLMap.YAMLMap(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;
let commentEnd = null;
for (const collItem of bm.items) {
const { start, key, sep, value } = collItem;
// key properties
const keyProps = resolveProps.resolveProps(start, {
indicator: 'explicit-key-ind',
next: key ?? sep?.[0],
offset,
onError,
startOnNewline: true
});
const implicitKey = !keyProps.found;
if (implicitKey) {
if (key) {
if (key.type === 'block-seq')
onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');
else if ('indent' in key && key.indent !== bm.indent)
onError(offset, 'BAD_INDENT', startColMsg);
}
if (!keyProps.anchor && !keyProps.tag && !sep) {
commentEnd = keyProps.end;
if (keyProps.comment) {
if (map.comment)
map.comment += '\n' + keyProps.comment;
else
map.comment = keyProps.comment;
}
continue;
}
if (keyProps.hasNewlineAfterProp || utilContainsNewline.containsNewline(key)) {
onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');
}
}
else if (keyProps.found?.indent !== bm.indent) {
onError(offset, 'BAD_INDENT', startColMsg);
}
// key value
const keyStart = keyProps.end;
const keyNode = key
? composeNode(ctx, key, keyProps, onError)
: composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
// value properties
const valueProps = resolveProps.resolveProps(sep ?? [], {
indicator: 'map-value-ind',
next: value,
offset: keyNode.range[2],
onError,
startOnNewline: !key || key.type === 'block-scalar'
});
offset = valueProps.end;
if (valueProps.found) {
if (implicitKey) {
if (value?.type === 'block-map' && !valueProps.hasNewline)
onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');
if (ctx.options.strict &&
keyProps.start < valueProps.found.offset - 1024)
onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');
}
// value value
const valueNode = value
? composeNode(ctx, value, valueProps, onError)
: composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
offset = valueNode.range[2];
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map.items.push(pair);
}
else {
// key with no value
if (implicitKey)
onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');
if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += '\n' + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map.items.push(pair);
}
}
if (commentEnd && commentEnd < offset)
onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');
map.range = [bm.offset, offset, commentEnd ?? offset];
return map;
}
exports.resolveBlockMap = resolveBlockMap;
/***/ }),
/***/ 9485:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
function resolveBlockScalar(scalar, strict, onError) {
const start = scalar.offset;
const header = parseBlockScalarHeader(scalar, strict, onError);
if (!header)
return { value: '', type: null, comment: '', range: [start, start, start] };
const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
const lines = scalar.source ? splitLines(scalar.source) : [];
// determine the end of content & start of chomping
let chompStart = lines.length;
for (let i = lines.length - 1; i >= 0; --i) {
const content = lines[i][1];
if (content === '' || content === '\r')
chompStart = i;
else
break;
}
// shortcut for empty contents
if (chompStart === 0) {
const value = header.chomp === '+' && lines.length > 0
? '\n'.repeat(Math.max(1, lines.length - 1))
: '';
let end = start + header.length;
if (scalar.source)
end += scalar.source.length;
return { value, type, comment: header.comment, range: [start, end, end] };
}
// find the indentation level to trim from start
let trimIndent = scalar.indent + header.indent;
let offset = scalar.offset + header.length;
let contentStart = 0;
for (let i = 0; i < chompStart; ++i) {
const [indent, content] = lines[i];
if (content === '' || content === '\r') {
if (header.indent === 0 && indent.length > trimIndent)
trimIndent = indent.length;
}
else {
if (indent.length < trimIndent) {
const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';
onError(offset + indent.length, 'MISSING_CHAR', message);
}
if (header.indent === 0)
trimIndent = indent.length;
contentStart = i;
break;
}
offset += indent.length + content.length + 1;
}
// include trailing more-indented empty lines in content
for (let i = lines.length - 1; i >= chompStart; --i) {
if (lines[i][0].length > trimIndent)
chompStart = i + 1;
}
let value = '';
let sep = '';
let prevMoreIndented = false;
// leading whitespace is kept intact
for (let i = 0; i < contentStart; ++i)
value += lines[i][0].slice(trimIndent) + '\n';
for (let i = contentStart; i < chompStart; ++i) {
let [indent, content] = lines[i];
offset += indent.length + content.length + 1;
const crlf = content[content.length - 1] === '\r';
if (crlf)
content = content.slice(0, -1);
/* istanbul ignore if already caught in lexer */
if (content && indent.length < trimIndent) {
const src = header.indent
? 'explicit indentation indicator'
: 'first line';
const message = `Block scalar lines must not be less indented than their ${src}`;
onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);
indent = '';
}
if (type === Scalar.Scalar.BLOCK_LITERAL) {
value += sep + indent.slice(trimIndent) + content;
sep = '\n';
}
else if (indent.length > trimIndent || content[0] === '\t') {
// more-indented content within a folded block
if (sep === ' ')
sep = '\n';
else if (!prevMoreIndented && sep === '\n')
sep = '\n\n';
value += sep + indent.slice(trimIndent) + content;
sep = '\n';
prevMoreIndented = true;
}
else if (content === '') {
// empty line
if (sep === '\n')
value += '\n';
else
sep = '\n';
}
else {
value += sep + content;
sep = ' ';
prevMoreIndented = false;
}
}
switch (header.chomp) {
case '-':
break;
case '+':
for (let i = chompStart; i < lines.length; ++i)
value += '\n' + lines[i][0].slice(trimIndent);
if (value[value.length - 1] !== '\n')
value += '\n';
break;
default:
value += '\n';
}
const end = start + header.length + scalar.source.length;
return { value, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset, props }, strict, onError) {
/* istanbul ignore if should not happen */
if (props[0].type !== 'block-scalar-header') {
onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');
return null;
}
const { source } = props[0];
const mode = source[0];
let indent = 0;
let chomp = '';
let error = -1;
for (let i = 1; i < source.length; ++i) {
const ch = source[i];
if (!chomp && (ch === '-' || ch === '+'))
chomp = ch;
else {
const n = Number(ch);
if (!indent && n)
indent = n;
else if (error === -1)
error = offset + i;
}
}
if (error !== -1)
onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);
let hasSpace = false;
let comment = '';
let length = source.length;
for (let i = 1; i < props.length; ++i) {
const token = props[i];
switch (token.type) {
case 'space':
hasSpace = true;
// fallthrough
case 'newline':
length += token.source.length;
break;
case 'comment':
if (strict && !hasSpace) {
const message = 'Comments must be separated from other tokens by white space characters';
onError(token, 'MISSING_CHAR', message);
}
length += token.source.length;
comment = token.source.substring(1);
break;
case 'error':
onError(token, 'UNEXPECTED_TOKEN', token.message);
length += token.source.length;
break;
/* istanbul ignore next should not happen */
default: {
const message = `Unexpected token in block scalar header: ${token.type}`;
onError(token, 'UNEXPECTED_TOKEN', message);
const ts = token.source;
if (ts && typeof ts === 'string')
length += ts.length;
}
}
}
return { mode, indent, chomp, comment, length };
}
/** @returns Array of lines split up as `[indent, content]` */
function splitLines(source) {
const split = source.split(/\n( *)/);
const first = split[0];
const m = first.match(/^( *)/);
const line0 = m?.[1]
? [m[1], first.slice(m[1].length)]
: ['', first];
const lines = [line0];
for (let i = 1; i < split.length; i += 2)
lines.push([split[i], split[i + 1]]);
return lines;
}
exports.resolveBlockScalar = resolveBlockScalar;
/***/ }),
/***/ 2289:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var YAMLSeq = __nccwpck_require__(5161);
var resolveProps = __nccwpck_require__(6985);
var utilFlowIndentCheck = __nccwpck_require__(3669);
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError) {
const seq = new YAMLSeq.YAMLSeq(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bs.offset;
let commentEnd = null;
for (const { start, value } of bs.items) {
const props = resolveProps.resolveProps(start, {
indicator: 'seq-item-ind',
next: value,
offset,
onError,
startOnNewline: true
});
if (!props.found) {
if (props.anchor || props.tag || value) {
if (value && value.type === 'block-seq')
onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');
else
onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
}
else {
commentEnd = props.end;
if (props.comment)
seq.comment = props.comment;
continue;
}
}
const node = value
? composeNode(ctx, value, props, onError)
: composeEmptyNode(ctx, props.end, start, null, props, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);
offset = node.range[2];
seq.items.push(node);
}
seq.range = [bs.offset, offset, commentEnd ?? offset];
return seq;
}
exports.resolveBlockSeq = resolveBlockSeq;
/***/ }),
/***/ 1250:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
function resolveEnd(end, offset, reqSpace, onError) {
let comment = '';
if (end) {
let hasSpace = false;
let sep = '';
for (const token of end) {
const { source, type } = token;
switch (type) {
case 'space':
hasSpace = true;
break;
case 'comment': {
if (reqSpace && !hasSpace)
onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
const cb = source.substring(1) || ' ';
if (!comment)
comment = cb;
else
comment += sep + cb;
sep = '';
break;
}
case 'newline':
if (comment)
sep += source;
hasSpace = true;
break;
default:
onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);
}
offset += source.length;
}
}
return { comment, offset };
}
exports.resolveEnd = resolveEnd;
/***/ }),
/***/ 45:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var YAMLMap = __nccwpck_require__(6011);
var YAMLSeq = __nccwpck_require__(5161);
var resolveEnd = __nccwpck_require__(1250);
var resolveProps = __nccwpck_require__(6985);
var utilContainsNewline = __nccwpck_require__(976);
var utilMapIncludes = __nccwpck_require__(6899);
const blockMsg = 'Block collections are not allowed within flow collections';
const isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError) {
const isMap = fc.start.source === '{';
const fcName = isMap ? 'flow map' : 'flow sequence';
const coll = isMap
? new YAMLMap.YAMLMap(ctx.schema)
: new YAMLSeq.YAMLSeq(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
ctx.atRoot = false;
let offset = fc.offset + fc.start.source.length;
for (let i = 0; i < fc.items.length; ++i) {
const collItem = fc.items[i];
const { start, key, sep, value } = collItem;
const props = resolveProps.resolveProps(start, {
flow: fcName,
indicator: 'explicit-key-ind',
next: key ?? sep?.[0],
offset,
onError,
startOnNewline: false
});
if (!props.found) {
if (!props.anchor && !props.tag && !sep && !value) {
if (i === 0 && props.comma)
onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
else if (i < fc.items.length - 1)
onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);
if (props.comment) {
if (coll.comment)
coll.comment += '\n' + props.comment;
else
coll.comment = props.comment;
}
offset = props.end;
continue;
}
if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
onError(key, // checked by containsNewline()
'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
}
if (i === 0) {
if (props.comma)
onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);
}
else {
if (!props.comma)
onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);
if (props.comment) {
let prevItemComment = '';
loop: for (const st of start) {
switch (st.type) {
case 'comma':
case 'space':
break;
case 'comment':
prevItemComment = st.source.substring(1);
break loop;
default:
break loop;
}
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (Node.isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += '\n' + prevItemComment;
else
prev.comment = prevItemComment;
props.comment = props.comment.substring(prevItemComment.length + 1);
}
}
}
if (!isMap && !sep && !props.found) {
// item is a value in a seq
// → key & sep are empty, start does not include ? or :
const valueNode = value
? composeNode(ctx, value, props, onError)
: composeEmptyNode(ctx, props.end, sep, null, props, onError);
coll.items.push(valueNode);
offset = valueNode.range[2];
if (isBlock(value))
onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
}
else {
// item is a key+value pair
// key value
const keyStart = props.end;
const keyNode = key
? composeNode(ctx, key, props, onError)
: composeEmptyNode(ctx, keyStart, start, null, props, onError);
if (isBlock(key))
onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);
// value properties
const valueProps = resolveProps.resolveProps(sep ?? [], {
flow: fcName,
indicator: 'map-value-ind',
next: value,
offset: keyNode.range[2],
onError,
startOnNewline: false
});
if (valueProps.found) {
if (!isMap && !props.found && ctx.options.strict) {
if (sep)
for (const st of sep) {
if (st === valueProps.found)
break;
if (st.type === 'newline') {
onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');
break;
}
}
if (props.start < valueProps.found.offset - 1024)
onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');
}
}
else if (value) {
if ('source' in value && value.source && value.source[0] === ':')
onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
else
onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
}
// value value
const valueNode = value
? composeNode(ctx, value, valueProps, onError)
: valueProps.found
? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)
: null;
if (valueNode) {
if (isBlock(value))
onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);
}
else if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += '\n' + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
if (isMap) {
const map = coll;
if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');
map.items.push(pair);
}
else {
const map = new YAMLMap.YAMLMap(ctx.schema);
map.flow = true;
map.items.push(pair);
coll.items.push(map);
}
offset = valueNode ? valueNode.range[2] : valueProps.end;
}
}
const expectedEnd = isMap ? '}' : ']';
const [ce, ...ee] = fc.end;
let cePos = offset;
if (ce && ce.source === expectedEnd)
cePos = ce.offset + ce.source.length;
else {
const name = fcName[0].toUpperCase() + fcName.substring(1);
const msg = atRoot
? `${name} must end with a ${expectedEnd}`
: `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);
if (ce && ce.source.length !== 1)
ee.unshift(ce);
}
if (ee.length > 0) {
const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
if (end.comment) {
if (coll.comment)
coll.comment += '\n' + end.comment;
else
coll.comment = end.comment;
}
coll.range = [fc.offset, cePos, end.offset];
}
else {
coll.range = [fc.offset, cePos, cePos];
}
return coll;
}
exports.resolveFlowCollection = resolveFlowCollection;
/***/ }),
/***/ 7578:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
var resolveEnd = __nccwpck_require__(1250);
function resolveFlowScalar(scalar, strict, onError) {
const { offset, type, source, end } = scalar;
let _type;
let value;
const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
switch (type) {
case 'scalar':
_type = Scalar.Scalar.PLAIN;
value = plainValue(source, _onError);
break;
case 'single-quoted-scalar':
_type = Scalar.Scalar.QUOTE_SINGLE;
value = singleQuotedValue(source, _onError);
break;
case 'double-quoted-scalar':
_type = Scalar.Scalar.QUOTE_DOUBLE;
value = doubleQuotedValue(source, _onError);
break;
/* istanbul ignore next should not happen */
default:
onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);
return {
value: '',
type: null,
comment: '',
range: [offset, offset + source.length, offset + source.length]
};
}
const valueEnd = offset + source.length;
const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
return {
value,
type: _type,
comment: re.comment,
range: [offset, valueEnd, re.offset]
};
}
function plainValue(source, onError) {
let badChar = '';
switch (source[0]) {
/* istanbul ignore next should not happen */
case '\t':
badChar = 'a tab character';
break;
case ',':
badChar = 'flow indicator character ,';
break;
case '%':
badChar = 'directive indicator character %';
break;
case '|':
case '>': {
badChar = `block scalar indicator ${source[0]}`;
break;
}
case '@':
case '`': {
badChar = `reserved character ${source[0]}`;
break;
}
}
if (badChar)
onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);
return foldLines(source);
}
function singleQuotedValue(source, onError) {
if (source[source.length - 1] !== "'" || source.length === 1)
onError(source.length, 'MISSING_CHAR', "Missing closing 'quote");
return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
/**
* The negative lookbehind here and in the `re` RegExp is to
* prevent causing a polynomial search time in certain cases.
*
* The try-catch is for Safari, which doesn't support this yet:
* https://caniuse.com/js-regexp-lookbehind
*/
let first, line;
try {
first = new RegExp('(.*?)(?<![ \t])[ \t]*\r?\n', 'sy');
line = new RegExp('[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\r?\n', 'sy');
}
catch (_) {
first = /(.*?)[ \t]*\r?\n/sy;
line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
}
let match = first.exec(source);
if (!match)
return source;
let res = match[1];
let sep = ' ';
let pos = first.lastIndex;
line.lastIndex = pos;
while ((match = line.exec(source))) {
if (match[1] === '') {
if (sep === '\n')
res += sep;
else
sep = '\n';
}
else {
res += sep + match[1];
sep = ' ';
}
pos = line.lastIndex;
}
const last = /[ \t]*(.*)/sy;
last.lastIndex = pos;
match = last.exec(source);
return res + sep + (match?.[1] ?? '');
}
function doubleQuotedValue(source, onError) {
let res = '';
for (let i = 1; i < source.length - 1; ++i) {
const ch = source[i];
if (ch === '\r' && source[i + 1] === '\n')
continue;
if (ch === '\n') {
const { fold, offset } = foldNewline(source, i);
res += fold;
i = offset;
}
else if (ch === '\\') {
let next = source[++i];
const cc = escapeCodes[next];
if (cc)
res += cc;
else if (next === '\n') {
// skip escaped newlines, but still trim the following line
next = source[i + 1];
while (next === ' ' || next === '\t')
next = source[++i + 1];
}
else if (next === '\r' && source[i + 1] === '\n') {
// skip escaped CRLF newlines, but still trim the following line
next = source[++i + 1];
while (next === ' ' || next === '\t')
next = source[++i + 1];
}
else if (next === 'x' || next === 'u' || next === 'U') {
const length = { x: 2, u: 4, U: 8 }[next];
res += parseCharCode(source, i + 1, length, onError);
i += length;
}
else {
const raw = source.substr(i - 1, 2);
onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
res += raw;
}
}
else if (ch === ' ' || ch === '\t') {
// trim trailing whitespace
const wsStart = i;
let next = source[i + 1];
while (next === ' ' || next === '\t')
next = source[++i + 1];
if (next !== '\n' && !(next === '\r' && source[i + 2] === '\n'))
res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
}
else {
res += ch;
}
}
if (source[source.length - 1] !== '"' || source.length === 1)
onError(source.length, 'MISSING_CHAR', 'Missing closing "quote');
return res;
}
/**
* Fold a single newline into a space, multiple newlines to N - 1 newlines.
* Presumes `source[offset] === '\n'`
*/
function foldNewline(source, offset) {
let fold = '';
let ch = source[offset + 1];
while (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
if (ch === '\r' && source[offset + 2] !== '\n')
break;
if (ch === '\n')
fold += '\n';
offset += 1;
ch = source[offset + 1];
}
if (!fold)
fold = ' ';
return { fold, offset };
}
const escapeCodes = {
'0': '\0',
a: '\x07',
b: '\b',
e: '\x1b',
f: '\f',
n: '\n',
r: '\r',
t: '\t',
v: '\v',
N: '\u0085',
_: '\u00a0',
L: '\u2028',
P: '\u2029',
' ': ' ',
'"': '"',
'/': '/',
'\\': '\\',
'\t': '\t'
};
function parseCharCode(source, offset, length, onError) {
const cc = source.substr(offset, length);
const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
const code = ok ? parseInt(cc, 16) : NaN;
if (isNaN(code)) {
const raw = source.substr(offset - 2, length + 2);
onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);
return raw;
}
return String.fromCodePoint(code);
}
exports.resolveFlowScalar = resolveFlowScalar;
/***/ }),
/***/ 6985:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
function resolveProps(tokens, { flow, indicator, next, offset, onError, startOnNewline }) {
let spaceBefore = false;
let atNewline = startOnNewline;
let hasSpace = startOnNewline;
let comment = '';
let commentSep = '';
let hasNewline = false;
let hasNewlineAfterProp = false;
let reqSpace = false;
let anchor = null;
let tag = null;
let comma = null;
let found = null;
let start = null;
for (const token of tokens) {
if (reqSpace) {
if (token.type !== 'space' &&
token.type !== 'newline' &&
token.type !== 'comma')
onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
reqSpace = false;
}
switch (token.type) {
case 'space':
// At the doc level, tabs at line start may be parsed
// as leading white space rather than indentation.
// In a flow collection, only the parser handles indent.
if (!flow &&
atNewline &&
indicator !== 'doc-start' &&
token.source[0] === '\t')
onError(token, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');
hasSpace = true;
break;
case 'comment': {
if (!hasSpace)
onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');
const cb = token.source.substring(1) || ' ';
if (!comment)
comment = cb;
else
comment += commentSep + cb;
commentSep = '';
atNewline = false;
break;
}
case 'newline':
if (atNewline) {
if (comment)
comment += token.source;
else
spaceBefore = true;
}
else
commentSep += token.source;
atNewline = true;
hasNewline = true;
if (anchor || tag)
hasNewlineAfterProp = true;
hasSpace = true;
break;
case 'anchor':
if (anchor)
onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');
if (token.source.endsWith(':'))
onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);
anchor = token;
if (start === null)
start = token.offset;
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
case 'tag': {
if (tag)
onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');
tag = token;
if (start === null)
start = token.offset;
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
}
case indicator:
// Could here handle preceding comments differently
if (anchor || tag)
onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);
if (found)
onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);
found = token;
atNewline = false;
hasSpace = false;
break;
case 'comma':
if (flow) {
if (comma)
onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);
comma = token;
atNewline = false;
hasSpace = false;
break;
}
// else fallthrough
default:
onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);
atNewline = false;
hasSpace = false;
}
}
const last = tokens[tokens.length - 1];
const end = last ? last.offset + last.source.length : offset;
if (reqSpace &&
next &&
next.type !== 'space' &&
next.type !== 'newline' &&
next.type !== 'comma' &&
(next.type !== 'scalar' || next.source !== ''))
onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');
return {
comma,
found,
spaceBefore,
comment,
hasNewline,
hasNewlineAfterProp,
anchor,
tag,
end,
start: start ?? end
};
}
exports.resolveProps = resolveProps;
/***/ }),
/***/ 976:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
function containsNewline(key) {
if (!key)
return null;
switch (key.type) {
case 'alias':
case 'scalar':
case 'double-quoted-scalar':
case 'single-quoted-scalar':
if (key.source.includes('\n'))
return true;
if (key.end)
for (const st of key.end)
if (st.type === 'newline')
return true;
return false;
case 'flow-collection':
for (const it of key.items) {
for (const st of it.start)
if (st.type === 'newline')
return true;
if (it.sep)
for (const st of it.sep)
if (st.type === 'newline')
return true;
if (containsNewline(it.key) || containsNewline(it.value))
return true;
}
return false;
default:
return true;
}
}
exports.containsNewline = containsNewline;
/***/ }),
/***/ 8781:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
function emptyScalarPosition(offset, before, pos) {
if (before) {
if (pos === null)
pos = before.length;
for (let i = pos - 1; i >= 0; --i) {
let st = before[i];
switch (st.type) {
case 'space':
case 'comment':
case 'newline':
offset -= st.source.length;
continue;
}
// Technically, an empty scalar is immediately after the last non-empty
// node, but it's more useful to place it after any whitespace.
st = before[++i];
while (st?.type === 'space') {
offset += st.source.length;
st = before[++i];
}
break;
}
}
return offset;
}
exports.emptyScalarPosition = emptyScalarPosition;
/***/ }),
/***/ 3669:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var utilContainsNewline = __nccwpck_require__(976);
function flowIndentCheck(indent, fc, onError) {
if (fc?.type === 'flow-collection') {
const end = fc.end[0];
if (end.indent === indent &&
(end.source === ']' || end.source === '}') &&
utilContainsNewline.containsNewline(fc)) {
const msg = 'Flow end indicator should be more indented than parent';
onError(end, 'BAD_INDENT', msg, true);
}
}
}
exports.flowIndentCheck = flowIndentCheck;
/***/ }),
/***/ 6899:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
if (uniqueKeys === false)
return false;
const isEqual = typeof uniqueKeys === 'function'
? uniqueKeys
: (a, b) => a === b ||
(Node.isScalar(a) &&
Node.isScalar(b) &&
a.value === b.value &&
!(a.value === '<<' && ctx.schema.merge));
return items.some(pair => isEqual(pair.key, search));
}
exports.mapIncludes = mapIncludes;
/***/ }),
/***/ 42:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Alias = __nccwpck_require__(5639);
var Collection = __nccwpck_require__(3466);
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var toJS = __nccwpck_require__(2463);
var Schema = __nccwpck_require__(6831);
var stringify = __nccwpck_require__(8409);
var stringifyDocument = __nccwpck_require__(5225);
var anchors = __nccwpck_require__(8459);
var applyReviver = __nccwpck_require__(3412);
var createNode = __nccwpck_require__(9652);
var directives = __nccwpck_require__(5400);
class Document {
constructor(value, replacer, options) {
/** A comment before this Document */
this.commentBefore = null;
/** A comment immediately after this Document */
this.comment = null;
/** Errors encountered during parsing. */
this.errors = [];
/** Warnings encountered during parsing. */
this.warnings = [];
Object.defineProperty(this, Node.NODE_TYPE, { value: Node.DOC });
let _replacer = null;
if (typeof replacer === 'function' || Array.isArray(replacer)) {
_replacer = replacer;
}
else if (options === undefined && replacer) {
options = replacer;
replacer = undefined;
}
const opt = Object.assign({
intAsBigInt: false,
keepSourceTokens: false,
logLevel: 'warn',
prettyErrors: true,
strict: true,
uniqueKeys: true,
version: '1.2'
}, options);
this.options = opt;
let { version } = opt;
if (options?._directives) {
this.directives = options._directives.atDocument();
if (this.directives.yaml.explicit)
version = this.directives.yaml.version;
}
else
this.directives = new directives.Directives({ version });
this.setSchema(version, options);
if (value === undefined)
this.contents = null;
else {
this.contents = this.createNode(value, _replacer, options);
}
}
/**
* Create a deep copy of this Document and its contents.
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone() {
const copy = Object.create(Document.prototype, {
[Node.NODE_TYPE]: { value: Node.DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
copy.errors = this.errors.slice();
copy.warnings = this.warnings.slice();
copy.options = Object.assign({}, this.options);
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = Node.isNode(this.contents)
? this.contents.clone(copy.schema)
: this.contents;
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** Adds a value to the document. */
add(value) {
if (assertCollection(this.contents))
this.contents.add(value);
}
/** Adds a value to the document. */
addIn(path, value) {
if (assertCollection(this.contents))
this.contents.addIn(path, value);
}
/**
* Create a new `Alias` node, ensuring that the target `node` has the required anchor.
*
* If `node` already has an anchor, `name` is ignored.
* Otherwise, the `node.anchor` value will be set to `name`,
* or if an anchor with that name is already present in the document,
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node, name) {
if (!node.anchor) {
const prev = anchors.anchorNames(this);
node.anchor =
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
!name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;
}
return new Alias.Alias(node.anchor);
}
createNode(value, replacer, options) {
let _replacer = undefined;
if (typeof replacer === 'function') {
value = replacer.call({ '': value }, '', value);
_replacer = replacer;
}
else if (Array.isArray(replacer)) {
const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
const asStr = replacer.filter(keyToStr).map(String);
if (asStr.length > 0)
replacer = replacer.concat(asStr);
_replacer = replacer;
}
else if (options === undefined && replacer) {
options = replacer;
replacer = undefined;
}
const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
anchorPrefix || 'a');
const ctx = {
aliasDuplicateObjects: aliasDuplicateObjects ?? true,
keepUndefined: keepUndefined ?? false,
onAnchor,
onTagObj,
replacer: _replacer,
schema: this.schema,
sourceObjects
};
const node = createNode.createNode(value, tag, ctx);
if (flow && Node.isCollection(node))
node.flow = true;
setAnchors();
return node;
}
/**
* Convert a key and a value into a `Pair` using the current schema,
* recursively wrapping all values as `Scalar` or `Collection` nodes.
*/
createPair(key, value, options = {}) {
const k = this.createNode(key, null, options);
const v = this.createNode(value, null, options);
return new Pair.Pair(k, v);
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
delete(key) {
return assertCollection(this.contents) ? this.contents.delete(key) : false;
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
deleteIn(path) {
if (Collection.isEmptyPath(path)) {
if (this.contents == null)
return false;
this.contents = null;
return true;
}
return assertCollection(this.contents)
? this.contents.deleteIn(path)
: false;
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key, keepScalar) {
return Node.isCollection(this.contents)
? this.contents.get(key, keepScalar)
: undefined;
}
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path, keepScalar) {
if (Collection.isEmptyPath(path))
return !keepScalar && Node.isScalar(this.contents)
? this.contents.value
: this.contents;
return Node.isCollection(this.contents)
? this.contents.getIn(path, keepScalar)
: undefined;
}
/**
* Checks if the document includes a value with the key `key`.
*/
has(key) {
return Node.isCollection(this.contents) ? this.contents.has(key) : false;
}
/**
* Checks if the document includes a value at `path`.
*/
hasIn(path) {
if (Collection.isEmptyPath(path))
return this.contents !== undefined;
return Node.isCollection(this.contents) ? this.contents.hasIn(path) : false;
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
set(key, value) {
if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, [key], value);
}
else if (assertCollection(this.contents)) {
this.contents.set(key, value);
}
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
if (Collection.isEmptyPath(path))
this.contents = value;
else if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
}
else if (assertCollection(this.contents)) {
this.contents.setIn(path, value);
}
}
/**
* Change the YAML version and schema used by the document.
* A `null` version disables support for directives, explicit tags, anchors, and aliases.
* It also requires the `schema` option to be given as a `Schema` instance value.
*
* Overrides all previously set schema options.
*/
setSchema(version, options = {}) {
if (typeof version === 'number')
version = String(version);
let opt;
switch (version) {
case '1.1':
if (this.directives)
this.directives.yaml.version = '1.1';
else
this.directives = new directives.Directives({ version: '1.1' });
opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' };
break;
case '1.2':
case 'next':
if (this.directives)
this.directives.yaml.version = version;
else
this.directives = new directives.Directives({ version });
opt = { merge: false, resolveKnownTags: true, schema: 'core' };
break;
case null:
if (this.directives)
delete this.directives;
opt = null;
break;
default: {
const sv = JSON.stringify(version);
throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
}
}
// Not using `instanceof Schema` to allow for duck typing
if (options.schema instanceof Object)
this.schema = options.schema;
else if (opt)
this.schema = new Schema.Schema(Object.assign(opt, options));
else
throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
}
// json & jsonArg are only used from toJSON()
toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
const ctx = {
anchors: new Map(),
doc: this,
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
stringify: stringify.stringify
};
const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);
if (typeof onAnchor === 'function')
for (const { count, res } of ctx.anchors.values())
onAnchor(res, count);
return typeof reviver === 'function'
? applyReviver.applyReviver(reviver, { '': res }, '', res)
: res;
}
/**
* A JSON representation of the document `contents`.
*
* @param jsonArg Used by `JSON.stringify` to indicate the array index or
* property name.
*/
toJSON(jsonArg, onAnchor) {
return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
}
/** A YAML representation of the document. */
toString(options = {}) {
if (this.errors.length > 0)
throw new Error('Document with errors cannot be stringified');
if ('indent' in options &&
(!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
const s = JSON.stringify(options.indent);
throw new Error(`"indent" option must be a positive integer, not ${s}`);
}
return stringifyDocument.stringifyDocument(this, options);
}
}
function assertCollection(contents) {
if (Node.isCollection(contents))
return true;
throw new Error('Expected a YAML collection as document contents');
}
exports.Document = Document;
/***/ }),
/***/ 8459:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var visit = __nccwpck_require__(6796);
/**
* Verify that the input string is a valid anchor.
*
* Will throw on errors.
*/
function anchorIsValid(anchor) {
if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
const sa = JSON.stringify(anchor);
const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
throw new Error(msg);
}
return true;
}
function anchorNames(root) {
const anchors = new Set();
visit.visit(root, {
Value(_key, node) {
if (node.anchor)
anchors.add(node.anchor);
}
});
return anchors;
}
/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
function findNewAnchor(prefix, exclude) {
for (let i = 1; true; ++i) {
const name = `${prefix}${i}`;
if (!exclude.has(name))
return name;
}
}
function createNodeAnchors(doc, prefix) {
const aliasObjects = [];
const sourceObjects = new Map();
let prevAnchors = null;
return {
onAnchor: (source) => {
aliasObjects.push(source);
if (!prevAnchors)
prevAnchors = anchorNames(doc);
const anchor = findNewAnchor(prefix, prevAnchors);
prevAnchors.add(anchor);
return anchor;
},
/**
* With circular references, the source node is only resolved after all
* of its child nodes are. This is why anchors are set only after all of
* the nodes have been created.
*/
setAnchors: () => {
for (const source of aliasObjects) {
const ref = sourceObjects.get(source);
if (typeof ref === 'object' &&
ref.anchor &&
(Node.isScalar(ref.node) || Node.isCollection(ref.node))) {
ref.node.anchor = ref.anchor;
}
else {
const error = new Error('Failed to resolve repeated object (this should not happen)');
error.source = source;
throw error;
}
}
},
sourceObjects
};
}
exports.anchorIsValid = anchorIsValid;
exports.anchorNames = anchorNames;
exports.createNodeAnchors = createNodeAnchors;
exports.findNewAnchor = findNewAnchor;
/***/ }),
/***/ 3412:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/**
* Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
* in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
* 2021 edition: https://tc39.es/ecma262/#sec-json.parse
*
* Includes extensions for handling Map and Set objects.
*/
function applyReviver(reviver, obj, key, val) {
if (val && typeof val === 'object') {
if (Array.isArray(val)) {
for (let i = 0, len = val.length; i < len; ++i) {
const v0 = val[i];
const v1 = applyReviver(reviver, val, String(i), v0);
if (v1 === undefined)
delete val[i];
else if (v1 !== v0)
val[i] = v1;
}
}
else if (val instanceof Map) {
for (const k of Array.from(val.keys())) {
const v0 = val.get(k);
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === undefined)
val.delete(k);
else if (v1 !== v0)
val.set(k, v1);
}
}
else if (val instanceof Set) {
for (const v0 of Array.from(val)) {
const v1 = applyReviver(reviver, val, v0, v0);
if (v1 === undefined)
val.delete(v0);
else if (v1 !== v0) {
val.delete(v0);
val.add(v1);
}
}
}
else {
for (const [k, v0] of Object.entries(val)) {
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === undefined)
delete val[k];
else if (v1 !== v0)
val[k] = v1;
}
}
}
return reviver.call(obj, key, val);
}
exports.applyReviver = applyReviver;
/***/ }),
/***/ 9652:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Alias = __nccwpck_require__(5639);
var Node = __nccwpck_require__(1399);
var Scalar = __nccwpck_require__(9338);
const defaultTagPrefix = 'tag:yaml.org,2002:';
function findTagObject(value, tagName, tags) {
if (tagName) {
const match = tags.filter(t => t.tag === tagName);
const tagObj = match.find(t => !t.format) ?? match[0];
if (!tagObj)
throw new Error(`Tag ${tagName} not found`);
return tagObj;
}
return tags.find(t => t.identify?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
if (Node.isDocument(value))
value = value.contents;
if (Node.isNode(value))
return value;
if (Node.isPair(value)) {
const map = ctx.schema[Node.MAP].createNode?.(ctx.schema, null, ctx);
map.items.push(value);
return map;
}
if (value instanceof String ||
value instanceof Number ||
value instanceof Boolean ||
(typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere
) {
// https://tc39.es/ecma262/#sec-serializejsonproperty
value = value.valueOf();
}
const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
// Detect duplicate references to the same object & use Alias nodes for all
// after first. The `ref` wrapper allows for circular references to resolve.
let ref = undefined;
if (aliasDuplicateObjects && value && typeof value === 'object') {
ref = sourceObjects.get(value);
if (ref) {
if (!ref.anchor)
ref.anchor = onAnchor(value);
return new Alias.Alias(ref.anchor);
}
else {
ref = { anchor: null, node: null };
sourceObjects.set(value, ref);
}
}
if (tagName?.startsWith('!!'))
tagName = defaultTagPrefix + tagName.slice(2);
let tagObj = findTagObject(value, tagName, schema.tags);
if (!tagObj) {
if (value && typeof value.toJSON === 'function') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
value = value.toJSON();
}
if (!value || typeof value !== 'object') {
const node = new Scalar.Scalar(value);
if (ref)
ref.node = node;
return node;
}
tagObj =
value instanceof Map
? schema[Node.MAP]
: Symbol.iterator in Object(value)
? schema[Node.SEQ]
: schema[Node.MAP];
}
if (onTagObj) {
onTagObj(tagObj);
delete ctx.onTagObj;
}
const node = tagObj?.createNode
? tagObj.createNode(ctx.schema, value, ctx)
: new Scalar.Scalar(value);
if (tagName)
node.tag = tagName;
if (ref)
ref.node = node;
return node;
}
exports.createNode = createNode;
/***/ }),
/***/ 5400:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var visit = __nccwpck_require__(6796);
const escapeChars = {
'!': '%21',
',': '%2C',
'[': '%5B',
']': '%5D',
'{': '%7B',
'}': '%7D'
};
const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]);
class Directives {
constructor(yaml, tags) {
/**
* The directives-end/doc-start marker `---`. If `null`, a marker may still be
* included in the document's stringified representation.
*/
this.docStart = null;
/** The doc-end marker `...`. */
this.docEnd = false;
this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
this.tags = Object.assign({}, Directives.defaultTags, tags);
}
clone() {
const copy = new Directives(this.yaml, this.tags);
copy.docStart = this.docStart;
return copy;
}
/**
* During parsing, get a Directives instance for the current document and
* update the stream state according to the current version's spec.
*/
atDocument() {
const res = new Directives(this.yaml, this.tags);
switch (this.yaml.version) {
case '1.1':
this.atNextDocument = true;
break;
case '1.2':
this.atNextDocument = false;
this.yaml = {
explicit: Directives.defaultYaml.explicit,
version: '1.2'
};
this.tags = Object.assign({}, Directives.defaultTags);
break;
}
return res;
}
/**
* @param onError - May be called even if the action was successful
* @returns `true` on success
*/
add(line, onError) {
if (this.atNextDocument) {
this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };
this.tags = Object.assign({}, Directives.defaultTags);
this.atNextDocument = false;
}
const parts = line.trim().split(/[ \t]+/);
const name = parts.shift();
switch (name) {
case '%TAG': {
if (parts.length !== 2) {
onError(0, '%TAG directive should contain exactly two parts');
if (parts.length < 2)
return false;
}
const [handle, prefix] = parts;
this.tags[handle] = prefix;
return true;
}
case '%YAML': {
this.yaml.explicit = true;
if (parts.length !== 1) {
onError(0, '%YAML directive should contain exactly one part');
return false;
}
const [version] = parts;
if (version === '1.1' || version === '1.2') {
this.yaml.version = version;
return true;
}
else {
const isValid = /^\d+\.\d+$/.test(version);
onError(6, `Unsupported YAML version ${version}`, isValid);
return false;
}
}
default:
onError(0, `Unknown directive ${name}`, true);
return false;
}
}
/**
* Resolves a tag, matching handles to those defined in %TAG directives.
*
* @returns Resolved tag, which may also be the non-specific tag `'!'` or a
* `'!local'` tag, or `null` if unresolvable.
*/
tagName(source, onError) {
if (source === '!')
return '!'; // non-specific tag
if (source[0] !== '!') {
onError(`Not a valid tag: ${source}`);
return null;
}
if (source[1] === '<') {
const verbatim = source.slice(2, -1);
if (verbatim === '!' || verbatim === '!!') {
onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
return null;
}
if (source[source.length - 1] !== '>')
onError('Verbatim tags must end with a >');
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix)
return prefix + decodeURIComponent(suffix);
if (handle === '!')
return source; // local tag
onError(`Could not resolve tag: ${source}`);
return null;
}
/**
* Given a fully resolved tag, returns its printable string form,
* taking into account current tag prefixes and defaults.
*/
tagString(tag) {
for (const [handle, prefix] of Object.entries(this.tags)) {
if (tag.startsWith(prefix))
return handle + escapeTagName(tag.substring(prefix.length));
}
return tag[0] === '!' ? tag : `!<${tag}>`;
}
toString(doc) {
const lines = this.yaml.explicit
? [`%YAML ${this.yaml.version || '1.2'}`]
: [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc && tagEntries.length > 0 && Node.isNode(doc.contents)) {
const tags = {};
visit.visit(doc.contents, (_key, node) => {
if (Node.isNode(node) && node.tag)
tags[node.tag] = true;
});
tagNames = Object.keys(tags);
}
else
tagNames = [];
for (const [handle, prefix] of tagEntries) {
if (handle === '!!' && prefix === 'tag:yaml.org,2002:')
continue;
if (!doc || tagNames.some(tn => tn.startsWith(prefix)))
lines.push(`%TAG ${handle} ${prefix}`);
}
return lines.join('\n');
}
}
Directives.defaultYaml = { explicit: false, version: '1.2' };
Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' };
exports.Directives = Directives;
/***/ }),
/***/ 4236:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
class YAMLError extends Error {
constructor(name, pos, code, message) {
super();
this.name = name;
this.code = code;
this.message = message;
this.pos = pos;
}
}
class YAMLParseError extends YAMLError {
constructor(pos, code, message) {
super('YAMLParseError', pos, code, message);
}
}
class YAMLWarning extends YAMLError {
constructor(pos, code, message) {
super('YAMLWarning', pos, code, message);
}
}
const prettifyError = (src, lc) => (error) => {
if (error.pos[0] === -1)
return;
error.linePos = error.pos.map(pos => lc.linePos(pos));
const { line, col } = error.linePos[0];
error.message += ` at line ${line}, column ${col}`;
let ci = col - 1;
let lineStr = src
.substring(lc.lineStarts[line - 1], lc.lineStarts[line])
.replace(/[\n\r]+$/, '');
// Trim to max 80 chars, keeping col position near the middle
if (ci >= 60 && lineStr.length > 80) {
const trimStart = Math.min(ci - 39, lineStr.length - 79);
lineStr = '…' + lineStr.substring(trimStart);
ci -= trimStart - 1;
}
if (lineStr.length > 80)
lineStr = lineStr.substring(0, 79) + '…';
// Include previous line in context if pointing at line start
if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
// Regexp won't match if start is trimmed
let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
if (prev.length > 80)
prev = prev.substring(0, 79) + '…\n';
lineStr = prev + lineStr;
}
if (/[^ ]/.test(lineStr)) {
let count = 1;
const end = error.linePos[1];
if (end && end.line === line && end.col > col) {
count = Math.min(end.col - col, 80 - ci);
}
const pointer = ' '.repeat(ci) + '^'.repeat(count);
error.message += `:\n\n${lineStr}\n${pointer}\n`;
}
};
exports.YAMLError = YAMLError;
exports.YAMLParseError = YAMLParseError;
exports.YAMLWarning = YAMLWarning;
exports.prettifyError = prettifyError;
/***/ }),
/***/ 4083:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var composer = __nccwpck_require__(9493);
var Document = __nccwpck_require__(42);
var Schema = __nccwpck_require__(6831);
var errors = __nccwpck_require__(4236);
var Alias = __nccwpck_require__(5639);
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var Scalar = __nccwpck_require__(9338);
var YAMLMap = __nccwpck_require__(6011);
var YAMLSeq = __nccwpck_require__(5161);
var cst = __nccwpck_require__(9169);
var lexer = __nccwpck_require__(5976);
var lineCounter = __nccwpck_require__(1929);
var parser = __nccwpck_require__(3328);
var publicApi = __nccwpck_require__(8649);
var visit = __nccwpck_require__(6796);
exports.Composer = composer.Composer;
exports.Document = Document.Document;
exports.Schema = Schema.Schema;
exports.YAMLError = errors.YAMLError;
exports.YAMLParseError = errors.YAMLParseError;
exports.YAMLWarning = errors.YAMLWarning;
exports.Alias = Alias.Alias;
exports.isAlias = Node.isAlias;
exports.isCollection = Node.isCollection;
exports.isDocument = Node.isDocument;
exports.isMap = Node.isMap;
exports.isNode = Node.isNode;
exports.isPair = Node.isPair;
exports.isScalar = Node.isScalar;
exports.isSeq = Node.isSeq;
exports.Pair = Pair.Pair;
exports.Scalar = Scalar.Scalar;
exports.YAMLMap = YAMLMap.YAMLMap;
exports.YAMLSeq = YAMLSeq.YAMLSeq;
exports.CST = cst;
exports.Lexer = lexer.Lexer;
exports.LineCounter = lineCounter.LineCounter;
exports.Parser = parser.Parser;
exports.parse = publicApi.parse;
exports.parseAllDocuments = publicApi.parseAllDocuments;
exports.parseDocument = publicApi.parseDocument;
exports.stringify = publicApi.stringify;
exports.visit = visit.visit;
exports.visitAsync = visit.visitAsync;
/***/ }),
/***/ 6909:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
function debug(logLevel, ...messages) {
if (logLevel === 'debug')
console.log(...messages);
}
function warn(logLevel, warning) {
if (logLevel === 'debug' || logLevel === 'warn') {
if (typeof process !== 'undefined' && process.emitWarning)
process.emitWarning(warning);
else
console.warn(warning);
}
}
exports.debug = debug;
exports.warn = warn;
/***/ }),
/***/ 5639:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var anchors = __nccwpck_require__(8459);
var visit = __nccwpck_require__(6796);
var Node = __nccwpck_require__(1399);
class Alias extends Node.NodeBase {
constructor(source) {
super(Node.ALIAS);
this.source = source;
Object.defineProperty(this, 'tag', {
set() {
throw new Error('Alias nodes cannot have tags');
}
});
}
/**
* Resolve the value of this alias within `doc`, finding the last
* instance of the `source` anchor before this node.
*/
resolve(doc) {
let found = undefined;
visit.visit(doc, {
Node: (_key, node) => {
if (node === this)
return visit.visit.BREAK;
if (node.anchor === this.source)
found = node;
}
});
return found;
}
toJSON(_arg, ctx) {
if (!ctx)
return { source: this.source };
const { anchors, doc, maxAliasCount } = ctx;
const source = this.resolve(doc);
if (!source) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
const data = anchors.get(source);
/* istanbul ignore if */
if (!data || data.res === undefined) {
const msg = 'This should not happen: Alias anchor was not resolved?';
throw new ReferenceError(msg);
}
if (maxAliasCount >= 0) {
data.count += 1;
if (data.aliasCount === 0)
data.aliasCount = getAliasCount(doc, source, anchors);
if (data.count * data.aliasCount > maxAliasCount) {
const msg = 'Excessive alias count indicates a resource exhaustion attack';
throw new ReferenceError(msg);
}
}
return data.res;
}
toString(ctx, _onComment, _onChompKeep) {
const src = `*${this.source}`;
if (ctx) {
anchors.anchorIsValid(this.source);
if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new Error(msg);
}
if (ctx.implicitKey)
return `${src} `;
}
return src;
}
}
function getAliasCount(doc, node, anchors) {
if (Node.isAlias(node)) {
const source = node.resolve(doc);
const anchor = anchors && source && anchors.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
}
else if (Node.isCollection(node)) {
let count = 0;
for (const item of node.items) {
const c = getAliasCount(doc, item, anchors);
if (c > count)
count = c;
}
return count;
}
else if (Node.isPair(node)) {
const kc = getAliasCount(doc, node.key, anchors);
const vc = getAliasCount(doc, node.value, anchors);
return Math.max(kc, vc);
}
return 1;
}
exports.Alias = Alias;
/***/ }),
/***/ 3466:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var createNode = __nccwpck_require__(9652);
var Node = __nccwpck_require__(1399);
function collectionFromPath(schema, path, value) {
let v = value;
for (let i = path.length - 1; i >= 0; --i) {
const k = path[i];
if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
const a = [];
a[k] = v;
v = a;
}
else {
v = new Map([[k, v]]);
}
}
return createNode.createNode(v, undefined, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error('This should not happen, please report a bug.');
},
schema,
sourceObjects: new Map()
});
}
// Type guard is intentionally a little wrong so as to be more useful,
// as it does not cover untypable empty non-string iterables (e.g. []).
const isEmptyPath = (path) => path == null ||
(typeof path === 'object' && !!path[Symbol.iterator]().next().done);
class Collection extends Node.NodeBase {
constructor(type, schema) {
super(type);
Object.defineProperty(this, 'schema', {
value: schema,
configurable: true,
enumerable: false,
writable: true
});
}
/**
* Create a copy of this collection.
*
* @param schema - If defined, overwrites the original's schema
*/
clone(schema) {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema)
copy.schema = schema;
copy.items = copy.items.map(it => Node.isNode(it) || Node.isPair(it) ? it.clone(schema) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
}
/**
* Adds a value to the collection. For `!!map` and `!!omap` the value must
* be a Pair instance or a `{ key, value }` object, which may not have a key
* that already exists in the map.
*/
addIn(path, value) {
if (isEmptyPath(path))
this.add(value);
else {
const [key, ...rest] = path;
const node = this.get(key, true);
if (Node.isCollection(node))
node.addIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
/**
* Removes a value from the collection.
* @returns `true` if the item was found and removed.
*/
deleteIn(path) {
const [key, ...rest] = path;
if (rest.length === 0)
return this.delete(key);
const node = this.get(key, true);
if (Node.isCollection(node))
return node.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path, keepScalar) {
const [key, ...rest] = path;
const node = this.get(key, true);
if (rest.length === 0)
return !keepScalar && Node.isScalar(node) ? node.value : node;
else
return Node.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
}
hasAllNullValues(allowScalar) {
return this.items.every(node => {
if (!Node.isPair(node))
return false;
const n = node.value;
return (n == null ||
(allowScalar &&
Node.isScalar(n) &&
n.value == null &&
!n.commentBefore &&
!n.comment &&
!n.tag));
});
}
/**
* Checks if the collection includes a value with the key `key`.
*/
hasIn(path) {
const [key, ...rest] = path;
if (rest.length === 0)
return this.has(key);
const node = this.get(key, true);
return Node.isCollection(node) ? node.hasIn(rest) : false;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path, value) {
const [key, ...rest] = path;
if (rest.length === 0) {
this.set(key, value);
}
else {
const node = this.get(key, true);
if (Node.isCollection(node))
node.setIn(rest, value);
else if (node === undefined && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
}
Collection.maxFlowStringSingleLineLength = 60;
exports.Collection = Collection;
exports.collectionFromPath = collectionFromPath;
exports.isEmptyPath = isEmptyPath;
/***/ }),
/***/ 1399:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === 'object')
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
class NodeBase {
constructor(type) {
Object.defineProperty(this, NODE_TYPE, { value: type });
}
/** Create a copy of this node. */
clone() {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (this.range)
copy.range = this.range.slice();
return copy;
}
}
exports.ALIAS = ALIAS;
exports.DOC = DOC;
exports.MAP = MAP;
exports.NODE_TYPE = NODE_TYPE;
exports.NodeBase = NodeBase;
exports.PAIR = PAIR;
exports.SCALAR = SCALAR;
exports.SEQ = SEQ;
exports.hasAnchor = hasAnchor;
exports.isAlias = isAlias;
exports.isCollection = isCollection;
exports.isDocument = isDocument;
exports.isMap = isMap;
exports.isNode = isNode;
exports.isPair = isPair;
exports.isScalar = isScalar;
exports.isSeq = isSeq;
/***/ }),
/***/ 246:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var createNode = __nccwpck_require__(9652);
var stringifyPair = __nccwpck_require__(4875);
var addPairToJSMap = __nccwpck_require__(4676);
var Node = __nccwpck_require__(1399);
function createPair(key, value, ctx) {
const k = createNode.createNode(key, undefined, ctx);
const v = createNode.createNode(value, undefined, ctx);
return new Pair(k, v);
}
class Pair {
constructor(key, value = null) {
Object.defineProperty(this, Node.NODE_TYPE, { value: Node.PAIR });
this.key = key;
this.value = value;
}
clone(schema) {
let { key, value } = this;
if (Node.isNode(key))
key = key.clone(schema);
if (Node.isNode(value))
value = value.clone(schema);
return new Pair(key, value);
}
toJSON(_, ctx) {
const pair = ctx?.mapAsMap ? new Map() : {};
return addPairToJSMap.addPairToJSMap(ctx, pair, this);
}
toString(ctx, onComment, onChompKeep) {
return ctx?.doc
? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)
: JSON.stringify(this);
}
}
exports.Pair = Pair;
exports.createPair = createPair;
/***/ }),
/***/ 9338:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var toJS = __nccwpck_require__(2463);
const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
class Scalar extends Node.NodeBase {
constructor(value) {
super(Node.SCALAR);
this.value = value;
}
toJSON(arg, ctx) {
return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
}
toString() {
return String(this.value);
}
}
Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED';
Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL';
Scalar.PLAIN = 'PLAIN';
Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';
exports.Scalar = Scalar;
exports.isScalarValue = isScalarValue;
/***/ }),
/***/ 6011:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var stringifyCollection = __nccwpck_require__(2466);
var addPairToJSMap = __nccwpck_require__(4676);
var Collection = __nccwpck_require__(3466);
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var Scalar = __nccwpck_require__(9338);
function findPair(items, key) {
const k = Node.isScalar(key) ? key.value : key;
for (const it of items) {
if (Node.isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (Node.isScalar(it.key) && it.key.value === k)
return it;
}
}
return undefined;
}
class YAMLMap extends Collection.Collection {
static get tagName() {
return 'tag:yaml.org,2002:map';
}
constructor(schema) {
super(Node.MAP, schema);
this.items = [];
}
/**
* Adds a value to the collection.
*
* @param overwrite - If not set `true`, using a key that is already in the
* collection will throw. Otherwise, overwrites the previous value.
*/
add(pair, overwrite) {
let _pair;
if (Node.isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
// In TypeScript, this never happens.
_pair = new Pair.Pair(pair, pair?.value);
}
else
_pair = new Pair.Pair(pair.key, pair.value);
const prev = findPair(this.items, _pair.key);
const sortEntries = this.schema?.sortMapEntries;
if (prev) {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
// For scalars, keep the old node & its comments and anchors
if (Node.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
}
else if (sortEntries) {
const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);
if (i === -1)
this.items.push(_pair);
else
this.items.splice(i, 0, _pair);
}
else {
this.items.push(_pair);
}
}
delete(key) {
const it = findPair(this.items, key);
if (!it)
return false;
const del = this.items.splice(this.items.indexOf(it), 1);
return del.length > 0;
}
get(key, keepScalar) {
const it = findPair(this.items, key);
const node = it?.value;
return (!keepScalar && Node.isScalar(node) ? node.value : node) ?? undefined;
}
has(key) {
return !!findPair(this.items, key);
}
set(key, value) {
this.add(new Pair.Pair(key, value), true);
}
/**
* @param ctx - Conversion context, originally set in Document#toJS()
* @param {Class} Type - If set, forces the returned collection type
* @returns Instance of Type, Map, or Object
*/
toJSON(_, ctx, Type) {
const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};
if (ctx?.onCreate)
ctx.onCreate(map);
for (const item of this.items)
addPairToJSMap.addPairToJSMap(ctx, map, item);
return map;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!Node.isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))
ctx = Object.assign({}, ctx, { allNullValues: true });
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: '',
flowChars: { start: '{', end: '}' },
itemIndent: ctx.indent || '',
onChompKeep,
onComment
});
}
}
exports.YAMLMap = YAMLMap;
exports.findPair = findPair;
/***/ }),
/***/ 5161:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var stringifyCollection = __nccwpck_require__(2466);
var Collection = __nccwpck_require__(3466);
var Node = __nccwpck_require__(1399);
var Scalar = __nccwpck_require__(9338);
var toJS = __nccwpck_require__(2463);
class YAMLSeq extends Collection.Collection {
static get tagName() {
return 'tag:yaml.org,2002:seq';
}
constructor(schema) {
super(Node.SEQ, schema);
this.items = [];
}
add(value) {
this.items.push(value);
}
/**
* Removes a value from the collection.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*
* @returns `true` if the item was found and removed.
*/
delete(key) {
const idx = asItemIndex(key);
if (typeof idx !== 'number')
return false;
const del = this.items.splice(idx, 1);
return del.length > 0;
}
get(key, keepScalar) {
const idx = asItemIndex(key);
if (typeof idx !== 'number')
return undefined;
const it = this.items[idx];
return !keepScalar && Node.isScalar(it) ? it.value : it;
}
/**
* Checks if the collection includes a value with the key `key`.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*/
has(key) {
const idx = asItemIndex(key);
return typeof idx === 'number' && idx < this.items.length;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*
* If `key` does not contain a representation of an integer, this will throw.
* It may be wrapped in a `Scalar`.
*/
set(key, value) {
const idx = asItemIndex(key);
if (typeof idx !== 'number')
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (Node.isScalar(prev) && Scalar.isScalarValue(value))
prev.value = value;
else
this.items[idx] = value;
}
toJSON(_, ctx) {
const seq = [];
if (ctx?.onCreate)
ctx.onCreate(seq);
let i = 0;
for (const item of this.items)
seq.push(toJS.toJS(item, String(i++), ctx));
return seq;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: '- ',
flowChars: { start: '[', end: ']' },
itemIndent: (ctx.indent || '') + ' ',
onChompKeep,
onComment
});
}
}
function asItemIndex(key) {
let idx = Node.isScalar(key) ? key.value : key;
if (idx && typeof idx === 'string')
idx = Number(idx);
return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0
? idx
: null;
}
exports.YAMLSeq = YAMLSeq;
/***/ }),
/***/ 4676:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var log = __nccwpck_require__(6909);
var stringify = __nccwpck_require__(8409);
var Node = __nccwpck_require__(1399);
var Scalar = __nccwpck_require__(9338);
var toJS = __nccwpck_require__(2463);
const MERGE_KEY = '<<';
function addPairToJSMap(ctx, map, { key, value }) {
if (ctx?.doc.schema.merge && isMergeKey(key)) {
value = Node.isAlias(value) ? value.resolve(ctx.doc) : value;
if (Node.isSeq(value))
for (const it of value.items)
mergeToJSMap(ctx, map, it);
else if (Array.isArray(value))
for (const it of value)
mergeToJSMap(ctx, map, it);
else
mergeToJSMap(ctx, map, value);
}
else {
const jsKey = toJS.toJS(key, '', ctx);
if (map instanceof Map) {
map.set(jsKey, toJS.toJS(value, jsKey, ctx));
}
else if (map instanceof Set) {
map.add(jsKey);
}
else {
const stringKey = stringifyKey(key, jsKey, ctx);
const jsValue = toJS.toJS(value, stringKey, ctx);
if (stringKey in map)
Object.defineProperty(map, stringKey, {
value: jsValue,
writable: true,
enumerable: true,
configurable: true
});
else
map[stringKey] = jsValue;
}
}
return map;
}
const isMergeKey = (key) => key === MERGE_KEY ||
(Node.isScalar(key) &&
key.value === MERGE_KEY &&
(!key.type || key.type === Scalar.Scalar.PLAIN));
// If the value associated with a merge key is a single mapping node, each of
// its key/value pairs is inserted into the current mapping, unless the key
// already exists in it. If the value associated with the merge key is a
// sequence, then this sequence is expected to contain mapping nodes and each
// of these nodes is merged in turn according to its order in the sequence.
// Keys in mapping nodes earlier in the sequence override keys specified in
// later mapping nodes. -- http://yaml.org/type/merge.html
function mergeToJSMap(ctx, map, value) {
const source = ctx && Node.isAlias(value) ? value.resolve(ctx.doc) : value;
if (!Node.isMap(source))
throw new Error('Merge sources must be maps or map aliases');
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value] of srcMap) {
if (map instanceof Map) {
if (!map.has(key))
map.set(key, value);
}
else if (map instanceof Set) {
map.add(key);
}
else if (!Object.prototype.hasOwnProperty.call(map, key)) {
Object.defineProperty(map, key, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
}
return map;
}
function stringifyKey(key, jsKey, ctx) {
if (jsKey === null)
return '';
if (typeof jsKey !== 'object')
return String(jsKey);
if (Node.isNode(key) && ctx && ctx.doc) {
const strCtx = stringify.createStringifyContext(ctx.doc, {});
strCtx.anchors = new Set();
for (const node of ctx.anchors.keys())
strCtx.anchors.add(node.anchor);
strCtx.inFlow = true;
strCtx.inStringifyKey = true;
const strKey = key.toString(strCtx);
if (!ctx.mapKeyWarned) {
let jsonStr = JSON.stringify(strKey);
if (jsonStr.length > 40)
jsonStr = jsonStr.substring(0, 36) + '..."';
log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
ctx.mapKeyWarned = true;
}
return strKey;
}
return JSON.stringify(jsKey);
}
exports.addPairToJSMap = addPairToJSMap;
/***/ }),
/***/ 2463:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
/**
* Recursively convert any node or its contents to native JavaScript
*
* @param value - The input value
* @param arg - If `value` defines a `toJSON()` method, use this
* as its first argument
* @param ctx - Conversion context, originally set in Document#toJS(). If
* `{ keep: true }` is not set, output should be suitable for JSON
* stringification.
*/
function toJS(value, arg, ctx) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
if (Array.isArray(value))
return value.map((v, i) => toJS(v, String(i), ctx));
if (value && typeof value.toJSON === 'function') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
if (!ctx || !Node.hasAnchor(value))
return value.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: undefined };
ctx.anchors.set(value, data);
ctx.onCreate = res => {
data.res = res;
delete ctx.onCreate;
};
const res = value.toJSON(arg, ctx);
if (ctx.onCreate)
ctx.onCreate(res);
return res;
}
if (typeof value === 'bigint' && !ctx?.keep)
return Number(value);
return value;
}
exports.toJS = toJS;
/***/ }),
/***/ 9027:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var resolveBlockScalar = __nccwpck_require__(9485);
var resolveFlowScalar = __nccwpck_require__(7578);
var errors = __nccwpck_require__(4236);
var stringifyString = __nccwpck_require__(6226);
function resolveAsScalar(token, strict = true, onError) {
if (token) {
const _onError = (pos, code, message) => {
const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
if (onError)
onError(offset, code, message);
else
throw new errors.YAMLParseError([offset, offset + 1], code, message);
};
switch (token.type) {
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
case 'block-scalar':
return resolveBlockScalar.resolveBlockScalar(token, strict, _onError);
}
}
return null;
}
/**
* Create a new scalar token with `value`
*
* Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
* as this function does not support any schema operations and won't check for such conflicts.
*
* @param value The string representation of the value, which will have its content properly indented.
* @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
* @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
* @param context.indent The indent level of the token.
* @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
* @param context.offset The offset position of the token.
* @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
*/
function createScalarToken(value, context) {
const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;
const source = stringifyString.stringifyString({ type, value }, {
implicitKey,
indent: indent > 0 ? ' '.repeat(indent) : '',
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
const end = context.end ?? [
{ type: 'newline', offset: -1, indent, source: '\n' }
];
switch (source[0]) {
case '|':
case '>': {
const he = source.indexOf('\n');
const head = source.substring(0, he);
const body = source.substring(he + 1) + '\n';
const props = [
{ type: 'block-scalar-header', offset, indent, source: head }
];
if (!addEndtoBlockProps(props, end))
props.push({ type: 'newline', offset: -1, indent, source: '\n' });
return { type: 'block-scalar', offset, indent, props, source: body };
}
case '"':
return { type: 'double-quoted-scalar', offset, indent, source, end };
case "'":
return { type: 'single-quoted-scalar', offset, indent, source, end };
default:
return { type: 'scalar', offset, indent, source, end };
}
}
/**
* Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.
*
* Best efforts are made to retain any comments previously associated with the `token`,
* though all contents within a collection's `items` will be overwritten.
*
* Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,
* as this function does not support any schema operations and won't check for such conflicts.
*
* @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.
* @param value The string representation of the value, which will have its content properly indented.
* @param context.afterKey In most cases, values after a key should have an additional level of indentation.
* @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
* @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.
* @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.
*/
function setScalarValue(token, value, context = {}) {
let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
let indent = 'indent' in token ? token.indent : null;
if (afterKey && typeof indent === 'number')
indent += 2;
if (!type)
switch (token.type) {
case 'single-quoted-scalar':
type = 'QUOTE_SINGLE';
break;
case 'double-quoted-scalar':
type = 'QUOTE_DOUBLE';
break;
case 'block-scalar': {
const header = token.props[0];
if (header.type !== 'block-scalar-header')
throw new Error('Invalid block scalar header');
type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';
break;
}
default:
type = 'PLAIN';
}
const source = stringifyString.stringifyString({ type, value }, {
implicitKey: implicitKey || indent === null,
indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
switch (source[0]) {
case '|':
case '>':
setBlockScalarValue(token, source);
break;
case '"':
setFlowScalarValue(token, source, 'double-quoted-scalar');
break;
case "'":
setFlowScalarValue(token, source, 'single-quoted-scalar');
break;
default:
setFlowScalarValue(token, source, 'scalar');
}
}
function setBlockScalarValue(token, source) {
const he = source.indexOf('\n');
const head = source.substring(0, he);
const body = source.substring(he + 1) + '\n';
if (token.type === 'block-scalar') {
const header = token.props[0];
if (header.type !== 'block-scalar-header')
throw new Error('Invalid block scalar header');
header.source = head;
token.source = body;
}
else {
const { offset } = token;
const indent = 'indent' in token ? token.indent : -1;
const props = [
{ type: 'block-scalar-header', offset, indent, source: head }
];
if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))
props.push({ type: 'newline', offset: -1, indent, source: '\n' });
for (const key of Object.keys(token))
if (key !== 'type' && key !== 'offset')
delete token[key];
Object.assign(token, { type: 'block-scalar', indent, props, source: body });
}
}
/** @returns `true` if last token is a newline */
function addEndtoBlockProps(props, end) {
if (end)
for (const st of end)
switch (st.type) {
case 'space':
case 'comment':
props.push(st);
break;
case 'newline':
props.push(st);
return true;
}
return false;
}
function setFlowScalarValue(token, source, type) {
switch (token.type) {
case 'scalar':
case 'double-quoted-scalar':
case 'single-quoted-scalar':
token.type = type;
token.source = source;
break;
case 'block-scalar': {
const end = token.props.slice(1);
let oa = source.length;
if (token.props[0].type === 'block-scalar-header')
oa -= token.props[0].source.length;
for (const tok of end)
tok.offset += oa;
delete token.props;
Object.assign(token, { type, source, end });
break;
}
case 'block-map':
case 'block-seq': {
const offset = token.offset + source.length;
const nl = { type: 'newline', offset, indent: token.indent, source: '\n' };
delete token.items;
Object.assign(token, { type, source, end: [nl] });
break;
}
default: {
const indent = 'indent' in token ? token.indent : -1;
const end = 'end' in token && Array.isArray(token.end)
? token.end.filter(st => st.type === 'space' ||
st.type === 'comment' ||
st.type === 'newline')
: [];
for (const key of Object.keys(token))
if (key !== 'type' && key !== 'offset')
delete token[key];
Object.assign(token, { type, indent, source, end });
}
}
}
exports.createScalarToken = createScalarToken;
exports.resolveAsScalar = resolveAsScalar;
exports.setScalarValue = setScalarValue;
/***/ }),
/***/ 6307:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/**
* Stringify a CST document, token, or collection item
*
* Fair warning: This applies no validation whatsoever, and
* simply concatenates the sources in their logical order.
*/
const stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);
function stringifyToken(token) {
switch (token.type) {
case 'block-scalar': {
let res = '';
for (const tok of token.props)
res += stringifyToken(tok);
return res + token.source;
}
case 'block-map':
case 'block-seq': {
let res = '';
for (const item of token.items)
res += stringifyItem(item);
return res;
}
case 'flow-collection': {
let res = token.start.source;
for (const item of token.items)
res += stringifyItem(item);
for (const st of token.end)
res += st.source;
return res;
}
case 'document': {
let res = stringifyItem(token);
if (token.end)
for (const st of token.end)
res += st.source;
return res;
}
default: {
let res = token.source;
if ('end' in token && token.end)
for (const st of token.end)
res += st.source;
return res;
}
}
}
function stringifyItem({ start, key, sep, value }) {
let res = '';
for (const st of start)
res += st.source;
if (key)
res += stringifyToken(key);
if (sep)
for (const st of sep)
res += st.source;
if (value)
res += stringifyToken(value);
return res;
}
exports.stringify = stringify;
/***/ }),
/***/ 8497:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
const BREAK = Symbol('break visit');
const SKIP = Symbol('skip children');
const REMOVE = Symbol('remove item');
/**
* Apply a visitor to a CST document or item.
*
* Walks through the tree (depth-first) starting from the root, calling a
* `visitor` function with two arguments when entering each item:
* - `item`: The current item, which included the following members:
* - `start: SourceToken[]` Source tokens before the key or value,
* possibly including its anchor or tag.
* - `key?: Token | null` Set for pair values. May then be `null`, if
* the key before the `:` separator is empty.
* - `sep?: SourceToken[]` Source tokens between the key and the value,
* which should include the `:` map value indicator if `value` is set.
* - `value?: Token` The value of a sequence item, or of a map pair.
* - `path`: The steps from the root to the current node, as an array of
* `['key' | 'value', number]` tuples.
*
* The return value of the visitor may be used to control the traversal:
* - `undefined` (default): Do nothing and continue
* - `visit.SKIP`: Do not visit the children of this token, continue with
* next sibling
* - `visit.BREAK`: Terminate traversal completely
* - `visit.REMOVE`: Remove the current item, then continue with the next one
* - `number`: Set the index of the next step. This is useful especially if
* the index of the current token has changed.
* - `function`: Define the next visitor for this item. After the original
* visitor is called on item entry, next visitors are called after handling
* a non-empty `key` and when exiting the item.
*/
function visit(cst, visitor) {
if ('type' in cst && cst.type === 'document')
cst = { start: cst.start, value: cst.value };
_visit(Object.freeze([]), cst, visitor);
}
// Without the `as symbol` casts, TS declares these in the `visit`
// namespace using `var`, but then complains about that because
// `unique symbol` must be `const`.
/** Terminate visit traversal completely */
visit.BREAK = BREAK;
/** Do not visit the children of the current item */
visit.SKIP = SKIP;
/** Remove the current item */
visit.REMOVE = REMOVE;
/** Find the item at `path` from `cst` as the root */
visit.itemAtPath = (cst, path) => {
let item = cst;
for (const [field, index] of path) {
const tok = item?.[field];
if (tok && 'items' in tok) {
item = tok.items[index];
}
else
return undefined;
}
return item;
};
/**
* Get the immediate parent collection of the item at `path` from `cst` as the root.
*
* Throws an error if the collection is not found, which should never happen if the item itself exists.
*/
visit.parentCollection = (cst, path) => {
const parent = visit.itemAtPath(cst, path.slice(0, -1));
const field = path[path.length - 1][0];
const coll = parent?.[field];
if (coll && 'items' in coll)
return coll;
throw new Error('Parent collection not found');
};
function _visit(path, item, visitor) {
let ctrl = visitor(item, path);
if (typeof ctrl === 'symbol')
return ctrl;
for (const field of ['key', 'value']) {
const token = item[field];
if (token && 'items' in token) {
for (let i = 0; i < token.items.length; ++i) {
const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
if (typeof ci === 'number')
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
token.items.splice(i, 1);
i -= 1;
}
}
if (typeof ctrl === 'function' && field === 'key')
ctrl = ctrl(item, path);
}
}
return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;
}
exports.visit = visit;
/***/ }),
/***/ 9169:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var cstScalar = __nccwpck_require__(9027);
var cstStringify = __nccwpck_require__(6307);
var cstVisit = __nccwpck_require__(8497);
/** The byte order mark */
const BOM = '\u{FEFF}';
/** Start of doc-mode */
const DOCUMENT = '\x02'; // C0: Start of Text
/** Unexpected end of flow-mode */
const FLOW_END = '\x18'; // C0: Cancel
/** Next token is a scalar value */
const SCALAR = '\x1f'; // C0: Unit Separator
/** @returns `true` if `token` is a flow or block collection */
const isCollection = (token) => !!token && 'items' in token;
/** @returns `true` if `token` is a flow or block scalar; not an alias */
const isScalar = (token) => !!token &&
(token.type === 'scalar' ||
token.type === 'single-quoted-scalar' ||
token.type === 'double-quoted-scalar' ||
token.type === 'block-scalar');
/* istanbul ignore next */
/** Get a printable representation of a lexer token */
function prettyToken(token) {
switch (token) {
case BOM:
return '<BOM>';
case DOCUMENT:
return '<DOC>';
case FLOW_END:
return '<FLOW_END>';
case SCALAR:
return '<SCALAR>';
default:
return JSON.stringify(token);
}
}
/** Identify the type of a lexer token. May return `null` for unknown tokens. */
function tokenType(source) {
switch (source) {
case BOM:
return 'byte-order-mark';
case DOCUMENT:
return 'doc-mode';
case FLOW_END:
return 'flow-error-end';
case SCALAR:
return 'scalar';
case '---':
return 'doc-start';
case '...':
return 'doc-end';
case '':
case '\n':
case '\r\n':
return 'newline';
case '-':
return 'seq-item-ind';
case '?':
return 'explicit-key-ind';
case ':':
return 'map-value-ind';
case '{':
return 'flow-map-start';
case '}':
return 'flow-map-end';
case '[':
return 'flow-seq-start';
case ']':
return 'flow-seq-end';
case ',':
return 'comma';
}
switch (source[0]) {
case ' ':
case '\t':
return 'space';
case '#':
return 'comment';
case '%':
return 'directive-line';
case '*':
return 'alias';
case '&':
return 'anchor';
case '!':
return 'tag';
case "'":
return 'single-quoted-scalar';
case '"':
return 'double-quoted-scalar';
case '|':
case '>':
return 'block-scalar-header';
}
return null;
}
exports.createScalarToken = cstScalar.createScalarToken;
exports.resolveAsScalar = cstScalar.resolveAsScalar;
exports.setScalarValue = cstScalar.setScalarValue;
exports.stringify = cstStringify.stringify;
exports.visit = cstVisit.visit;
exports.BOM = BOM;
exports.DOCUMENT = DOCUMENT;
exports.FLOW_END = FLOW_END;
exports.SCALAR = SCALAR;
exports.isCollection = isCollection;
exports.isScalar = isScalar;
exports.prettyToken = prettyToken;
exports.tokenType = tokenType;
/***/ }),
/***/ 5976:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var cst = __nccwpck_require__(9169);
/*
START -> stream
stream
directive -> line-end -> stream
indent + line-end -> stream
[else] -> line-start
line-end
comment -> line-end
newline -> .
input-end -> END
line-start
doc-start -> doc
doc-end -> stream
[else] -> indent -> block-start
block-start
seq-item-start -> block-start
explicit-key-start -> block-start
map-value-start -> block-start
[else] -> doc
doc
line-end -> line-start
spaces -> doc
anchor -> doc
tag -> doc
flow-start -> flow -> doc
flow-end -> error -> doc
seq-item-start -> error -> doc
explicit-key-start -> error -> doc
map-value-start -> doc
alias -> doc
quote-start -> quoted-scalar -> doc
block-scalar-header -> line-end -> block-scalar(min) -> line-start
[else] -> plain-scalar(false, min) -> doc
flow
line-end -> flow
spaces -> flow
anchor -> flow
tag -> flow
flow-start -> flow -> flow
flow-end -> .
seq-item-start -> error -> flow
explicit-key-start -> flow
map-value-start -> flow
alias -> flow
quote-start -> quoted-scalar -> flow
comma -> flow
[else] -> plain-scalar(true, 0) -> flow
quoted-scalar
quote-end -> .
[else] -> quoted-scalar
block-scalar(min)
newline + peek(indent < min) -> .
[else] -> block-scalar(min)
plain-scalar(is-flow, min)
scalar-end(is-flow) -> .
peek(newline + (indent < min)) -> .
[else] -> plain-scalar(min)
*/
function isEmpty(ch) {
switch (ch) {
case undefined:
case ' ':
case '\n':
case '\r':
case '\t':
return true;
default:
return false;
}
}
const hexDigits = '0123456789ABCDEFabcdef'.split('');
const tagChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split('');
const invalidFlowScalarChars = ',[]{}'.split('');
const invalidAnchorChars = ' ,[]{}\n\r\t'.split('');
const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.includes(ch);
/**
* Splits an input string into lexical tokens, i.e. smaller strings that are
* easily identifiable by `tokens.tokenType()`.
*
* Lexing starts always in a "stream" context. Incomplete input may be buffered
* until a complete token can be emitted.
*
* In addition to slices of the original input, the following control characters
* may also be emitted:
*
* - `\x02` (Start of Text): A document starts with the next token
* - `\x18` (Cancel): Unexpected end of flow-mode (indicates an error)
* - `\x1f` (Unit Separator): Next token is a scalar value
* - `\u{FEFF}` (Byte order mark): Emitted separately outside documents
*/
class Lexer {
constructor() {
/**
* Flag indicating whether the end of the current buffer marks the end of
* all input
*/
this.atEnd = false;
/**
* Explicit indent set in block scalar header, as an offset from the current
* minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not
* explicitly set.
*/
this.blockScalarIndent = -1;
/**
* Block scalars that include a + (keep) chomping indicator in their header
* include trailing empty lines, which are otherwise excluded from the
* scalar's contents.
*/
this.blockScalarKeep = false;
/** Current input */
this.buffer = '';
/**
* Flag noting whether the map value indicator : can immediately follow this
* node within a flow context.
*/
this.flowKey = false;
/** Count of surrounding flow collection levels. */
this.flowLevel = 0;
/**
* Minimum level of indentation required for next lines to be parsed as a
* part of the current scalar value.
*/
this.indentNext = 0;
/** Indentation level of the current line. */
this.indentValue = 0;
/** Position of the next \n character. */
this.lineEndPos = null;
/** Stores the state of the lexer if reaching the end of incpomplete input */
this.next = null;
/** A pointer to `buffer`; the current position of the lexer. */
this.pos = 0;
}
/**
* Generate YAML tokens from the `source` string. If `incomplete`,
* a part of the last line may be left as a buffer for the next call.
*
* @returns A generator of lexical tokens
*/
*lex(source, incomplete = false) {
if (source) {
this.buffer = this.buffer ? this.buffer + source : source;
this.lineEndPos = null;
}
this.atEnd = !incomplete;
let next = this.next ?? 'stream';
while (next && (incomplete || this.hasChars(1)))
next = yield* this.parseNext(next);
}
atLineEnd() {
let i = this.pos;
let ch = this.buffer[i];
while (ch === ' ' || ch === '\t')
ch = this.buffer[++i];
if (!ch || ch === '#' || ch === '\n')
return true;
if (ch === '\r')
return this.buffer[i + 1] === '\n';
return false;
}
charAt(n) {
return this.buffer[this.pos + n];
}
continueScalar(offset) {
let ch = this.buffer[offset];
if (this.indentNext > 0) {
let indent = 0;
while (ch === ' ')
ch = this.buffer[++indent + offset];
if (ch === '\r') {
const next = this.buffer[indent + offset + 1];
if (next === '\n' || (!next && !this.atEnd))
return offset + indent + 1;
}
return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd)
? offset + indent
: -1;
}
if (ch === '-' || ch === '.') {
const dt = this.buffer.substr(offset, 3);
if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))
return -1;
}
return offset;
}
getLine() {
let end = this.lineEndPos;
if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {
end = this.buffer.indexOf('\n', this.pos);
this.lineEndPos = end;
}
if (end === -1)
return this.atEnd ? this.buffer.substring(this.pos) : null;
if (this.buffer[end - 1] === '\r')
end -= 1;
return this.buffer.substring(this.pos, end);
}
hasChars(n) {
return this.pos + n <= this.buffer.length;
}
setNext(state) {
this.buffer = this.buffer.substring(this.pos);
this.pos = 0;
this.lineEndPos = null;
this.next = state;
return null;
}
peek(n) {
return this.buffer.substr(this.pos, n);
}
*parseNext(next) {
switch (next) {
case 'stream':
return yield* this.parseStream();
case 'line-start':
return yield* this.parseLineStart();
case 'block-start':
return yield* this.parseBlockStart();
case 'doc':
return yield* this.parseDocument();
case 'flow':
return yield* this.parseFlowCollection();
case 'quoted-scalar':
return yield* this.parseQuotedScalar();
case 'block-scalar':
return yield* this.parseBlockScalar();
case 'plain-scalar':
return yield* this.parsePlainScalar();
}
}
*parseStream() {
let line = this.getLine();
if (line === null)
return this.setNext('stream');
if (line[0] === cst.BOM) {
yield* this.pushCount(1);
line = line.substring(1);
}
if (line[0] === '%') {
let dirEnd = line.length;
const cs = line.indexOf('#');
if (cs !== -1) {
const ch = line[cs - 1];
if (ch === ' ' || ch === '\t')
dirEnd = cs - 1;
}
while (true) {
const ch = line[dirEnd - 1];
if (ch === ' ' || ch === '\t')
dirEnd -= 1;
else
break;
}
const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
yield* this.pushCount(line.length - n); // possible comment
this.pushNewline();
return 'stream';
}
if (this.atLineEnd()) {
const sp = yield* this.pushSpaces(true);
yield* this.pushCount(line.length - sp);
yield* this.pushNewline();
return 'stream';
}
yield cst.DOCUMENT;
return yield* this.parseLineStart();
}
*parseLineStart() {
const ch = this.charAt(0);
if (!ch && !this.atEnd)
return this.setNext('line-start');
if (ch === '-' || ch === '.') {
if (!this.atEnd && !this.hasChars(4))
return this.setNext('line-start');
const s = this.peek(3);
if (s === '---' && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
this.indentValue = 0;
this.indentNext = 0;
return 'doc';
}
else if (s === '...' && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
return 'stream';
}
}
this.indentValue = yield* this.pushSpaces(false);
if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
this.indentNext = this.indentValue;
return yield* this.parseBlockStart();
}
*parseBlockStart() {
const [ch0, ch1] = this.peek(2);
if (!ch1 && !this.atEnd)
return this.setNext('block-start');
if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {
const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
this.indentNext = this.indentValue + 1;
this.indentValue += n;
return yield* this.parseBlockStart();
}
return 'doc';
}
*parseDocument() {
yield* this.pushSpaces(true);
const line = this.getLine();
if (line === null)
return this.setNext('doc');
let n = yield* this.pushIndicators();
switch (line[n]) {
case '#':
yield* this.pushCount(line.length - n);
// fallthrough
case undefined:
yield* this.pushNewline();
return yield* this.parseLineStart();
case '{':
case '[':
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel = 1;
return 'flow';
case '}':
case ']':
// this is an error
yield* this.pushCount(1);
return 'doc';
case '*':
yield* this.pushUntil(isNotAnchorChar);
return 'doc';
case '"':
case "'":
return yield* this.parseQuotedScalar();
case '|':
case '>':
n += yield* this.parseBlockScalarHeader();
n += yield* this.pushSpaces(true);
yield* this.pushCount(line.length - n);
yield* this.pushNewline();
return yield* this.parseBlockScalar();
default:
return yield* this.parsePlainScalar();
}
}
*parseFlowCollection() {
let nl, sp;
let indent = -1;
do {
nl = yield* this.pushNewline();
if (nl > 0) {
sp = yield* this.pushSpaces(false);
this.indentValue = indent = sp;
}
else {
sp = 0;
}
sp += yield* this.pushSpaces(true);
} while (nl + sp > 0);
const line = this.getLine();
if (line === null)
return this.setNext('flow');
if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||
(indent === 0 &&
(line.startsWith('---') || line.startsWith('...')) &&
isEmpty(line[3]))) {
// Allowing for the terminal ] or } at the same (rather than greater)
// indent level as the initial [ or { is technically invalid, but
// failing here would be surprising to users.
const atFlowEndMarker = indent === this.indentNext - 1 &&
this.flowLevel === 1 &&
(line[0] === ']' || line[0] === '}');
if (!atFlowEndMarker) {
// this is an error
this.flowLevel = 0;
yield cst.FLOW_END;
return yield* this.parseLineStart();
}
}
let n = 0;
while (line[n] === ',') {
n += yield* this.pushCount(1);
n += yield* this.pushSpaces(true);
this.flowKey = false;
}
n += yield* this.pushIndicators();
switch (line[n]) {
case undefined:
return 'flow';
case '#':
yield* this.pushCount(line.length - n);
return 'flow';
case '{':
case '[':
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel += 1;
return 'flow';
case '}':
case ']':
yield* this.pushCount(1);
this.flowKey = true;
this.flowLevel -= 1;
return this.flowLevel ? 'flow' : 'doc';
case '*':
yield* this.pushUntil(isNotAnchorChar);
return 'flow';
case '"':
case "'":
this.flowKey = true;
return yield* this.parseQuotedScalar();
case ':': {
const next = this.charAt(1);
if (this.flowKey || isEmpty(next) || next === ',') {
this.flowKey = false;
yield* this.pushCount(1);
yield* this.pushSpaces(true);
return 'flow';
}
}
// fallthrough
default:
this.flowKey = false;
return yield* this.parsePlainScalar();
}
}
*parseQuotedScalar() {
const quote = this.charAt(0);
let end = this.buffer.indexOf(quote, this.pos + 1);
if (quote === "'") {
while (end !== -1 && this.buffer[end + 1] === "'")
end = this.buffer.indexOf("'", end + 2);
}
else {
// double-quote
while (end !== -1) {
let n = 0;
while (this.buffer[end - 1 - n] === '\\')
n += 1;
if (n % 2 === 0)
break;
end = this.buffer.indexOf('"', end + 1);
}
}
// Only looking for newlines within the quotes
const qb = this.buffer.substring(0, end);
let nl = qb.indexOf('\n', this.pos);
if (nl !== -1) {
while (nl !== -1) {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = qb.indexOf('\n', cs);
}
if (nl !== -1) {
// this is an error caused by an unexpected unindent
end = nl - (qb[nl - 1] === '\r' ? 2 : 1);
}
}
if (end === -1) {
if (!this.atEnd)
return this.setNext('quoted-scalar');
end = this.buffer.length;
}
yield* this.pushToIndex(end + 1, false);
return this.flowLevel ? 'flow' : 'doc';
}
*parseBlockScalarHeader() {
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
let i = this.pos;
while (true) {
const ch = this.buffer[++i];
if (ch === '+')
this.blockScalarKeep = true;
else if (ch > '0' && ch <= '9')
this.blockScalarIndent = Number(ch) - 1;
else if (ch !== '-')
break;
}
return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');
}
*parseBlockScalar() {
let nl = this.pos - 1; // may be -1 if this.pos === 0
let indent = 0;
let ch;
loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {
switch (ch) {
case ' ':
indent += 1;
break;
case '\n':
nl = i;
indent = 0;
break;
case '\r': {
const next = this.buffer[i + 1];
if (!next && !this.atEnd)
return this.setNext('block-scalar');
if (next === '\n')
break;
} // fallthrough
default:
break loop;
}
}
if (!ch && !this.atEnd)
return this.setNext('block-scalar');
if (indent >= this.indentNext) {
if (this.blockScalarIndent === -1)
this.indentNext = indent;
else
this.indentNext += this.blockScalarIndent;
do {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = this.buffer.indexOf('\n', cs);
} while (nl !== -1);
if (nl === -1) {
if (!this.atEnd)
return this.setNext('block-scalar');
nl = this.buffer.length;
}
}
if (!this.blockScalarKeep) {
do {
let i = nl - 1;
let ch = this.buffer[i];
if (ch === '\r')
ch = this.buffer[--i];
const lastChar = i; // Drop the line if last char not more indented
while (ch === ' ' || ch === '\t')
ch = this.buffer[--i];
if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar)
nl = i;
else
break;
} while (true);
}
yield cst.SCALAR;
yield* this.pushToIndex(nl + 1, true);
return yield* this.parseLineStart();
}
*parsePlainScalar() {
const inFlow = this.flowLevel > 0;
let end = this.pos - 1;
let i = this.pos - 1;
let ch;
while ((ch = this.buffer[++i])) {
if (ch === ':') {
const next = this.buffer[i + 1];
if (isEmpty(next) || (inFlow && next === ','))
break;
end = i;
}
else if (isEmpty(ch)) {
let next = this.buffer[i + 1];
if (ch === '\r') {
if (next === '\n') {
i += 1;
ch = '\n';
next = this.buffer[i + 1];
}
else
end = i;
}
if (next === '#' || (inFlow && invalidFlowScalarChars.includes(next)))
break;
if (ch === '\n') {
const cs = this.continueScalar(i + 1);
if (cs === -1)
break;
i = Math.max(i, cs - 2); // to advance, but still account for ' #'
}
}
else {
if (inFlow && invalidFlowScalarChars.includes(ch))
break;
end = i;
}
}
if (!ch && !this.atEnd)
return this.setNext('plain-scalar');
yield cst.SCALAR;
yield* this.pushToIndex(end + 1, true);
return inFlow ? 'flow' : 'doc';
}
*pushCount(n) {
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos += n;
return n;
}
return 0;
}
*pushToIndex(i, allowEmpty) {
const s = this.buffer.slice(this.pos, i);
if (s) {
yield s;
this.pos += s.length;
return s.length;
}
else if (allowEmpty)
yield '';
return 0;
}
*pushIndicators() {
switch (this.charAt(0)) {
case '!':
return ((yield* this.pushTag()) +
(yield* this.pushSpaces(true)) +
(yield* this.pushIndicators()));
case '&':
return ((yield* this.pushUntil(isNotAnchorChar)) +
(yield* this.pushSpaces(true)) +
(yield* this.pushIndicators()));
case '-': // this is an error
case '?': // this is an error outside flow collections
case ':': {
const inFlow = this.flowLevel > 0;
const ch1 = this.charAt(1);
if (isEmpty(ch1) || (inFlow && invalidFlowScalarChars.includes(ch1))) {
if (!inFlow)
this.indentNext = this.indentValue + 1;
else if (this.flowKey)
this.flowKey = false;
return ((yield* this.pushCount(1)) +
(yield* this.pushSpaces(true)) +
(yield* this.pushIndicators()));
}
}
}
return 0;
}
*pushTag() {
if (this.charAt(1) === '<') {
let i = this.pos + 2;
let ch = this.buffer[i];
while (!isEmpty(ch) && ch !== '>')
ch = this.buffer[++i];
return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);
}
else {
let i = this.pos + 1;
let ch = this.buffer[i];
while (ch) {
if (tagChars.includes(ch))
ch = this.buffer[++i];
else if (ch === '%' &&
hexDigits.includes(this.buffer[i + 1]) &&
hexDigits.includes(this.buffer[i + 2])) {
ch = this.buffer[(i += 3)];
}
else
break;
}
return yield* this.pushToIndex(i, false);
}
}
*pushNewline() {
const ch = this.buffer[this.pos];
if (ch === '\n')
return yield* this.pushCount(1);
else if (ch === '\r' && this.charAt(1) === '\n')
return yield* this.pushCount(2);
else
return 0;
}
*pushSpaces(allowTabs) {
let i = this.pos - 1;
let ch;
do {
ch = this.buffer[++i];
} while (ch === ' ' || (allowTabs && ch === '\t'));
const n = i - this.pos;
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos = i;
}
return n;
}
*pushUntil(test) {
let i = this.pos;
let ch = this.buffer[i];
while (!test(ch))
ch = this.buffer[++i];
return yield* this.pushToIndex(i, false);
}
}
exports.Lexer = Lexer;
/***/ }),
/***/ 1929:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/**
* Tracks newlines during parsing in order to provide an efficient API for
* determining the one-indexed `{ line, col }` position for any offset
* within the input.
*/
class LineCounter {
constructor() {
this.lineStarts = [];
/**
* Should be called in ascending order. Otherwise, call
* `lineCounter.lineStarts.sort()` before calling `linePos()`.
*/
this.addNewLine = (offset) => this.lineStarts.push(offset);
/**
* Performs a binary search and returns the 1-indexed { line, col }
* position of `offset`. If `line === 0`, `addNewLine` has never been
* called or `offset` is before the first known newline.
*/
this.linePos = (offset) => {
let low = 0;
let high = this.lineStarts.length;
while (low < high) {
const mid = (low + high) >> 1; // Math.floor((low + high) / 2)
if (this.lineStarts[mid] < offset)
low = mid + 1;
else
high = mid;
}
if (this.lineStarts[low] === offset)
return { line: low + 1, col: 1 };
if (low === 0)
return { line: 0, col: offset };
const start = this.lineStarts[low - 1];
return { line: low, col: offset - start + 1 };
};
}
}
exports.LineCounter = LineCounter;
/***/ }),
/***/ 3328:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var cst = __nccwpck_require__(9169);
var lexer = __nccwpck_require__(5976);
function includesToken(list, type) {
for (let i = 0; i < list.length; ++i)
if (list[i].type === type)
return true;
return false;
}
function findNonEmptyIndex(list) {
for (let i = 0; i < list.length; ++i) {
switch (list[i].type) {
case 'space':
case 'comment':
case 'newline':
break;
default:
return i;
}
}
return -1;
}
function isFlowToken(token) {
switch (token?.type) {
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
case 'flow-collection':
return true;
default:
return false;
}
}
function getPrevProps(parent) {
switch (parent.type) {
case 'document':
return parent.start;
case 'block-map': {
const it = parent.items[parent.items.length - 1];
return it.sep ?? it.start;
}
case 'block-seq':
return parent.items[parent.items.length - 1].start;
/* istanbul ignore next should not happen */
default:
return [];
}
}
/** Note: May modify input array */
function getFirstKeyStartProps(prev) {
if (prev.length === 0)
return [];
let i = prev.length;
loop: while (--i >= 0) {
switch (prev[i].type) {
case 'doc-start':
case 'explicit-key-ind':
case 'map-value-ind':
case 'seq-item-ind':
case 'newline':
break loop;
}
}
while (prev[++i]?.type === 'space') {
/* loop */
}
return prev.splice(i, prev.length);
}
function fixFlowSeqItems(fc) {
if (fc.start.type === 'flow-seq-start') {
for (const it of fc.items) {
if (it.sep &&
!it.value &&
!includesToken(it.start, 'explicit-key-ind') &&
!includesToken(it.sep, 'map-value-ind')) {
if (it.key)
it.value = it.key;
delete it.key;
if (isFlowToken(it.value)) {
if (it.value.end)
Array.prototype.push.apply(it.value.end, it.sep);
else
it.value.end = it.sep;
}
else
Array.prototype.push.apply(it.start, it.sep);
delete it.sep;
}
}
}
}
/**
* A YAML concrete syntax tree (CST) parser
*
* ```ts
* const src: string = ...
* for (const token of new Parser().parse(src)) {
* // token: Token
* }
* ```
*
* To use the parser with a user-provided lexer:
*
* ```ts
* function* parse(source: string, lexer: Lexer) {
* const parser = new Parser()
* for (const lexeme of lexer.lex(source))
* yield* parser.next(lexeme)
* yield* parser.end()
* }
*
* const src: string = ...
* const lexer = new Lexer()
* for (const token of parse(src, lexer)) {
* // token: Token
* }
* ```
*/
class Parser {
/**
* @param onNewLine - If defined, called separately with the start position of
* each new line (in `parse()`, including the start of input).
*/
constructor(onNewLine) {
/** If true, space and sequence indicators count as indentation */
this.atNewLine = true;
/** If true, next token is a scalar value */
this.atScalar = false;
/** Current indentation level */
this.indent = 0;
/** Current offset since the start of parsing */
this.offset = 0;
/** On the same line with a block map key */
this.onKeyLine = false;
/** Top indicates the node that's currently being built */
this.stack = [];
/** The source of the current token, set in parse() */
this.source = '';
/** The type of the current token, set in parse() */
this.type = '';
// Must be defined after `next()`
this.lexer = new lexer.Lexer();
this.onNewLine = onNewLine;
}
/**
* Parse `source` as a YAML stream.
* If `incomplete`, a part of the last line may be left as a buffer for the next call.
*
* Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
*
* @returns A generator of tokens representing each directive, document, and other structure.
*/
*parse(source, incomplete = false) {
if (this.onNewLine && this.offset === 0)
this.onNewLine(0);
for (const lexeme of this.lexer.lex(source, incomplete))
yield* this.next(lexeme);
if (!incomplete)
yield* this.end();
}
/**
* Advance the parser by the `source` of one lexical token.
*/
*next(source) {
this.source = source;
if (process.env.LOG_TOKENS)
console.log('|', cst.prettyToken(source));
if (this.atScalar) {
this.atScalar = false;
yield* this.step();
this.offset += source.length;
return;
}
const type = cst.tokenType(source);
if (!type) {
const message = `Not a YAML token: ${source}`;
yield* this.pop({ type: 'error', offset: this.offset, message, source });
this.offset += source.length;
}
else if (type === 'scalar') {
this.atNewLine = false;
this.atScalar = true;
this.type = 'scalar';
}
else {
this.type = type;
yield* this.step();
switch (type) {
case 'newline':
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine)
this.onNewLine(this.offset + source.length);
break;
case 'space':
if (this.atNewLine && source[0] === ' ')
this.indent += source.length;
break;
case 'explicit-key-ind':
case 'map-value-ind':
case 'seq-item-ind':
if (this.atNewLine)
this.indent += source.length;
break;
case 'doc-mode':
case 'flow-error-end':
return;
default:
this.atNewLine = false;
}
this.offset += source.length;
}
}
/** Call at end of input to push out any remaining constructions */
*end() {
while (this.stack.length > 0)
yield* this.pop();
}
get sourceToken() {
const st = {
type: this.type,
offset: this.offset,
indent: this.indent,
source: this.source
};
return st;
}
*step() {
const top = this.peek(1);
if (this.type === 'doc-end' && (!top || top.type !== 'doc-end')) {
while (this.stack.length > 0)
yield* this.pop();
this.stack.push({
type: 'doc-end',
offset: this.offset,
source: this.source
});
return;
}
if (!top)
return yield* this.stream();
switch (top.type) {
case 'document':
return yield* this.document(top);
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
return yield* this.scalar(top);
case 'block-scalar':
return yield* this.blockScalar(top);
case 'block-map':
return yield* this.blockMap(top);
case 'block-seq':
return yield* this.blockSequence(top);
case 'flow-collection':
return yield* this.flowCollection(top);
case 'doc-end':
return yield* this.documentEnd(top);
}
/* istanbul ignore next should not happen */
yield* this.pop();
}
peek(n) {
return this.stack[this.stack.length - n];
}
*pop(error) {
const token = error ?? this.stack.pop();
/* istanbul ignore if should not happen */
if (!token) {
const message = 'Tried to pop an empty stack';
yield { type: 'error', offset: this.offset, source: '', message };
}
else if (this.stack.length === 0) {
yield token;
}
else {
const top = this.peek(1);
if (token.type === 'block-scalar') {
// Block scalars use their parent rather than header indent
token.indent = 'indent' in top ? top.indent : 0;
}
else if (token.type === 'flow-collection' && top.type === 'document') {
// Ignore all indent for top-level flow collections
token.indent = 0;
}
if (token.type === 'flow-collection')
fixFlowSeqItems(token);
switch (top.type) {
case 'document':
top.value = token;
break;
case 'block-scalar':
top.props.push(token); // error
break;
case 'block-map': {
const it = top.items[top.items.length - 1];
if (it.value) {
top.items.push({ start: [], key: token, sep: [] });
this.onKeyLine = true;
return;
}
else if (it.sep) {
it.value = token;
}
else {
Object.assign(it, { key: token, sep: [] });
this.onKeyLine = !includesToken(it.start, 'explicit-key-ind');
return;
}
break;
}
case 'block-seq': {
const it = top.items[top.items.length - 1];
if (it.value)
top.items.push({ start: [], value: token });
else
it.value = token;
break;
}
case 'flow-collection': {
const it = top.items[top.items.length - 1];
if (!it || it.value)
top.items.push({ start: [], key: token, sep: [] });
else if (it.sep)
it.value = token;
else
Object.assign(it, { key: token, sep: [] });
return;
}
/* istanbul ignore next should not happen */
default:
yield* this.pop();
yield* this.pop(token);
}
if ((top.type === 'document' ||
top.type === 'block-map' ||
top.type === 'block-seq') &&
(token.type === 'block-map' || token.type === 'block-seq')) {
const last = token.items[token.items.length - 1];
if (last &&
!last.sep &&
!last.value &&
last.start.length > 0 &&
findNonEmptyIndex(last.start) === -1 &&
(token.indent === 0 ||
last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {
if (top.type === 'document')
top.end = last.start;
else
top.items.push({ start: last.start });
token.items.splice(-1, 1);
}
}
}
}
*stream() {
switch (this.type) {
case 'directive-line':
yield { type: 'directive', offset: this.offset, source: this.source };
return;
case 'byte-order-mark':
case 'space':
case 'comment':
case 'newline':
yield this.sourceToken;
return;
case 'doc-mode':
case 'doc-start': {
const doc = {
type: 'document',
offset: this.offset,
start: []
};
if (this.type === 'doc-start')
doc.start.push(this.sourceToken);
this.stack.push(doc);
return;
}
}
yield {
type: 'error',
offset: this.offset,
message: `Unexpected ${this.type} token in YAML stream`,
source: this.source
};
}
*document(doc) {
if (doc.value)
return yield* this.lineEnd(doc);
switch (this.type) {
case 'doc-start': {
if (findNonEmptyIndex(doc.start) !== -1) {
yield* this.pop();
yield* this.step();
}
else
doc.start.push(this.sourceToken);
return;
}
case 'anchor':
case 'tag':
case 'space':
case 'comment':
case 'newline':
doc.start.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(doc);
if (bv)
this.stack.push(bv);
else {
yield {
type: 'error',
offset: this.offset,
message: `Unexpected ${this.type} token in YAML document`,
source: this.source
};
}
}
*scalar(scalar) {
if (this.type === 'map-value-ind') {
const prev = getPrevProps(this.peek(2));
const start = getFirstKeyStartProps(prev);
let sep;
if (scalar.end) {
sep = scalar.end;
sep.push(this.sourceToken);
delete scalar.end;
}
else
sep = [this.sourceToken];
const map = {
type: 'block-map',
offset: scalar.offset,
indent: scalar.indent,
items: [{ start, key: scalar, sep }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map;
}
else
yield* this.lineEnd(scalar);
}
*blockScalar(scalar) {
switch (this.type) {
case 'space':
case 'comment':
case 'newline':
scalar.props.push(this.sourceToken);
return;
case 'scalar':
scalar.source = this.source;
// block-scalar source includes trailing newline
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine) {
let nl = this.source.indexOf('\n') + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf('\n', nl) + 1;
}
}
yield* this.pop();
break;
/* istanbul ignore next should not happen */
default:
yield* this.pop();
yield* this.step();
}
}
*blockMap(map) {
const it = map.items[map.items.length - 1];
// it.sep is true-ish if pair already has key or : separator
switch (this.type) {
case 'newline':
this.onKeyLine = false;
if (it.value) {
const end = 'end' in it.value ? it.value.end : undefined;
const last = Array.isArray(end) ? end[end.length - 1] : undefined;
if (last?.type === 'comment')
end?.push(this.sourceToken);
else
map.items.push({ start: [this.sourceToken] });
}
else if (it.sep) {
it.sep.push(this.sourceToken);
}
else {
it.start.push(this.sourceToken);
}
return;
case 'space':
case 'comment':
if (it.value) {
map.items.push({ start: [this.sourceToken] });
}
else if (it.sep) {
it.sep.push(this.sourceToken);
}
else {
if (this.atIndentedComment(it.start, map.indent)) {
const prev = map.items[map.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
map.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
}
if (this.indent >= map.indent) {
const atNextItem = !this.onKeyLine && this.indent === map.indent && it.sep;
// For empty nodes, assign newline-separated not indented empty tokens to following node
let start = [];
if (atNextItem && it.sep && !it.value) {
const nl = [];
for (let i = 0; i < it.sep.length; ++i) {
const st = it.sep[i];
switch (st.type) {
case 'newline':
nl.push(i);
break;
case 'space':
break;
case 'comment':
if (st.indent > map.indent)
nl.length = 0;
break;
default:
nl.length = 0;
}
}
if (nl.length >= 2)
start = it.sep.splice(nl[1]);
}
switch (this.type) {
case 'anchor':
case 'tag':
if (atNextItem || it.value) {
start.push(this.sourceToken);
map.items.push({ start });
this.onKeyLine = true;
}
else if (it.sep) {
it.sep.push(this.sourceToken);
}
else {
it.start.push(this.sourceToken);
}
return;
case 'explicit-key-ind':
if (!it.sep && !includesToken(it.start, 'explicit-key-ind')) {
it.start.push(this.sourceToken);
}
else if (atNextItem || it.value) {
start.push(this.sourceToken);
map.items.push({ start });
}
else {
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
});
}
this.onKeyLine = true;
return;
case 'map-value-ind':
if (includesToken(it.start, 'explicit-key-ind')) {
if (!it.sep) {
if (includesToken(it.start, 'newline')) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
}
else {
const start = getFirstKeyStartProps(it.start);
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
});
}
}
else if (it.value) {
map.items.push({ start: [], key: null, sep: [this.sourceToken] });
}
else if (includesToken(it.sep, 'map-value-ind')) {
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
});
}
else if (isFlowToken(it.key) &&
!includesToken(it.sep, 'newline')) {
const start = getFirstKeyStartProps(it.start);
const key = it.key;
const sep = it.sep;
sep.push(this.sourceToken);
// @ts-expect-error type guard is wrong here
delete it.key, delete it.sep;
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start, key, sep }]
});
}
else if (start.length > 0) {
// Not actually at next item
it.sep = it.sep.concat(start, this.sourceToken);
}
else {
it.sep.push(this.sourceToken);
}
}
else {
if (!it.sep) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
}
else if (it.value || atNextItem) {
map.items.push({ start, key: null, sep: [this.sourceToken] });
}
else if (includesToken(it.sep, 'map-value-ind')) {
this.stack.push({
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
});
}
else {
it.sep.push(this.sourceToken);
}
}
this.onKeyLine = true;
return;
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar': {
const fs = this.flowScalar(this.type);
if (atNextItem || it.value) {
map.items.push({ start, key: fs, sep: [] });
this.onKeyLine = true;
}
else if (it.sep) {
this.stack.push(fs);
}
else {
Object.assign(it, { key: fs, sep: [] });
this.onKeyLine = true;
}
return;
}
default: {
const bv = this.startBlockValue(map);
if (bv) {
if (atNextItem &&
bv.type !== 'block-seq' &&
includesToken(it.start, 'explicit-key-ind')) {
map.items.push({ start });
}
this.stack.push(bv);
return;
}
}
}
}
yield* this.pop();
yield* this.step();
}
*blockSequence(seq) {
const it = seq.items[seq.items.length - 1];
switch (this.type) {
case 'newline':
if (it.value) {
const end = 'end' in it.value ? it.value.end : undefined;
const last = Array.isArray(end) ? end[end.length - 1] : undefined;
if (last?.type === 'comment')
end?.push(this.sourceToken);
else
seq.items.push({ start: [this.sourceToken] });
}
else
it.start.push(this.sourceToken);
return;
case 'space':
case 'comment':
if (it.value)
seq.items.push({ start: [this.sourceToken] });
else {
if (this.atIndentedComment(it.start, seq.indent)) {
const prev = seq.items[seq.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
seq.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
case 'anchor':
case 'tag':
if (it.value || this.indent <= seq.indent)
break;
it.start.push(this.sourceToken);
return;
case 'seq-item-ind':
if (this.indent !== seq.indent)
break;
if (it.value || includesToken(it.start, 'seq-item-ind'))
seq.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
}
if (this.indent > seq.indent) {
const bv = this.startBlockValue(seq);
if (bv) {
this.stack.push(bv);
return;
}
}
yield* this.pop();
yield* this.step();
}
*flowCollection(fc) {
const it = fc.items[fc.items.length - 1];
if (this.type === 'flow-error-end') {
let top;
do {
yield* this.pop();
top = this.peek(1);
} while (top && top.type === 'flow-collection');
}
else if (fc.end.length === 0) {
switch (this.type) {
case 'comma':
case 'explicit-key-ind':
if (!it || it.sep)
fc.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
case 'map-value-ind':
if (!it || it.value)
fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
Object.assign(it, { key: null, sep: [this.sourceToken] });
return;
case 'space':
case 'comment':
case 'newline':
case 'anchor':
case 'tag':
if (!it || it.value)
fc.items.push({ start: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
it.start.push(this.sourceToken);
return;
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar': {
const fs = this.flowScalar(this.type);
if (!it || it.value)
fc.items.push({ start: [], key: fs, sep: [] });
else if (it.sep)
this.stack.push(fs);
else
Object.assign(it, { key: fs, sep: [] });
return;
}
case 'flow-map-end':
case 'flow-seq-end':
fc.end.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(fc);
/* istanbul ignore else should not happen */
if (bv)
this.stack.push(bv);
else {
yield* this.pop();
yield* this.step();
}
}
else {
const parent = this.peek(2);
if (parent.type === 'block-map' &&
((this.type === 'map-value-ind' && parent.indent === fc.indent) ||
(this.type === 'newline' &&
!parent.items[parent.items.length - 1].sep))) {
yield* this.pop();
yield* this.step();
}
else if (this.type === 'map-value-ind' &&
parent.type !== 'flow-collection') {
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
fixFlowSeqItems(fc);
const sep = fc.end.splice(1, fc.end.length);
sep.push(this.sourceToken);
const map = {
type: 'block-map',
offset: fc.offset,
indent: fc.indent,
items: [{ start, key: fc, sep }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map;
}
else {
yield* this.lineEnd(fc);
}
}
}
flowScalar(type) {
if (this.onNewLine) {
let nl = this.source.indexOf('\n') + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf('\n', nl) + 1;
}
}
return {
type,
offset: this.offset,
indent: this.indent,
source: this.source
};
}
startBlockValue(parent) {
switch (this.type) {
case 'alias':
case 'scalar':
case 'single-quoted-scalar':
case 'double-quoted-scalar':
return this.flowScalar(this.type);
case 'block-scalar-header':
return {
type: 'block-scalar',
offset: this.offset,
indent: this.indent,
props: [this.sourceToken],
source: ''
};
case 'flow-map-start':
case 'flow-seq-start':
return {
type: 'flow-collection',
offset: this.offset,
indent: this.indent,
start: this.sourceToken,
items: [],
end: []
};
case 'seq-item-ind':
return {
type: 'block-seq',
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
};
case 'explicit-key-ind': {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
start.push(this.sourceToken);
return {
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start }]
};
}
case 'map-value-ind': {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
return {
type: 'block-map',
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
};
}
}
return null;
}
atIndentedComment(start, indent) {
if (this.type !== 'comment')
return false;
if (this.indent <= indent)
return false;
return start.every(st => st.type === 'newline' || st.type === 'space');
}
*documentEnd(docEnd) {
if (this.type !== 'doc-mode') {
if (docEnd.end)
docEnd.end.push(this.sourceToken);
else
docEnd.end = [this.sourceToken];
if (this.type === 'newline')
yield* this.pop();
}
}
*lineEnd(token) {
switch (this.type) {
case 'comma':
case 'doc-start':
case 'doc-end':
case 'flow-seq-end':
case 'flow-map-end':
case 'map-value-ind':
yield* this.pop();
yield* this.step();
break;
case 'newline':
this.onKeyLine = false;
// fallthrough
case 'space':
case 'comment':
default:
// all other values are errors
if (token.end)
token.end.push(this.sourceToken);
else
token.end = [this.sourceToken];
if (this.type === 'newline')
yield* this.pop();
}
}
}
exports.Parser = Parser;
/***/ }),
/***/ 8649:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var composer = __nccwpck_require__(9493);
var Document = __nccwpck_require__(42);
var errors = __nccwpck_require__(4236);
var log = __nccwpck_require__(6909);
var lineCounter = __nccwpck_require__(1929);
var parser = __nccwpck_require__(3328);
function parseOptions(options) {
const prettyErrors = options.prettyErrors !== false;
const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;
return { lineCounter: lineCounter$1, prettyErrors };
}
/**
* Parse the input as a stream of YAML documents.
*
* Documents should be separated from each other by `...` or `---` marker lines.
*
* @returns If an empty `docs` array is returned, it will be of type
* EmptyStream and contain additional stream information. In
* TypeScript, you should use `'empty' in docs` as a type guard for it.
*/
function parseAllDocuments(source, options = {}) {
const { lineCounter, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter?.addNewLine);
const composer$1 = new composer.Composer(options);
const docs = Array.from(composer$1.compose(parser$1.parse(source)));
if (prettyErrors && lineCounter)
for (const doc of docs) {
doc.errors.forEach(errors.prettifyError(source, lineCounter));
doc.warnings.forEach(errors.prettifyError(source, lineCounter));
}
if (docs.length > 0)
return docs;
return Object.assign([], { empty: true }, composer$1.streamInfo());
}
/** Parse an input string into a single YAML.Document */
function parseDocument(source, options = {}) {
const { lineCounter, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter?.addNewLine);
const composer$1 = new composer.Composer(options);
// `doc` is always set by compose.end(true) at the very latest
let doc = null;
for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
if (!doc)
doc = _doc;
else if (doc.options.logLevel !== 'silent') {
doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));
break;
}
}
if (prettyErrors && lineCounter) {
doc.errors.forEach(errors.prettifyError(source, lineCounter));
doc.warnings.forEach(errors.prettifyError(source, lineCounter));
}
return doc;
}
function parse(src, reviver, options) {
let _reviver = undefined;
if (typeof reviver === 'function') {
_reviver = reviver;
}
else if (options === undefined && reviver && typeof reviver === 'object') {
options = reviver;
}
const doc = parseDocument(src, options);
if (!doc)
return null;
doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));
if (doc.errors.length > 0) {
if (doc.options.logLevel !== 'silent')
throw doc.errors[0];
else
doc.errors = [];
}
return doc.toJS(Object.assign({ reviver: _reviver }, options));
}
function stringify(value, replacer, options) {
let _replacer = null;
if (typeof replacer === 'function' || Array.isArray(replacer)) {
_replacer = replacer;
}
else if (options === undefined && replacer) {
options = replacer;
}
if (typeof options === 'string')
options = options.length;
if (typeof options === 'number') {
const indent = Math.round(options);
options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
}
if (value === undefined) {
const { keepUndefined } = options ?? replacer ?? {};
if (!keepUndefined)
return undefined;
}
return new Document.Document(value, _replacer, options).toString(options);
}
exports.parse = parse;
exports.parseAllDocuments = parseAllDocuments;
exports.parseDocument = parseDocument;
exports.stringify = stringify;
/***/ }),
/***/ 6831:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var map = __nccwpck_require__(83);
var seq = __nccwpck_require__(1693);
var string = __nccwpck_require__(2201);
var tags = __nccwpck_require__(4138);
const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
class Schema {
constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
this.compat = Array.isArray(compat)
? tags.getTags(compat, 'compat')
: compat
? tags.getTags(null, compat)
: null;
this.merge = !!merge;
this.name = (typeof schema === 'string' && schema) || 'core';
this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
this.tags = tags.getTags(customTags, this.name);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, Node.MAP, { value: map.map });
Object.defineProperty(this, Node.SCALAR, { value: string.string });
Object.defineProperty(this, Node.SEQ, { value: seq.seq });
// Used by createMap()
this.sortMapEntries =
typeof sortMapEntries === 'function'
? sortMapEntries
: sortMapEntries === true
? sortMapEntriesByKey
: null;
}
clone() {
const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
copy.tags = this.tags.slice();
return copy;
}
}
exports.Schema = Schema;
/***/ }),
/***/ 83:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var YAMLMap = __nccwpck_require__(6011);
function createMap(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map = new YAMLMap.YAMLMap(schema);
const add = (key, value) => {
if (typeof replacer === 'function')
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== undefined || keepUndefined)
map.items.push(Pair.createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
}
else if (obj && typeof obj === 'object') {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === 'function') {
map.items.sort(schema.sortMapEntries);
}
return map;
}
const map = {
collection: 'map',
createNode: createMap,
default: true,
nodeClass: YAMLMap.YAMLMap,
tag: 'tag:yaml.org,2002:map',
resolve(map, onError) {
if (!Node.isMap(map))
onError('Expected a mapping for this tag');
return map;
}
};
exports.map = map;
/***/ }),
/***/ 6703:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
const nullTag = {
identify: value => value == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: 'tag:yaml.org,2002:null',
test: /^(?:~|[Nn]ull|NULL)?$/,
resolve: () => new Scalar.Scalar(null),
stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
? source
: ctx.options.nullStr
};
exports.nullTag = nullTag;
/***/ }),
/***/ 1693:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var createNode = __nccwpck_require__(9652);
var Node = __nccwpck_require__(1399);
var YAMLSeq = __nccwpck_require__(5161);
function createSeq(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new YAMLSeq.YAMLSeq(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === 'function') {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, undefined, ctx));
}
}
return seq;
}
const seq = {
collection: 'seq',
createNode: createSeq,
default: true,
nodeClass: YAMLSeq.YAMLSeq,
tag: 'tag:yaml.org,2002:seq',
resolve(seq, onError) {
if (!Node.isSeq(seq))
onError('Expected a sequence for this tag');
return seq;
}
};
exports.seq = seq;
/***/ }),
/***/ 2201:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var stringifyString = __nccwpck_require__(6226);
const string = {
identify: value => typeof value === 'string',
default: true,
tag: 'tag:yaml.org,2002:str',
resolve: str => str,
stringify(item, ctx, onComment, onChompKeep) {
ctx = Object.assign({ actualString: true }, ctx);
return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
}
};
exports.string = string;
/***/ }),
/***/ 2045:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
const boolTag = {
identify: value => typeof value === 'boolean',
default: true,
tag: 'tag:yaml.org,2002:bool',
test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),
stringify({ source, value }, ctx) {
if (source && boolTag.test.test(source)) {
const sv = source[0] === 't' || source[0] === 'T';
if (value === sv)
return source;
}
return value ? ctx.options.trueStr : ctx.options.falseStr;
}
};
exports.boolTag = boolTag;
/***/ }),
/***/ 6810:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
var stringifyNumber = __nccwpck_require__(4174);
const floatNaN = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
test: /^(?:[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN))$/,
resolve: str => str.slice(-3).toLowerCase() === 'nan'
? NaN
: str[0] === '-'
? Number.NEGATIVE_INFINITY
: Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
const floatExp = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
format: 'EXP',
test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
resolve: str => parseFloat(str),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
const float = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str));
const dot = str.indexOf('.');
if (dot !== -1 && str[str.length - 1] === '0')
node.minFractionDigits = str.length - dot - 1;
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports.float = float;
exports.floatExp = floatExp;
exports.floatNaN = floatNaN;
/***/ }),
/***/ 3019:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var stringifyNumber = __nccwpck_require__(4174);
const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
const intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
function intStringify(node, radix, prefix) {
const { value } = node;
if (intIdentify(value) && value >= 0)
return prefix + value.toString(radix);
return stringifyNumber.stringifyNumber(node);
}
const intOct = {
identify: value => intIdentify(value) && value >= 0,
default: true,
tag: 'tag:yaml.org,2002:int',
format: 'OCT',
test: /^0o[0-7]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
stringify: node => intStringify(node, 8, '0o')
};
const int = {
identify: intIdentify,
default: true,
tag: 'tag:yaml.org,2002:int',
test: /^[-+]?[0-9]+$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
const intHex = {
identify: value => intIdentify(value) && value >= 0,
default: true,
tag: 'tag:yaml.org,2002:int',
format: 'HEX',
test: /^0x[0-9a-fA-F]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: node => intStringify(node, 16, '0x')
};
exports.int = int;
exports.intHex = intHex;
exports.intOct = intOct;
/***/ }),
/***/ 27:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var map = __nccwpck_require__(83);
var _null = __nccwpck_require__(6703);
var seq = __nccwpck_require__(1693);
var string = __nccwpck_require__(2201);
var bool = __nccwpck_require__(2045);
var float = __nccwpck_require__(6810);
var int = __nccwpck_require__(3019);
const schema = [
map.map,
seq.seq,
string.string,
_null.nullTag,
bool.boolTag,
int.intOct,
int.int,
int.intHex,
float.floatNaN,
float.floatExp,
float.float
];
exports.schema = schema;
/***/ }),
/***/ 4673:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
var map = __nccwpck_require__(83);
var seq = __nccwpck_require__(1693);
function intIdentify(value) {
return typeof value === 'bigint' || Number.isInteger(value);
}
const stringifyJSON = ({ value }) => JSON.stringify(value);
const jsonScalars = [
{
identify: value => typeof value === 'string',
default: true,
tag: 'tag:yaml.org,2002:str',
resolve: str => str,
stringify: stringifyJSON
},
{
identify: value => value == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: 'tag:yaml.org,2002:null',
test: /^null$/,
resolve: () => null,
stringify: stringifyJSON
},
{
identify: value => typeof value === 'boolean',
default: true,
tag: 'tag:yaml.org,2002:bool',
test: /^true|false$/,
resolve: str => str === 'true',
stringify: stringifyJSON
},
{
identify: intIdentify,
default: true,
tag: 'tag:yaml.org,2002:int',
test: /^-?(?:0|[1-9][0-9]*)$/,
resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
},
{
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
resolve: str => parseFloat(str),
stringify: stringifyJSON
}
];
const jsonError = {
default: true,
tag: '',
test: /^/,
resolve(str, onError) {
onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
return str;
}
};
const schema = [map.map, seq.seq].concat(jsonScalars, jsonError);
exports.schema = schema;
/***/ }),
/***/ 4138:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var map = __nccwpck_require__(83);
var _null = __nccwpck_require__(6703);
var seq = __nccwpck_require__(1693);
var string = __nccwpck_require__(2201);
var bool = __nccwpck_require__(2045);
var float = __nccwpck_require__(6810);
var int = __nccwpck_require__(3019);
var schema = __nccwpck_require__(27);
var schema$1 = __nccwpck_require__(4673);
var binary = __nccwpck_require__(5724);
var omap = __nccwpck_require__(8974);
var pairs = __nccwpck_require__(9841);
var schema$2 = __nccwpck_require__(5389);
var set = __nccwpck_require__(7847);
var timestamp = __nccwpck_require__(1156);
const schemas = new Map([
['core', schema.schema],
['failsafe', [map.map, seq.seq, string.string]],
['json', schema$1.schema],
['yaml11', schema$2.schema],
['yaml-1.1', schema$2.schema]
]);
const tagsByName = {
binary: binary.binary,
bool: bool.boolTag,
float: float.float,
floatExp: float.floatExp,
floatNaN: float.floatNaN,
floatTime: timestamp.floatTime,
int: int.int,
intHex: int.intHex,
intOct: int.intOct,
intTime: timestamp.intTime,
map: map.map,
null: _null.nullTag,
omap: omap.omap,
pairs: pairs.pairs,
seq: seq.seq,
set: set.set,
timestamp: timestamp.timestamp
};
const coreKnownTags = {
'tag:yaml.org,2002:binary': binary.binary,
'tag:yaml.org,2002:omap': omap.omap,
'tag:yaml.org,2002:pairs': pairs.pairs,
'tag:yaml.org,2002:set': set.set,
'tag:yaml.org,2002:timestamp': timestamp.timestamp
};
function getTags(customTags, schemaName) {
let tags = schemas.get(schemaName);
if (!tags) {
if (Array.isArray(customTags))
tags = [];
else {
const keys = Array.from(schemas.keys())
.filter(key => key !== 'yaml11')
.map(key => JSON.stringify(key))
.join(', ');
throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
}
}
if (Array.isArray(customTags)) {
for (const tag of customTags)
tags = tags.concat(tag);
}
else if (typeof customTags === 'function') {
tags = customTags(tags.slice());
}
return tags.map(tag => {
if (typeof tag !== 'string')
return tag;
const tagObj = tagsByName[tag];
if (tagObj)
return tagObj;
const keys = Object.keys(tagsByName)
.map(key => JSON.stringify(key))
.join(', ');
throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
});
}
exports.coreKnownTags = coreKnownTags;
exports.getTags = getTags;
/***/ }),
/***/ 5724:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
var stringifyString = __nccwpck_require__(6226);
const binary = {
identify: value => value instanceof Uint8Array,
default: false,
tag: 'tag:yaml.org,2002:binary',
/**
* Returns a Buffer in node and an Uint8Array in browsers
*
* To use the resulting buffer as an image, you'll want to do something like:
*
* const blob = new Blob([buffer], { type: 'image/jpeg' })
* document.querySelector('#photo').src = URL.createObjectURL(blob)
*/
resolve(src, onError) {
if (typeof Buffer === 'function') {
return Buffer.from(src, 'base64');
}
else if (typeof atob === 'function') {
// On IE 11, atob() can't handle newlines
const str = atob(src.replace(/[\n\r]/g, ''));
const buffer = new Uint8Array(str.length);
for (let i = 0; i < str.length; ++i)
buffer[i] = str.charCodeAt(i);
return buffer;
}
else {
onError('This environment does not support reading binary tags; either Buffer or atob is required');
return src;
}
},
stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
const buf = value; // checked earlier by binary.identify()
let str;
if (typeof Buffer === 'function') {
str =
buf instanceof Buffer
? buf.toString('base64')
: Buffer.from(buf.buffer).toString('base64');
}
else if (typeof btoa === 'function') {
let s = '';
for (let i = 0; i < buf.length; ++i)
s += String.fromCharCode(buf[i]);
str = btoa(s);
}
else {
throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
}
if (!type)
type = Scalar.Scalar.BLOCK_LITERAL;
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
const n = Math.ceil(str.length / lineWidth);
const lines = new Array(n);
for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
lines[i] = str.substr(o, lineWidth);
}
str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\n' : ' ');
}
return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
}
};
exports.binary = binary;
/***/ }),
/***/ 2631:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
function boolStringify({ value, source }, ctx) {
const boolObj = value ? trueTag : falseTag;
if (source && boolObj.test.test(source))
return source;
return value ? ctx.options.trueStr : ctx.options.falseStr;
}
const trueTag = {
identify: value => value === true,
default: true,
tag: 'tag:yaml.org,2002:bool',
test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
resolve: () => new Scalar.Scalar(true),
stringify: boolStringify
};
const falseTag = {
identify: value => value === false,
default: true,
tag: 'tag:yaml.org,2002:bool',
test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,
resolve: () => new Scalar.Scalar(false),
stringify: boolStringify
};
exports.falseTag = falseTag;
exports.trueTag = trueTag;
/***/ }),
/***/ 8035:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
var stringifyNumber = __nccwpck_require__(4174);
const floatNaN = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
test: /^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
? NaN
: str[0] === '-'
? Number.NEGATIVE_INFINITY
: Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
const floatExp = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
format: 'EXP',
test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str.replace(/_/g, '')),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
const float = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));
const dot = str.indexOf('.');
if (dot !== -1) {
const f = str.substring(dot + 1).replace(/_/g, '');
if (f[f.length - 1] === '0')
node.minFractionDigits = f.length;
}
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports.float = float;
exports.floatExp = floatExp;
exports.floatNaN = floatNaN;
/***/ }),
/***/ 9503:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var stringifyNumber = __nccwpck_require__(4174);
const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
function intResolve(str, offset, radix, { intAsBigInt }) {
const sign = str[0];
if (sign === '-' || sign === '+')
offset += 1;
str = str.substring(offset).replace(/_/g, '');
if (intAsBigInt) {
switch (radix) {
case 2:
str = `0b${str}`;
break;
case 8:
str = `0o${str}`;
break;
case 16:
str = `0x${str}`;
break;
}
const n = BigInt(str);
return sign === '-' ? BigInt(-1) * n : n;
}
const n = parseInt(str, radix);
return sign === '-' ? -1 * n : n;
}
function intStringify(node, radix, prefix) {
const { value } = node;
if (intIdentify(value)) {
const str = value.toString(radix);
return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
}
return stringifyNumber.stringifyNumber(node);
}
const intBin = {
identify: intIdentify,
default: true,
tag: 'tag:yaml.org,2002:int',
format: 'BIN',
test: /^[-+]?0b[0-1_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
stringify: node => intStringify(node, 2, '0b')
};
const intOct = {
identify: intIdentify,
default: true,
tag: 'tag:yaml.org,2002:int',
format: 'OCT',
test: /^[-+]?0[0-7_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
stringify: node => intStringify(node, 8, '0')
};
const int = {
identify: intIdentify,
default: true,
tag: 'tag:yaml.org,2002:int',
test: /^[-+]?[0-9][0-9_]*$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
const intHex = {
identify: intIdentify,
default: true,
tag: 'tag:yaml.org,2002:int',
format: 'HEX',
test: /^[-+]?0x[0-9a-fA-F_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: node => intStringify(node, 16, '0x')
};
exports.int = int;
exports.intBin = intBin;
exports.intHex = intHex;
exports.intOct = intOct;
/***/ }),
/***/ 8974:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var YAMLSeq = __nccwpck_require__(5161);
var toJS = __nccwpck_require__(2463);
var Node = __nccwpck_require__(1399);
var YAMLMap = __nccwpck_require__(6011);
var pairs = __nccwpck_require__(9841);
class YAMLOMap extends YAMLSeq.YAMLSeq {
constructor() {
super();
this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
this.tag = YAMLOMap.tag;
}
/**
* If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
* but TypeScript won't allow widening the signature of a child method.
*/
toJSON(_, ctx) {
if (!ctx)
return super.toJSON(_);
const map = new Map();
if (ctx?.onCreate)
ctx.onCreate(map);
for (const pair of this.items) {
let key, value;
if (Node.isPair(pair)) {
key = toJS.toJS(pair.key, '', ctx);
value = toJS.toJS(pair.value, key, ctx);
}
else {
key = toJS.toJS(pair, '', ctx);
}
if (map.has(key))
throw new Error('Ordered maps must not include duplicate keys');
map.set(key, value);
}
return map;
}
}
YAMLOMap.tag = 'tag:yaml.org,2002:omap';
const omap = {
collection: 'seq',
identify: value => value instanceof Map,
nodeClass: YAMLOMap,
default: false,
tag: 'tag:yaml.org,2002:omap',
resolve(seq, onError) {
const pairs$1 = pairs.resolvePairs(seq, onError);
const seenKeys = [];
for (const { key } of pairs$1.items) {
if (Node.isScalar(key)) {
if (seenKeys.includes(key.value)) {
onError(`Ordered maps must not include duplicate keys: ${key.value}`);
}
else {
seenKeys.push(key.value);
}
}
}
return Object.assign(new YAMLOMap(), pairs$1);
},
createNode(schema, iterable, ctx) {
const pairs$1 = pairs.createPairs(schema, iterable, ctx);
const omap = new YAMLOMap();
omap.items = pairs$1.items;
return omap;
}
};
exports.YAMLOMap = YAMLOMap;
exports.omap = omap;
/***/ }),
/***/ 9841:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var Scalar = __nccwpck_require__(9338);
var YAMLSeq = __nccwpck_require__(5161);
function resolvePairs(seq, onError) {
if (Node.isSeq(seq)) {
for (let i = 0; i < seq.items.length; ++i) {
let item = seq.items[i];
if (Node.isPair(item))
continue;
else if (Node.isMap(item)) {
if (item.items.length > 1)
onError('Each pair must have its own sequence indicator');
const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
if (item.commentBefore)
pair.key.commentBefore = pair.key.commentBefore
? `${item.commentBefore}\n${pair.key.commentBefore}`
: item.commentBefore;
if (item.comment) {
const cn = pair.value ?? pair.key;
cn.comment = cn.comment
? `${item.comment}\n${cn.comment}`
: item.comment;
}
item = pair;
}
seq.items[i] = Node.isPair(item) ? item : new Pair.Pair(item);
}
}
else
onError('Expected a sequence for this tag');
return seq;
}
function createPairs(schema, iterable, ctx) {
const { replacer } = ctx;
const pairs = new YAMLSeq.YAMLSeq(schema);
pairs.tag = 'tag:yaml.org,2002:pairs';
let i = 0;
if (iterable && Symbol.iterator in Object(iterable))
for (let it of iterable) {
if (typeof replacer === 'function')
it = replacer.call(iterable, String(i++), it);
let key, value;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = it[1];
}
else
throw new TypeError(`Expected [key, value] tuple: ${it}`);
}
else if (it && it instanceof Object) {
const keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value = it[key];
}
else
throw new TypeError(`Expected { key: value } tuple: ${it}`);
}
else {
key = it;
}
pairs.items.push(Pair.createPair(key, value, ctx));
}
return pairs;
}
const pairs = {
collection: 'seq',
default: false,
tag: 'tag:yaml.org,2002:pairs',
resolve: resolvePairs,
createNode: createPairs
};
exports.createPairs = createPairs;
exports.pairs = pairs;
exports.resolvePairs = resolvePairs;
/***/ }),
/***/ 5389:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var map = __nccwpck_require__(83);
var _null = __nccwpck_require__(6703);
var seq = __nccwpck_require__(1693);
var string = __nccwpck_require__(2201);
var binary = __nccwpck_require__(5724);
var bool = __nccwpck_require__(2631);
var float = __nccwpck_require__(8035);
var int = __nccwpck_require__(9503);
var omap = __nccwpck_require__(8974);
var pairs = __nccwpck_require__(9841);
var set = __nccwpck_require__(7847);
var timestamp = __nccwpck_require__(1156);
const schema = [
map.map,
seq.seq,
string.string,
_null.nullTag,
bool.trueTag,
bool.falseTag,
int.intBin,
int.intOct,
int.int,
int.intHex,
float.floatNaN,
float.floatExp,
float.float,
binary.binary,
omap.omap,
pairs.pairs,
set.set,
timestamp.intTime,
timestamp.floatTime,
timestamp.timestamp
];
exports.schema = schema;
/***/ }),
/***/ 7847:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Pair = __nccwpck_require__(246);
var YAMLMap = __nccwpck_require__(6011);
class YAMLSet extends YAMLMap.YAMLMap {
constructor(schema) {
super(schema);
this.tag = YAMLSet.tag;
}
add(key) {
let pair;
if (Node.isPair(key))
pair = key;
else if (key &&
typeof key === 'object' &&
'key' in key &&
'value' in key &&
key.value === null)
pair = new Pair.Pair(key.key, null);
else
pair = new Pair.Pair(key, null);
const prev = YAMLMap.findPair(this.items, pair.key);
if (!prev)
this.items.push(pair);
}
/**
* If `keepPair` is `true`, returns the Pair matching `key`.
* Otherwise, returns the value of that Pair's key.
*/
get(key, keepPair) {
const pair = YAMLMap.findPair(this.items, key);
return !keepPair && Node.isPair(pair)
? Node.isScalar(pair.key)
? pair.key.value
: pair.key
: pair;
}
set(key, value) {
if (typeof value !== 'boolean')
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
const prev = YAMLMap.findPair(this.items, key);
if (prev && !value) {
this.items.splice(this.items.indexOf(prev), 1);
}
else if (!prev && value) {
this.items.push(new Pair.Pair(key));
}
}
toJSON(_, ctx) {
return super.toJSON(_, ctx, Set);
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
if (this.hasAllNullValues(true))
return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
else
throw new Error('Set items must all have null values');
}
}
YAMLSet.tag = 'tag:yaml.org,2002:set';
const set = {
collection: 'map',
identify: value => value instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: 'tag:yaml.org,2002:set',
resolve(map, onError) {
if (Node.isMap(map)) {
if (map.hasAllNullValues(true))
return Object.assign(new YAMLSet(), map);
else
onError('Set items must all have null values');
}
else
onError('Expected a mapping for this tag');
return map;
},
createNode(schema, iterable, ctx) {
const { replacer } = ctx;
const set = new YAMLSet(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === 'function')
value = replacer.call(iterable, value, value);
set.items.push(Pair.createPair(value, null, ctx));
}
return set;
}
};
exports.YAMLSet = YAMLSet;
exports.set = set;
/***/ }),
/***/ 1156:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var stringifyNumber = __nccwpck_require__(4174);
/** Internal types handle bigint as number, because TS can't figure it out. */
function parseSexagesimal(str, asBigInt) {
const sign = str[0];
const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
const num = (n) => asBigInt ? BigInt(n) : Number(n);
const res = parts
.replace(/_/g, '')
.split(':')
.reduce((res, p) => res * num(60) + num(p), num(0));
return (sign === '-' ? num(-1) * res : res);
}
/**
* hhhh:mm:ss.sss
*
* Internal types handle bigint as number, because TS can't figure it out.
*/
function stringifySexagesimal(node) {
let { value } = node;
let num = (n) => n;
if (typeof value === 'bigint')
num = n => BigInt(n);
else if (isNaN(value) || !isFinite(value))
return stringifyNumber.stringifyNumber(node);
let sign = '';
if (value < 0) {
sign = '-';
value *= num(-1);
}
const _60 = num(60);
const parts = [value % _60]; // seconds, including ms
if (value < 60) {
parts.unshift(0); // at least one : is required
}
else {
value = (value - parts[0]) / _60;
parts.unshift(value % _60); // minutes
if (value >= 60) {
value = (value - parts[0]) / _60;
parts.unshift(value); // hours
}
}
return (sign +
parts
.map(n => (n < 10 ? '0' + String(n) : String(n)))
.join(':')
.replace(/000000\d*$/, '') // % 60 may introduce error
);
}
const intTime = {
identify: value => typeof value === 'bigint' || Number.isInteger(value),
default: true,
tag: 'tag:yaml.org,2002:int',
format: 'TIME',
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
stringify: stringifySexagesimal
};
const floatTime = {
identify: value => typeof value === 'number',
default: true,
tag: 'tag:yaml.org,2002:float',
format: 'TIME',
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
resolve: str => parseSexagesimal(str, false),
stringify: stringifySexagesimal
};
const timestamp = {
identify: value => value instanceof Date,
default: true,
tag: 'tag:yaml.org,2002:timestamp',
// If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
// may be omitted altogether, resulting in a date format. In such a case, the time part is
// assumed to be 00:00:00Z (start of day, UTC).
test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
'(?:' + // time is optional
'(?:t|T|[ \\t]+)' + // t | T | whitespace
'([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
'(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
')?$'),
resolve(str) {
const match = str.match(timestamp.test);
if (!match)
throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
const [, year, month, day, hour, minute, second] = match.map(Number);
const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
const tz = match[8];
if (tz && tz !== 'Z') {
let d = parseSexagesimal(tz, false);
if (Math.abs(d) < 30)
d *= 60;
date -= 60000 * d;
}
return new Date(date);
},
stringify: ({ value }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '')
};
exports.floatTime = floatTime;
exports.intTime = intTime;
exports.timestamp = timestamp;
/***/ }),
/***/ 2889:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
const FOLD_FLOW = 'flow';
const FOLD_BLOCK = 'block';
const FOLD_QUOTED = 'quoted';
/**
* Tries to keep input at up to `lineWidth` characters, splitting only on spaces
* not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
* terminated with `\n` and started with `indent`.
*/
function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
if (!lineWidth || lineWidth < 0)
return text;
const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
if (text.length <= endStep)
return text;
const folds = [];
const escapedFolds = {};
let end = lineWidth - indent.length;
if (typeof indentAtStart === 'number') {
if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
folds.push(0);
else
end = lineWidth - indentAtStart;
}
let split = undefined;
let prev = undefined;
let overflow = false;
let i = -1;
let escStart = -1;
let escEnd = -1;
if (mode === FOLD_BLOCK) {
i = consumeMoreIndentedLines(text, i);
if (i !== -1)
end = i + endStep;
}
for (let ch; (ch = text[(i += 1)]);) {
if (mode === FOLD_QUOTED && ch === '\\') {
escStart = i;
switch (text[i + 1]) {
case 'x':
i += 3;
break;
case 'u':
i += 5;
break;
case 'U':
i += 9;
break;
default:
i += 1;
}
escEnd = i;
}
if (ch === '\n') {
if (mode === FOLD_BLOCK)
i = consumeMoreIndentedLines(text, i);
end = i + endStep;
split = undefined;
}
else {
if (ch === ' ' &&
prev &&
prev !== ' ' &&
prev !== '\n' &&
prev !== '\t') {
// space surrounded by non-space can be replaced with newline + indent
const next = text[i + 1];
if (next && next !== ' ' && next !== '\n' && next !== '\t')
split = i;
}
if (i >= end) {
if (split) {
folds.push(split);
end = split + endStep;
split = undefined;
}
else if (mode === FOLD_QUOTED) {
// white-space collected at end may stretch past lineWidth
while (prev === ' ' || prev === '\t') {
prev = ch;
ch = text[(i += 1)];
overflow = true;
}
// Account for newline escape, but don't break preceding escape
const j = i > escEnd + 1 ? i - 2 : escStart - 1;
// Bail out if lineWidth & minContentWidth are shorter than an escape string
if (escapedFolds[j])
return text;
folds.push(j);
escapedFolds[j] = true;
end = j + endStep;
split = undefined;
}
else {
overflow = true;
}
}
}
prev = ch;
}
if (overflow && onOverflow)
onOverflow();
if (folds.length === 0)
return text;
if (onFold)
onFold();
let res = text.slice(0, folds[0]);
for (let i = 0; i < folds.length; ++i) {
const fold = folds[i];
const end = folds[i + 1] || text.length;
if (fold === 0)
res = `\n${indent}${text.slice(0, end)}`;
else {
if (mode === FOLD_QUOTED && escapedFolds[fold])
res += `${text[fold]}\\`;
res += `\n${indent}${text.slice(fold + 1, end)}`;
}
}
return res;
}
/**
* Presumes `i + 1` is at the start of a line
* @returns index of last newline in more-indented block
*/
function consumeMoreIndentedLines(text, i) {
let ch = text[i + 1];
while (ch === ' ' || ch === '\t') {
do {
ch = text[(i += 1)];
} while (ch && ch !== '\n');
ch = text[i + 1];
}
return i;
}
exports.FOLD_BLOCK = FOLD_BLOCK;
exports.FOLD_FLOW = FOLD_FLOW;
exports.FOLD_QUOTED = FOLD_QUOTED;
exports.foldFlowLines = foldFlowLines;
/***/ }),
/***/ 8409:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var anchors = __nccwpck_require__(8459);
var Node = __nccwpck_require__(1399);
var stringifyComment = __nccwpck_require__(5182);
var stringifyString = __nccwpck_require__(6226);
function createStringifyContext(doc, options) {
const opt = Object.assign({
blockQuote: true,
commentString: stringifyComment.stringifyComment,
defaultKeyType: null,
defaultStringType: 'PLAIN',
directives: null,
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: 'false',
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
nullStr: 'null',
simpleKeys: false,
singleQuote: null,
trueStr: 'true',
verifyAliasOrder: true
}, doc.schema.toStringOptions, options);
let inFlow;
switch (opt.collectionStyle) {
case 'block':
inFlow = false;
break;
case 'flow':
inFlow = true;
break;
default:
inFlow = null;
}
return {
anchors: new Set(),
doc,
flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',
indent: '',
indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',
inFlow,
options: opt
};
}
function getTagObject(tags, item) {
if (item.tag) {
const match = tags.filter(t => t.tag === item.tag);
if (match.length > 0)
return match.find(t => t.format === item.format) ?? match[0];
}
let tagObj = undefined;
let obj;
if (Node.isScalar(item)) {
obj = item.value;
const match = tags.filter(t => t.identify?.(obj));
tagObj =
match.find(t => t.format === item.format) ?? match.find(t => !t.format);
}
else {
obj = item;
tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
}
if (!tagObj) {
const name = obj?.constructor?.name ?? typeof obj;
throw new Error(`Tag not resolved for ${name} value`);
}
return tagObj;
}
// needs to be called before value stringifier to allow for circular anchor refs
function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
if (!doc.directives)
return '';
const props = [];
const anchor = (Node.isScalar(node) || Node.isCollection(node)) && node.anchor;
if (anchor && anchors.anchorIsValid(anchor)) {
anchors$1.add(anchor);
props.push(`&${anchor}`);
}
const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag;
if (tag)
props.push(doc.directives.tagString(tag));
return props.join(' ');
}
function stringify(item, ctx, onComment, onChompKeep) {
if (Node.isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (Node.isAlias(item)) {
if (ctx.doc.directives)
return item.toString(ctx);
if (ctx.resolvedAliases?.has(item)) {
throw new TypeError(`Cannot stringify circular structure without alias nodes`);
}
else {
if (ctx.resolvedAliases)
ctx.resolvedAliases.add(item);
else
ctx.resolvedAliases = new Set([item]);
item = item.resolve(ctx.doc);
}
}
let tagObj = undefined;
const node = Node.isNode(item)
? item
: ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
if (!tagObj)
tagObj = getTagObject(ctx.doc.schema.tags, node);
const props = stringifyProps(node, tagObj, ctx);
if (props.length > 0)
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
const str = typeof tagObj.stringify === 'function'
? tagObj.stringify(node, ctx, onComment, onChompKeep)
: Node.isScalar(node)
? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)
: node.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return Node.isScalar(node) || str[0] === '{' || str[0] === '['
? `${props} ${str}`
: `${props}\n${ctx.indent}${str}`;
}
exports.createStringifyContext = createStringifyContext;
exports.stringify = stringify;
/***/ }),
/***/ 2466:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Collection = __nccwpck_require__(3466);
var Node = __nccwpck_require__(1399);
var stringify = __nccwpck_require__(8409);
var stringifyComment = __nccwpck_require__(5182);
function stringifyCollection(collection, ctx, options) {
const flow = ctx.inFlow ?? collection.flow;
const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
return stringify(collection, ctx, options);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
const { indent, options: { commentString } } = ctx;
const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
let chompKeep = false; // flag for the preceding node's status
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (Node.isNode(item)) {
if (!chompKeep && item.spaceBefore)
lines.push('');
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment = item.comment;
}
else if (Node.isPair(item)) {
const ik = Node.isNode(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push('');
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
}
}
chompKeep = false;
let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));
if (comment)
str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
if (chompKeep && comment)
chompKeep = false;
lines.push(blockItemPrefix + str);
}
let str;
if (lines.length === 0) {
str = flowChars.start + flowChars.end;
}
else {
str = lines[0];
for (let i = 1; i < lines.length; ++i) {
const line = lines[i];
str += line ? `\n${indent}${line}` : '\n';
}
}
if (comment) {
str += '\n' + stringifyComment.indentComment(commentString(comment), indent);
if (onComment)
onComment();
}
else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
function stringifyFlowCollection({ comment, items }, ctx, { flowChars, itemIndent, onComment }) {
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
inFlow: true,
type: null
});
let reqNewline = false;
let linesAtValue = 0;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (Node.isNode(item)) {
if (item.spaceBefore)
lines.push('');
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
}
else if (Node.isPair(item)) {
const ik = Node.isNode(item.key) ? item.key : null;
if (ik) {
if (ik.spaceBefore)
lines.push('');
addCommentBefore(ctx, lines, ik.commentBefore, false);
if (ik.comment)
reqNewline = true;
}
const iv = Node.isNode(item.value) ? item.value : null;
if (iv) {
if (iv.comment)
comment = iv.comment;
if (iv.commentBefore)
reqNewline = true;
}
else if (item.value == null && ik && ik.comment) {
comment = ik.comment;
}
}
if (comment)
reqNewline = true;
let str = stringify.stringify(item, itemCtx, () => (comment = null));
if (i < items.length - 1)
str += ',';
if (comment)
str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
if (!reqNewline && (lines.length > linesAtValue || str.includes('\n')))
reqNewline = true;
lines.push(str);
linesAtValue = lines.length;
}
let str;
const { start, end } = flowChars;
if (lines.length === 0) {
str = start + end;
}
else {
if (!reqNewline) {
const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
reqNewline = len > Collection.Collection.maxFlowStringSingleLineLength;
}
if (reqNewline) {
str = start;
for (const line of lines)
str += line ? `\n${indentStep}${indent}${line}` : '\n';
str += `\n${indent}${end}`;
}
else {
str = `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;
}
}
if (comment) {
str += stringifyComment.lineComment(str, commentString(comment), indent);
if (onComment)
onComment();
}
return str;
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
if (comment && chompKeep)
comment = comment.replace(/^\n+/, '');
if (comment) {
const ic = stringifyComment.indentComment(commentString(comment), indent);
lines.push(ic.trimStart()); // Avoid double indent on first line
}
}
exports.stringifyCollection = stringifyCollection;
/***/ }),
/***/ 5182:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
/**
* Stringifies a comment.
*
* Empty comment lines are left empty,
* lines consisting of a single space are replaced by `#`,
* and all other lines are prefixed with a `#`.
*/
const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
function indentComment(comment, indent) {
if (/^\n+$/.test(comment))
return comment.substring(1);
return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
const lineComment = (str, indent, comment) => str.endsWith('\n')
? indentComment(comment, indent)
: comment.includes('\n')
? '\n' + indentComment(comment, indent)
: (str.endsWith(' ') ? '' : ' ') + comment;
exports.indentComment = indentComment;
exports.lineComment = lineComment;
exports.stringifyComment = stringifyComment;
/***/ }),
/***/ 5225:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var stringify = __nccwpck_require__(8409);
var stringifyComment = __nccwpck_require__(5182);
function stringifyDocument(doc, options) {
const lines = [];
let hasDirectives = options.directives === true;
if (options.directives !== false && doc.directives) {
const dir = doc.directives.toString(doc);
if (dir) {
lines.push(dir);
hasDirectives = true;
}
else if (doc.directives.docStart)
hasDirectives = true;
}
if (hasDirectives)
lines.push('---');
const ctx = stringify.createStringifyContext(doc, options);
const { commentString } = ctx.options;
if (doc.commentBefore) {
if (lines.length !== 1)
lines.unshift('');
const cs = commentString(doc.commentBefore);
lines.unshift(stringifyComment.indentComment(cs, ''));
}
let chompKeep = false;
let contentComment = null;
if (doc.contents) {
if (Node.isNode(doc.contents)) {
if (doc.contents.spaceBefore && hasDirectives)
lines.push('');
if (doc.contents.commentBefore) {
const cs = commentString(doc.contents.commentBefore);
lines.push(stringifyComment.indentComment(cs, ''));
}
// top-level block scalars need to be indented if followed by a comment
ctx.forceBlockIndent = !!doc.comment;
contentComment = doc.contents.comment;
}
const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);
if (contentComment)
body += stringifyComment.lineComment(body, '', commentString(contentComment));
if ((body[0] === '|' || body[0] === '>') &&
lines[lines.length - 1] === '---') {
// Top-level block scalars with a preceding doc marker ought to use the
// same line for their header.
lines[lines.length - 1] = `--- ${body}`;
}
else
lines.push(body);
}
else {
lines.push(stringify.stringify(doc.contents, ctx));
}
if (doc.directives?.docEnd) {
if (doc.comment) {
const cs = commentString(doc.comment);
if (cs.includes('\n')) {
lines.push('...');
lines.push(stringifyComment.indentComment(cs, ''));
}
else {
lines.push(`... ${cs}`);
}
}
else {
lines.push('...');
}
}
else {
let dc = doc.comment;
if (dc && chompKeep)
dc = dc.replace(/^\n+/, '');
if (dc) {
if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
lines.push('');
lines.push(stringifyComment.indentComment(commentString(dc), ''));
}
}
return lines.join('\n') + '\n';
}
exports.stringifyDocument = stringifyDocument;
/***/ }),
/***/ 4174:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
function stringifyNumber({ format, minFractionDigits, tag, value }) {
if (typeof value === 'bigint')
return String(value);
const num = typeof value === 'number' ? value : Number(value);
if (!isFinite(num))
return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
let n = JSON.stringify(value);
if (!format &&
minFractionDigits &&
(!tag || tag === 'tag:yaml.org,2002:float') &&
/^\d/.test(n)) {
let i = n.indexOf('.');
if (i < 0) {
i = n.length;
n += '.';
}
let d = minFractionDigits - (n.length - i - 1);
while (d-- > 0)
n += '0';
}
return n;
}
exports.stringifyNumber = stringifyNumber;
/***/ }),
/***/ 4875:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
var Scalar = __nccwpck_require__(9338);
var stringify = __nccwpck_require__(8409);
var stringifyComment = __nccwpck_require__(5182);
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = (Node.isNode(key) && key.comment) || null;
if (simpleKeys) {
if (keyComment) {
throw new Error('With simple keys, key nodes cannot have comments');
}
if (Node.isCollection(key)) {
const msg = 'With simple keys, collection cannot be used as a key value';
throw new Error(msg);
}
}
let explicitKey = !simpleKeys &&
(!key ||
(keyComment && value == null && !ctx.inFlow) ||
Node.isCollection(key) ||
(Node.isScalar(key)
? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL
: typeof key === 'object'));
ctx = Object.assign({}, ctx, {
allNullValues: false,
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
indent: indent + indentStep
});
let keyCommentDone = false;
let chompKeep = false;
let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));
if (!explicitKey && !ctx.inFlow && str.length > 1024) {
if (simpleKeys)
throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
explicitKey = true;
}
if (ctx.inFlow) {
if (allNullValues || value == null) {
if (keyCommentDone && onComment)
onComment();
return str === '' ? '?' : explicitKey ? `? ${str}` : str;
}
}
else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {
str = `? ${str}`;
if (keyComment && !keyCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
if (keyCommentDone)
keyComment = null;
if (explicitKey) {
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
str = `? ${str}\n${indent}:`;
}
else {
str = `${str}:`;
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
let vsb, vcb, valueComment;
if (Node.isNode(value)) {
vsb = !!value.spaceBefore;
vcb = value.commentBefore;
valueComment = value.comment;
}
else {
vsb = false;
vcb = null;
valueComment = null;
if (value && typeof value === 'object')
value = doc.createNode(value);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && Node.isScalar(value))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq &&
indentStep.length >= 2 &&
!ctx.inFlow &&
!explicitKey &&
Node.isSeq(value) &&
!value.flow &&
!value.tag &&
!value.anchor) {
// If indentSeq === false, consider '- ' as part of indentation where possible
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
let ws = ' ';
if (keyComment || vsb || vcb) {
ws = vsb ? '\n' : '';
if (vcb) {
const cs = commentString(vcb);
ws += `\n${stringifyComment.indentComment(cs, ctx.indent)}`;
}
if (valueStr === '' && !ctx.inFlow) {
if (ws === '\n')
ws = '\n\n';
}
else {
ws += `\n${ctx.indent}`;
}
}
else if (!explicitKey && Node.isCollection(value)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf('\n');
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === '&' || vs0 === '!')) {
let sp0 = valueStr.indexOf(' ');
if (vs0 === '&' &&
sp0 !== -1 &&
sp0 < nl0 &&
valueStr[sp0 + 1] === '!') {
sp0 = valueStr.indexOf(' ', sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `\n${ctx.indent}`;
}
}
else if (valueStr === '' || valueStr[0] === '\n') {
ws = '';
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)
onComment();
}
else if (valueComment && !valueCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
}
else if (chompKeep && onChompKeep) {
onChompKeep();
}
return str;
}
exports.stringifyPair = stringifyPair;
/***/ }),
/***/ 6226:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Scalar = __nccwpck_require__(9338);
var foldFlowLines = __nccwpck_require__(2889);
const getFoldOptions = (ctx) => ({
indentAtStart: ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
// Also checks for lines starting with %, as parsing the output as YAML 1.1 will
// presume that's starting a new document.
const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
if (!lineWidth || lineWidth < 0)
return false;
const limit = lineWidth - indentLength;
const strLen = str.length;
if (strLen <= limit)
return false;
for (let i = 0, start = 0; i < strLen; ++i) {
if (str[i] === '\n') {
if (i - start > limit)
return true;
start = i + 1;
if (strLen - start <= limit)
return false;
}
}
return true;
}
function doubleQuotedString(value, ctx) {
const json = JSON.stringify(value);
if (ctx.options.doubleQuotedAsJSON)
return json;
const { implicitKey } = ctx;
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
let str = '';
let start = 0;
for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
// space before newline needs to be escaped to not be folded
str += json.slice(start, i) + '\\ ';
i += 1;
start = i;
ch = '\\';
}
if (ch === '\\')
switch (json[i + 1]) {
case 'u':
{
str += json.slice(start, i);
const code = json.substr(i + 2, 4);
switch (code) {
case '0000':
str += '\\0';
break;
case '0007':
str += '\\a';
break;
case '000b':
str += '\\v';
break;
case '001b':
str += '\\e';
break;
case '0085':
str += '\\N';
break;
case '00a0':
str += '\\_';
break;
case '2028':
str += '\\L';
break;
case '2029':
str += '\\P';
break;
default:
if (code.substr(0, 2) === '00')
str += '\\x' + code.substr(2);
else
str += json.substr(i, 6);
}
i += 5;
start = i + 1;
}
break;
case 'n':
if (implicitKey ||
json[i + 2] === '"' ||
json.length < minMultiLineLength) {
i += 1;
}
else {
// folding will eat first newline
str += json.slice(start, i) + '\n\n';
while (json[i + 2] === '\\' &&
json[i + 3] === 'n' &&
json[i + 4] !== '"') {
str += '\n';
i += 2;
}
str += indent;
// space after newline needs to be escaped to not be folded
if (json[i + 2] === ' ')
str += '\\';
i += 1;
start = i + 1;
}
break;
default:
i += 1;
}
}
str = start ? str + json.slice(start) : json;
return implicitKey
? str
: foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx));
}
function singleQuotedString(value, ctx) {
if (ctx.options.singleQuote === false ||
(ctx.implicitKey && value.includes('\n')) ||
/[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline
)
return doubleQuotedString(value, ctx);
const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
return ctx.implicitKey
? res
: foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx));
}
function quotedString(value, ctx) {
const { singleQuote } = ctx.options;
let qs;
if (singleQuote === false)
qs = doubleQuotedString;
else {
const hasDouble = value.includes('"');
const hasSingle = value.includes("'");
if (hasDouble && !hasSingle)
qs = singleQuotedString;
else if (hasSingle && !hasDouble)
qs = doubleQuotedString;
else
qs = singleQuote ? singleQuotedString : doubleQuotedString;
}
return qs(value, ctx);
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
// 1. Block can't end in whitespace unless the last line is non-empty.
// 2. Strings consisting of only whitespace are best rendered explicitly.
if (!blockQuote || /\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
return quotedString(value, ctx);
}
const indent = ctx.indent ||
(ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');
const literal = blockQuote === 'literal'
? true
: blockQuote === 'folded' || type === Scalar.Scalar.BLOCK_FOLDED
? false
: type === Scalar.Scalar.BLOCK_LITERAL
? true
: !lineLengthOverLimit(value, lineWidth, indent.length);
if (!value)
return literal ? '|\n' : '>\n';
// determine chomping from whitespace at value end
let chomp;
let endStart;
for (endStart = value.length; endStart > 0; --endStart) {
const ch = value[endStart - 1];
if (ch !== '\n' && ch !== '\t' && ch !== ' ')
break;
}
let end = value.substring(endStart);
const endNlPos = end.indexOf('\n');
if (endNlPos === -1) {
chomp = '-'; // strip
}
else if (value === end || endNlPos !== end.length - 1) {
chomp = '+'; // keep
if (onChompKeep)
onChompKeep();
}
else {
chomp = ''; // clip
}
if (end) {
value = value.slice(0, -end.length);
if (end[end.length - 1] === '\n')
end = end.slice(0, -1);
end = end.replace(/\n+(?!\n|$)/g, `$&${indent}`);
}
// determine indent indicator from whitespace at value start
let startWithSpace = false;
let startEnd;
let startNlPos = -1;
for (startEnd = 0; startEnd < value.length; ++startEnd) {
const ch = value[startEnd];
if (ch === ' ')
startWithSpace = true;
else if (ch === '\n')
startNlPos = startEnd;
else
break;
}
let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
if (start) {
value = value.substring(start.length);
start = start.replace(/\n+/g, `$&${indent}`);
}
const indentSize = indent ? '2' : '1'; // root is at -1
let header = (literal ? '|' : '>') + (startWithSpace ? indentSize : '') + chomp;
if (comment) {
header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '));
if (onComment)
onComment();
}
if (literal) {
value = value.replace(/\n+/g, `$&${indent}`);
return `${header}\n${indent}${start}${value}${end}`;
}
value = value
.replace(/\n+/g, '\n$&')
.replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
// ^ more-ind. ^ empty ^ capture next empty lines only at end of indent
.replace(/\n+/g, `$&${indent}`);
const body = foldFlowLines.foldFlowLines(`${start}${value}${end}`, indent, foldFlowLines.FOLD_BLOCK, getFoldOptions(ctx));
return `${header}\n${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value } = item;
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if ((implicitKey && /[\n[\]{},]/.test(value)) ||
(inFlow && /[[\]{},]/.test(value))) {
return quotedString(value, ctx);
}
if (!value ||
/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
// not allowed:
// - empty string, '-' or '?'
// - start with an indicator character (except [?:-]) or /[?-] /
// - '\n ', ': ' or ' \n' anywhere
// - '#' not preceded by a non-space char
// - end with ' ' or ':'
return implicitKey || inFlow || !value.includes('\n')
? quotedString(value, ctx)
: blockString(item, ctx, onComment, onChompKeep);
}
if (!implicitKey &&
!inFlow &&
type !== Scalar.Scalar.PLAIN &&
value.includes('\n')) {
// Where allowed & type not set explicitly, prefer block style for multiline strings
return blockString(item, ctx, onComment, onChompKeep);
}
if (containsDocumentMarker(value)) {
if (indent === '') {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
}
else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx);
}
}
const str = value.replace(/\n+/g, `$&\n${indent}`);
// Verify that output will be parsed as a string, as e.g. plain numbers and
// booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
// and others in v1.1.
if (actualString) {
const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);
const { compat, tags } = ctx.doc.schema;
if (tags.some(test) || compat?.some(test))
return quotedString(value, ctx);
}
return implicitKey
? str
: foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;
const ss = typeof item.value === 'string'
? item
: Object.assign({}, item, { value: String(item.value) });
let { type } = item;
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
// force double quotes on control characters & unpaired surrogates
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
type = Scalar.Scalar.QUOTE_DOUBLE;
}
const _stringify = (_type) => {
switch (_type) {
case Scalar.Scalar.BLOCK_FOLDED:
case Scalar.Scalar.BLOCK_LITERAL:
return implicitKey || inFlow
? quotedString(ss.value, ctx) // blocks are not valid inside flow containers
: blockString(ss, ctx, onComment, onChompKeep);
case Scalar.Scalar.QUOTE_DOUBLE:
return doubleQuotedString(ss.value, ctx);
case Scalar.Scalar.QUOTE_SINGLE:
return singleQuotedString(ss.value, ctx);
case Scalar.Scalar.PLAIN:
return plainString(ss, ctx, onComment, onChompKeep);
default:
return null;
}
};
let res = _stringify(type);
if (res === null) {
const { defaultKeyType, defaultStringType } = ctx.options;
const t = (implicitKey && defaultKeyType) || defaultStringType;
res = _stringify(t);
if (res === null)
throw new Error(`Unsupported default string type ${t}`);
}
return res;
}
exports.stringifyString = stringifyString;
/***/ }),
/***/ 6796:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
var Node = __nccwpck_require__(1399);
const BREAK = Symbol('break visit');
const SKIP = Symbol('skip children');
const REMOVE = Symbol('remove node');
/**
* Apply a visitor to an AST node or document.
*
* Walks through the tree (depth-first) starting from `node`, calling a
* `visitor` function with three arguments:
* - `key`: For sequence values and map `Pair`, the node's index in the
* collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
* `null` for the root node.
* - `node`: The current node.
* - `path`: The ancestry of the current node.
*
* The return value of the visitor may be used to control the traversal:
* - `undefined` (default): Do nothing and continue
* - `visit.SKIP`: Do not visit the children of this node, continue with next
* sibling
* - `visit.BREAK`: Terminate traversal completely
* - `visit.REMOVE`: Remove the current node, then continue with the next one
* - `Node`: Replace the current node, then continue by visiting it
* - `number`: While iterating the items of a sequence or map, set the index
* of the next step. This is useful especially if the index of the current
* node has changed.
*
* If `visitor` is a single function, it will be called with all values
* encountered in the tree, including e.g. `null` values. Alternatively,
* separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
* `Alias` and `Scalar` node. To define the same visitor function for more than
* one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
* and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
* specific defined one will be used for each node.
*/
function visit(node, visitor) {
const visitor_ = initVisitor(visitor);
if (Node.isDocument(node)) {
const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
}
else
visit_(null, node, visitor_, Object.freeze([]));
}
// Without the `as symbol` casts, TS declares these in the `visit`
// namespace using `var`, but then complains about that because
// `unique symbol` must be `const`.
/** Terminate visit traversal completely */
visit.BREAK = BREAK;
/** Do not visit the children of the current node */
visit.SKIP = SKIP;
/** Remove the current node */
visit.REMOVE = REMOVE;
function visit_(key, node, visitor, path) {
const ctrl = callVisitor(key, node, visitor, path);
if (Node.isNode(ctrl) || Node.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visit_(key, ctrl, visitor, path);
}
if (typeof ctrl !== 'symbol') {
if (Node.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = visit_(i, node.items[i], visitor, path);
if (typeof ci === 'number')
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i, 1);
i -= 1;
}
}
}
else if (Node.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = visit_('key', node.key, visitor, path);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = visit_('value', node.value, visitor, path);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
/**
* Apply an async visitor to an AST node or document.
*
* Walks through the tree (depth-first) starting from `node`, calling a
* `visitor` function with three arguments:
* - `key`: For sequence values and map `Pair`, the node's index in the
* collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
* `null` for the root node.
* - `node`: The current node.
* - `path`: The ancestry of the current node.
*
* The return value of the visitor may be used to control the traversal:
* - `Promise`: Must resolve to one of the following values
* - `undefined` (default): Do nothing and continue
* - `visit.SKIP`: Do not visit the children of this node, continue with next
* sibling
* - `visit.BREAK`: Terminate traversal completely
* - `visit.REMOVE`: Remove the current node, then continue with the next one
* - `Node`: Replace the current node, then continue by visiting it
* - `number`: While iterating the items of a sequence or map, set the index
* of the next step. This is useful especially if the index of the current
* node has changed.
*
* If `visitor` is a single function, it will be called with all values
* encountered in the tree, including e.g. `null` values. Alternatively,
* separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
* `Alias` and `Scalar` node. To define the same visitor function for more than
* one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
* and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
* specific defined one will be used for each node.
*/
async function visitAsync(node, visitor) {
const visitor_ = initVisitor(visitor);
if (Node.isDocument(node)) {
const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
}
else
await visitAsync_(null, node, visitor_, Object.freeze([]));
}
// Without the `as symbol` casts, TS declares these in the `visit`
// namespace using `var`, but then complains about that because
// `unique symbol` must be `const`.
/** Terminate visit traversal completely */
visitAsync.BREAK = BREAK;
/** Do not visit the children of the current node */
visitAsync.SKIP = SKIP;
/** Remove the current node */
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key, node, visitor, path) {
const ctrl = await callVisitor(key, node, visitor, path);
if (Node.isNode(ctrl) || Node.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visitAsync_(key, ctrl, visitor, path);
}
if (typeof ctrl !== 'symbol') {
if (Node.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = await visitAsync_(i, node.items[i], visitor, path);
if (typeof ci === 'number')
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i, 1);
i -= 1;
}
}
}
else if (Node.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = await visitAsync_('key', node.key, visitor, path);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = await visitAsync_('value', node.value, visitor, path);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
function initVisitor(visitor) {
if (typeof visitor === 'object' &&
(visitor.Collection || visitor.Node || visitor.Value)) {
return Object.assign({
Alias: visitor.Node,
Map: visitor.Node,
Scalar: visitor.Node,
Seq: visitor.Node
}, visitor.Value && {
Map: visitor.Value,
Scalar: visitor.Value,
Seq: visitor.Value
}, visitor.Collection && {
Map: visitor.Collection,
Seq: visitor.Collection
}, visitor);
}
return visitor;
}
function callVisitor(key, node, visitor, path) {
if (typeof visitor === 'function')
return visitor(key, node, path);
if (Node.isMap(node))
return visitor.Map?.(key, node, path);
if (Node.isSeq(node))
return visitor.Seq?.(key, node, path);
if (Node.isPair(node))
return visitor.Pair?.(key, node, path);
if (Node.isScalar(node))
return visitor.Scalar?.(key, node, path);
if (Node.isAlias(node))
return visitor.Alias?.(key, node, path);
return undefined;
}
function replaceNode(key, path, node) {
const parent = path[path.length - 1];
if (Node.isCollection(parent)) {
parent.items[key] = node;
}
else if (Node.isPair(parent)) {
if (key === 'key')
parent.key = node;
else
parent.value = node;
}
else if (Node.isDocument(parent)) {
parent.contents = node;
}
else {
const pt = Node.isAlias(parent) ? 'alias' : 'scalar';
throw new Error(`Cannot replace node with ${pt} parent`);
}
}
exports.visit = visit;
exports.visitAsync = visitAsync;
/***/ }),
/***/ 277:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => {
"use strict";
// ESM COMPAT FLAG
__nccwpck_require__.r(__webpack_exports__);
// EXPORTS
__nccwpck_require__.d(__webpack_exports__, {
"generateGlobTasks": () => (/* binding */ generateGlobTasks),
"generateGlobTasksSync": () => (/* binding */ generateGlobTasksSync),
"globby": () => (/* binding */ globby),
"globbyStream": () => (/* binding */ globbyStream),
"globbySync": () => (/* binding */ globbySync),
"isDynamicPattern": () => (/* binding */ isDynamicPattern),
"isGitIgnored": () => (/* reexport */ isGitIgnored),
"isGitIgnoredSync": () => (/* reexport */ isGitIgnoredSync)
});
// EXTERNAL MODULE: external "node:fs"
var external_node_fs_ = __nccwpck_require__(7561);
// EXTERNAL MODULE: external "node:path"
var external_node_path_ = __nccwpck_require__(9411);
// EXTERNAL MODULE: ./node_modules/merge2/index.js
var merge2 = __nccwpck_require__(2578);
// EXTERNAL MODULE: ./node_modules/fast-glob/out/index.js
var out = __nccwpck_require__(3664);
// EXTERNAL MODULE: ./node_modules/dir-glob/index.js
var dir_glob = __nccwpck_require__(2738);
;// CONCATENATED MODULE: external "node:process"
const external_node_process_namespaceObject = require("node:process");
// EXTERNAL MODULE: ./node_modules/ignore/index.js
var ignore = __nccwpck_require__(4777);
;// CONCATENATED MODULE: ./node_modules/slash/index.js
function slash(path) {
const isExtendedLengthPath = /^\\\\\?\\/.test(path);
const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
if (isExtendedLengthPath || hasNonAscii) {
return path;
}
return path.replace(/\\/g, '/');
}
// EXTERNAL MODULE: external "node:url"
var external_node_url_ = __nccwpck_require__(1041);
;// CONCATENATED MODULE: external "node:stream"
const external_node_stream_namespaceObject = require("node:stream");
;// CONCATENATED MODULE: ./node_modules/globby/utilities.js
const toPath = urlOrPath => urlOrPath instanceof URL ? (0,external_node_url_.fileURLToPath)(urlOrPath) : urlOrPath;
class FilterStream extends external_node_stream_namespaceObject.Transform {
constructor(filter) {
super({
objectMode: true,
transform(data, encoding, callback) {
callback(undefined, filter(data) ? data : undefined);
},
});
}
}
const isNegativePattern = pattern => pattern[0] === '!';
;// CONCATENATED MODULE: ./node_modules/globby/ignore.js
const ignoreFilesGlobOptions = {
ignore: [
'**/node_modules',
'**/flow-typed',
'**/coverage',
'**/.git',
],
absolute: true,
dot: true,
};
const GITIGNORE_FILES_PATTERN = '**/.gitignore';
const applyBaseToPattern = (pattern, base) => isNegativePattern(pattern)
? '!' + external_node_path_.posix.join(base, pattern.slice(1))
: external_node_path_.posix.join(base, pattern);
const parseIgnoreFile = (file, cwd) => {
const base = slash(external_node_path_.relative(cwd, external_node_path_.dirname(file.filePath)));
return file.content
.split(/\r?\n/)
.filter(line => line && !line.startsWith('#'))
.map(pattern => applyBaseToPattern(pattern, base));
};
const toRelativePath = (fileOrDirectory, cwd) => {
cwd = slash(cwd);
if (external_node_path_.isAbsolute(fileOrDirectory)) {
if (slash(fileOrDirectory).startsWith(cwd)) {
return external_node_path_.relative(cwd, fileOrDirectory);
}
throw new Error(`Path ${fileOrDirectory} is not in cwd ${cwd}`);
}
return fileOrDirectory;
};
const getIsIgnoredPredicate = (files, cwd) => {
const patterns = files.flatMap(file => parseIgnoreFile(file, cwd));
const ignores = ignore().add(patterns);
return fileOrDirectory => {
fileOrDirectory = toPath(fileOrDirectory);
fileOrDirectory = toRelativePath(fileOrDirectory, cwd);
return fileOrDirectory ? ignores.ignores(slash(fileOrDirectory)) : false;
};
};
const normalizeOptions = (options = {}) => ({
cwd: toPath(options.cwd) || external_node_process_namespaceObject.cwd(),
});
const isIgnoredByIgnoreFiles = async (patterns, options) => {
const {cwd} = normalizeOptions(options);
const paths = await out(patterns, {cwd, ...ignoreFilesGlobOptions});
const files = await Promise.all(
paths.map(async filePath => ({
filePath,
content: await external_node_fs_.promises.readFile(filePath, 'utf8'),
})),
);
return getIsIgnoredPredicate(files, cwd);
};
const isIgnoredByIgnoreFilesSync = (patterns, options) => {
const {cwd} = normalizeOptions(options);
const paths = out.sync(patterns, {cwd, ...ignoreFilesGlobOptions});
const files = paths.map(filePath => ({
filePath,
content: external_node_fs_.readFileSync(filePath, 'utf8'),
}));
return getIsIgnoredPredicate(files, cwd);
};
const isGitIgnored = options => isIgnoredByIgnoreFiles(GITIGNORE_FILES_PATTERN, options);
const isGitIgnoredSync = options => isIgnoredByIgnoreFilesSync(GITIGNORE_FILES_PATTERN, options);
;// CONCATENATED MODULE: ./node_modules/globby/index.js
const assertPatternsInput = patterns => {
if (patterns.some(pattern => typeof pattern !== 'string')) {
throw new TypeError('Patterns must be a string or an array of strings');
}
};
const toPatternsArray = patterns => {
patterns = [...new Set([patterns].flat())];
assertPatternsInput(patterns);
return patterns;
};
const checkCwdOption = options => {
if (!options.cwd) {
return;
}
let stat;
try {
stat = external_node_fs_.statSync(options.cwd);
} catch {
return;
}
if (!stat.isDirectory()) {
throw new Error('The `cwd` option must be a path to a directory');
}
};
const globby_normalizeOptions = (options = {}) => {
options = {
ignore: [],
expandDirectories: true,
...options,
cwd: toPath(options.cwd),
};
checkCwdOption(options);
return options;
};
const normalizeArguments = fn => async (patterns, options) => fn(toPatternsArray(patterns), globby_normalizeOptions(options));
const normalizeArgumentsSync = fn => (patterns, options) => fn(toPatternsArray(patterns), globby_normalizeOptions(options));
const getIgnoreFilesPatterns = options => {
const {ignoreFiles, gitignore} = options;
const patterns = ignoreFiles ? toPatternsArray(ignoreFiles) : [];
if (gitignore) {
patterns.push(GITIGNORE_FILES_PATTERN);
}
return patterns;
};
const getFilter = async options => {
const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
return createFilterFunction(
ignoreFilesPatterns.length > 0 && await isIgnoredByIgnoreFiles(ignoreFilesPatterns, {cwd: options.cwd}),
);
};
const getFilterSync = options => {
const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
return createFilterFunction(
ignoreFilesPatterns.length > 0 && isIgnoredByIgnoreFilesSync(ignoreFilesPatterns, {cwd: options.cwd}),
);
};
const createFilterFunction = isIgnored => {
const seen = new Set();
return fastGlobResult => {
const path = fastGlobResult.path || fastGlobResult;
const pathKey = external_node_path_.normalize(path);
const seenOrIgnored = seen.has(pathKey) || (isIgnored && isIgnored(path));
seen.add(pathKey);
return !seenOrIgnored;
};
};
const unionFastGlobResults = (results, filter) => results.flat().filter(fastGlobResult => filter(fastGlobResult));
const unionFastGlobStreams = (streams, filter) => merge2(streams).pipe(new FilterStream(fastGlobResult => filter(fastGlobResult)));
const convertNegativePatterns = (patterns, options) => {
const tasks = [];
while (patterns.length > 0) {
const index = patterns.findIndex(pattern => isNegativePattern(pattern));
if (index === -1) {
tasks.push({patterns, options});
break;
}
const ignorePattern = patterns[index].slice(1);
for (const task of tasks) {
task.options.ignore.push(ignorePattern);
}
if (index !== 0) {
tasks.push({
patterns: patterns.slice(0, index),
options: {
...options,
ignore: [
...options.ignore,
ignorePattern,
],
},
});
}
patterns = patterns.slice(index + 1);
}
return tasks;
};
const getDirGlobOptions = (options, cwd) => ({
...(cwd ? {cwd} : {}),
...(Array.isArray(options) ? {files: options} : options),
});
const generateTasks = async (patterns, options) => {
const globTasks = convertNegativePatterns(patterns, options);
const {cwd, expandDirectories} = options;
if (!expandDirectories) {
return globTasks;
}
const patternExpandOptions = getDirGlobOptions(expandDirectories, cwd);
const ignoreExpandOptions = cwd ? {cwd} : undefined;
return Promise.all(
globTasks.map(async task => {
let {patterns, options} = task;
[
patterns,
options.ignore,
] = await Promise.all([
dir_glob(patterns, patternExpandOptions),
dir_glob(options.ignore, ignoreExpandOptions),
]);
return {patterns, options};
}),
);
};
const generateTasksSync = (patterns, options) => {
const globTasks = convertNegativePatterns(patterns, options);
const {cwd, expandDirectories} = options;
if (!expandDirectories) {
return globTasks;
}
const patternExpandOptions = getDirGlobOptions(expandDirectories, cwd);
const ignoreExpandOptions = cwd ? {cwd} : undefined;
return globTasks.map(task => {
let {patterns, options} = task;
patterns = dir_glob.sync(patterns, patternExpandOptions);
options.ignore = dir_glob.sync(options.ignore, ignoreExpandOptions);
return {patterns, options};
});
};
const globby = normalizeArguments(async (patterns, options) => {
const [
tasks,
filter,
] = await Promise.all([
generateTasks(patterns, options),
getFilter(options),
]);
const results = await Promise.all(tasks.map(task => out(task.patterns, task.options)));
return unionFastGlobResults(results, filter);
});
const globbySync = normalizeArgumentsSync((patterns, options) => {
const tasks = generateTasksSync(patterns, options);
const filter = getFilterSync(options);
const results = tasks.map(task => out.sync(task.patterns, task.options));
return unionFastGlobResults(results, filter);
});
const globbyStream = normalizeArgumentsSync((patterns, options) => {
const tasks = generateTasksSync(patterns, options);
const filter = getFilterSync(options);
const streams = tasks.map(task => out.stream(task.patterns, task.options));
return unionFastGlobStreams(streams, filter);
});
const isDynamicPattern = normalizeArgumentsSync(
(patterns, options) => patterns.some(pattern => out.isDynamicPattern(pattern, options)),
);
const generateGlobTasks = normalizeArguments(generateTasks);
const generateGlobTasksSync = normalizeArgumentsSync(generateTasksSync);
/***/ }),
/***/ 6177:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => {
"use strict";
__nccwpck_require__.r(__webpack_exports__);
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ stripJsonComments)
/* harmony export */ });
const singleComment = Symbol('singleComment');
const multiComment = Symbol('multiComment');
const stripWithoutWhitespace = () => '';
const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');
const isEscaped = (jsonString, quotePosition) => {
let index = quotePosition - 1;
let backslashCount = 0;
while (jsonString[index] === '\\') {
index -= 1;
backslashCount += 1;
}
return Boolean(backslashCount % 2);
};
function stripJsonComments(jsonString, {whitespace = true, trailingCommas = false} = {}) {
if (typeof jsonString !== 'string') {
throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
}
const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace;
let isInsideString = false;
let isInsideComment = false;
let offset = 0;
let buffer = '';
let result = '';
let commaIndex = -1;
for (let index = 0; index < jsonString.length; index++) {
const currentCharacter = jsonString[index];
const nextCharacter = jsonString[index + 1];
if (!isInsideComment && currentCharacter === '"') {
// Enter or exit string
const escaped = isEscaped(jsonString, index);
if (!escaped) {
isInsideString = !isInsideString;
}
}
if (isInsideString) {
continue;
}
if (!isInsideComment && currentCharacter + nextCharacter === '//') {
// Enter single-line comment
buffer += jsonString.slice(offset, index);
offset = index;
isInsideComment = singleComment;
index++;
} else if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
// Exit single-line comment via \r\n
index++;
isInsideComment = false;
buffer += strip(jsonString, offset, index);
offset = index;
continue;
} else if (isInsideComment === singleComment && currentCharacter === '\n') {
// Exit single-line comment via \n
isInsideComment = false;
buffer += strip(jsonString, offset, index);
offset = index;
} else if (!isInsideComment && currentCharacter + nextCharacter === '/*') {
// Enter multiline comment
buffer += jsonString.slice(offset, index);
offset = index;
isInsideComment = multiComment;
index++;
continue;
} else if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') {
// Exit multiline comment
index++;
isInsideComment = false;
buffer += strip(jsonString, offset, index + 1);
offset = index + 1;
continue;
} else if (trailingCommas && !isInsideComment) {
if (commaIndex !== -1) {
if (currentCharacter === '}' || currentCharacter === ']') {
// Strip trailing comma
buffer += jsonString.slice(offset, index);
result += strip(buffer, 0, 1) + buffer.slice(1);
buffer = '';
offset = index;
commaIndex = -1;
} else if (currentCharacter !== ' ' && currentCharacter !== '\t' && currentCharacter !== '\r' && currentCharacter !== '\n') {
// Hit non-whitespace following a comma; comma is not trailing
buffer += jsonString.slice(offset, index);
offset = index;
commaIndex = -1;
}
} else if (currentCharacter === ',') {
// Flush buffer prior to this point, and save new comma index
result += buffer + jsonString.slice(offset, index);
buffer = '';
offset = index;
commaIndex = index;
}
}
}
return result + buffer + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
}
/***/ }),
/***/ 9323:
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"Aacute":"Á","aacute":"á","Abreve":"Ă","abreve":"ă","ac":"∾","acd":"∿","acE":"∾̳","Acirc":"Â","acirc":"â","acute":"´","Acy":"А","acy":"а","AElig":"Æ","aelig":"æ","af":"","Afr":"𝔄","afr":"𝔞","Agrave":"À","agrave":"à","alefsym":"ℵ","aleph":"ℵ","Alpha":"Α","alpha":"α","Amacr":"Ā","amacr":"ā","amalg":"⨿","amp":"&","AMP":"&","andand":"⩕","And":"⩓","and":"∧","andd":"⩜","andslope":"⩘","andv":"⩚","ang":"∠","ange":"⦤","angle":"∠","angmsdaa":"⦨","angmsdab":"⦩","angmsdac":"⦪","angmsdad":"⦫","angmsdae":"⦬","angmsdaf":"⦭","angmsdag":"⦮","angmsdah":"⦯","angmsd":"∡","angrt":"∟","angrtvb":"⊾","angrtvbd":"⦝","angsph":"∢","angst":"Å","angzarr":"⍼","Aogon":"Ą","aogon":"ą","Aopf":"𝔸","aopf":"𝕒","apacir":"⩯","ap":"≈","apE":"⩰","ape":"≊","apid":"≋","apos":"\'","ApplyFunction":"","approx":"≈","approxeq":"≊","Aring":"Å","aring":"å","Ascr":"𝒜","ascr":"𝒶","Assign":"≔","ast":"*","asymp":"≈","asympeq":"≍","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","awconint":"∳","awint":"⨑","backcong":"≌","backepsilon":"϶","backprime":"","backsim":"∽","backsimeq":"⋍","Backslash":"","Barv":"⫧","barvee":"⊽","barwed":"⌅","Barwed":"⌆","barwedge":"⌅","bbrk":"⎵","bbrktbrk":"⎶","bcong":"≌","Bcy":"Б","bcy":"б","bdquo":"„","becaus":"∵","because":"∵","Because":"∵","bemptyv":"⦰","bepsi":"϶","bernou":"","Bernoullis":"","Beta":"Β","beta":"β","beth":"ℶ","between":"≬","Bfr":"𝔅","bfr":"𝔟","bigcap":"⋂","bigcirc":"◯","bigcup":"","bigodot":"⨀","bigoplus":"⨁","bigotimes":"⨂","bigsqcup":"⨆","bigstar":"★","bigtriangledown":"▽","bigtriangleup":"△","biguplus":"⨄","bigvee":"","bigwedge":"⋀","bkarow":"⤍","blacklozenge":"⧫","blacksquare":"▪","blacktriangle":"▴","blacktriangledown":"▾","blacktriangleleft":"◂","blacktriangleright":"▸","blank":"␣","blk12":"▒","blk14":"░","blk34":"▓","block":"█","bne":"=⃥","bnequiv":"≡⃥","bNot":"⫭","bnot":"⌐","Bopf":"𝔹","bopf":"𝕓","bot":"⊥","bottom":"⊥","bowtie":"⋈","boxbox":"⧉","boxdl":"┐","boxdL":"╕","boxDl":"╖","boxDL":"╗","boxdr":"┌","boxdR":"╒","boxDr":"╓","boxDR":"╔","boxh":"─","boxH":"═","boxhd":"┬","boxHd":"╤","boxhD":"╥","boxHD":"╦","boxhu":"┴","boxHu":"╧","boxhU":"╨","boxHU":"╩","boxminus":"⊟","boxplus":"⊞","boxtimes":"⊠","boxul":"┘","boxuL":"╛","boxUl":"╜","boxUL":"╝","boxur":"└","boxuR":"╘","boxUr":"╙","boxUR":"╚","boxv":"│","boxV":"║","boxvh":"┼","boxvH":"╪","boxVh":"╫","boxVH":"╬","boxvl":"┤","boxvL":"╡","boxVl":"╢","boxVL":"╣","boxvr":"├","boxvR":"╞","boxVr":"╟","boxVR":"╠","bprime":"","breve":"˘","Breve":"˘","brvbar":"¦","bscr":"𝒷","Bscr":"","bsemi":"⁏","bsim":"∽","bsime":"⋍","bsolb":"⧅","bsol":"\\\\","bsolhsub":"⟈","bull":"•","bullet":"•","bump":"≎","bumpE":"⪮","bumpe":"≏","Bumpeq":"≎","bumpeq":"≏","Cacute":"Ć","cacute":"ć","capand":"⩄","capbrcup":"⩉","capcap":"⩋","cap":"∩","Cap":"⋒","capcup":"⩇","capdot":"⩀","CapitalDifferentialD":"","caps":"∩︀","caret":"","caron":"ˇ","Cayleys":"","ccaps":"⩍","Ccaron":"Č","ccaron":"č","Ccedil":"Ç","ccedil":"ç","Ccirc":"Ĉ","ccirc":"ĉ","Cconint":"∰","ccups":"⩌","ccupssm":"⩐","Cdot":"Ċ","cdot":"ċ","cedil":"¸","Cedilla":"¸","cemptyv":"⦲","cent":"¢","centerdot":"·","CenterDot":"·","cfr":"𝔠","Cfr":"","CHcy":"Ч","chcy":"ч","check":"✓","checkmark":"✓","Chi":"Χ","chi":"χ","circ":"ˆ","circeq":"≗","circlearrowleft":"↺","circlearrowright":"↻","circledast":"⊛","circledcirc":"⊚","circleddash":"⊝","CircleDot":"⊙","circledR":"®","circledS":"Ⓢ","CircleMinus":"⊖","CirclePlus":"⊕","CircleTimes":"⊗","cir":"○","cirE":"⧃","cire":"≗","cirfnint":"⨐","cirmid":"⫯","cirscir":"⧂","ClockwiseContourIntegral":"∲","CloseCurlyDoubleQuote":"”","CloseCurlyQuote":"","clubs":"♣","clubsuit":"♣","colon":":","Colon":"∷","Colone":"⩴","colone":"≔","coloneq":"≔","comma":",","commat":"@","comp":"∁","compfn":"∘","complement":"∁","complexes":"","cong":"≅","congdot":"⩭","Congruent":"≡","conint":"∮","Conint":"∯","ContourIntegral":"∮","copf":"𝕔","Copf":"","coprod":"∐","Coproduct":"∐","copy":"©","COPY":"©","copysr":"℗","CounterClockwiseContourIntegral":"∳","crarr":"↵","cross":"✗","Cross":"","Cscr":"𝒞","cscr":"𝒸","csub":"⫏","csube":"⫑","csup":"⫐","csupe":"⫒","ctdot":"⋯","cudarrl":"⤸","cudarrr":"⤵","cuepr":"⋞","cuesc":"⋟","cularr":"↶","cularrp":"⤽","cupbrcap":"⩈","cupcap":"⩆","CupCap":"≍","cup":"","Cup":"⋓","cupcup":"⩊","cupdot":"⊍","cupor":"⩅","cups":"","curarr":"↷","curarrm":"⤼","curlyeqprec":"⋞","curlyeqsucc":"⋟","curlyvee":"⋎","curlywedge":"⋏","curren":"¤","curvearrowleft":"↶","curvearrowright":"↷","cuvee":"⋎","cuwed":"⋏","cwconint":"∲","cwint":"∱","cylcty":"⌭","dagger":"†","Dagger":"‡","daleth":"ℸ","darr":"↓","Darr":"↡","dArr":"⇓","dash":"","Dashv":"⫤","dashv":"⊣","dbkarow":"⤏","dblac":"˝","Dcaron":"Ď","dcaron":"ď","Dcy":"Д","dcy":"д","ddagger":"‡","ddarr":"⇊","DD":"","dd":"","DDotrahd":"⤑","ddotseq":"⩷","deg":"°","Del":"∇","Delta":"Δ","delta":"δ","demptyv":"⦱","dfisht":"⥿","Dfr":"𝔇","dfr":"𝔡","dHar":"⥥","dharl":"⇃","dharr":"⇂","DiacriticalAcute":"´","DiacriticalDot":"˙","DiacriticalDoubleAcute":"˝","DiacriticalGrave":"`","DiacriticalTilde":"˜","diam":"⋄","diamond":"⋄","Diamond":"⋄","diamondsuit":"♦","diams":"♦","die":"¨","DifferentialD":"","digamma":"ϝ","disin":"⋲","div":"÷","divide":"÷","divideontimes":"⋇","divonx":"⋇","DJcy":"Ђ","djcy":"ђ","dlcorn":"⌞","dlcrop":"⌍","dollar":"$","Dopf":"𝔻","dopf":"𝕕","Dot":"¨","dot":"˙","DotDot":"⃜","doteq":"≐","doteqdot":"≑","DotEqual":"≐","dotminus":"∸","dotplus":"∔","dotsquare":"⊡","doublebarwedge":"⌆","DoubleContourIntegral":"∯","DoubleDot":"¨","DoubleDownArrow":"⇓","DoubleLeftArrow":"⇐","DoubleLeftRightArrow":"⇔","DoubleLeftTee":"⫤","DoubleLongLeftArrow":"⟸","DoubleLongLeftRightArrow":"⟺","DoubleLongRightArrow":"⟹","DoubleRightArrow":"⇒","DoubleRightTee":"⊨","DoubleUpArrow":"⇑","DoubleUpDownArrow":"⇕","DoubleVerticalBar":"∥","DownArrowBar":"⤓","downarrow":"↓","DownArrow":"↓","Downarrow":"⇓","DownArrowUpArrow":"⇵","DownBreve":"̑","downdownarrows":"⇊","downharpoonleft":"⇃","downharpoonright":"⇂","DownLeftRightVector":"⥐","DownLeftTeeVector":"⥞","DownLeftVectorBar":"⥖","DownLeftVector":"↽","DownRightTeeVector":"⥟","DownRightVectorBar":"⥗","DownRightVector":"⇁","DownTeeArrow":"↧","DownTee":"","drbkarow":"⤐","drcorn":"⌟","drcrop":"⌌","Dscr":"𝒟","dscr":"𝒹","DScy":"Ѕ","dscy":"ѕ","dsol":"⧶","Dstrok":"Đ","dstrok":"đ","dtdot":"⋱","dtri":"▿","dtrif":"▾","duarr":"⇵","duhar":"⥯","dwangle":"⦦","DZcy":"Џ","dzcy":"џ","dzigrarr":"⟿","Eacute":"É","eacute":"é","easter":"⩮","Ecaron":"Ě","ecaron":"ě","Ecirc":"Ê","ecirc":"ê","ecir":"≖","ecolon":"≕","Ecy":"Э","ecy":"э","eDDot":"⩷","Edot":"Ė","edot":"ė","eDot":"≑","ee":"","efDot":"≒","Efr":"𝔈","efr":"𝔢","eg":"⪚","Egrave":"È","egrave":"è","egs":"⪖","egsdot":"⪘","el":"⪙","Element":"∈","elinters":"⏧","ell":"","els":"⪕","elsdot":"⪗","Emacr":"Ē","emacr":"ē","empty":"∅","emptyset":"∅","EmptySmallSquare":"◻","emptyv":"∅","EmptyVerySmallSquare":"▫","emsp13":"","emsp14":"","emsp":"","ENG":"Ŋ","eng":"ŋ","ensp":"","Eogon":"Ę","eogon":"ę","Eopf":"𝔼","eopf":"𝕖","epar":"⋕","eparsl":"⧣","eplus":"⩱","epsi":"ε","Epsilon":"Ε","epsilon":"ε","epsiv":"ϵ","eqcirc":"≖","eqcolon":"≕","eqsim":"≂","eqslantgtr":"⪖","eqslantless":"⪕","Equal":"⩵","equals":"=","EqualTilde":"≂","equest":"≟","Equilibrium":"⇌","equiv":"≡","equivDD":"⩸","eqvparsl":"⧥","erarr":"⥱","erDot":"≓","escr":"","Escr":"","esdot":"≐","Esim":"⩳","esim":"≂","Eta":"Η","eta":"η","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","euro":"€","excl":"!","exist":"∃","Exists":"∃","expectation":"","exponentiale":"","ExponentialE":"","fallingdotseq":"≒","Fcy":"Ф","fcy":"ф","female":"♀","ffilig":"ffi","fflig":"ff","ffllig":"ffl","Ffr":"𝔉","ffr":"𝔣","filig":"fi","FilledSmallSquare":"◼","FilledVerySmallSquare":"▪","fjlig":"fj","flat":"♭","fllig":"fl","fltns":"▱","fnof":"ƒ","Fopf":"𝔽","fopf":"𝕗","forall":"∀","ForAll":"∀","fork":"⋔","forkv":"⫙","Fouriertrf":"","fpartint":"⨍","frac12":"½","frac13":"⅓","frac14":"¼","frac15":"⅕","frac16":"⅙","frac18":"⅛","frac23":"⅔","frac25":"⅖","frac34":"¾","frac35":"⅗","frac38":"⅜","frac45":"⅘","frac56":"⅚","frac58":"⅝","frac78":"⅞","frasl":"","frown":"⌢","fscr":"𝒻","Fscr":"","gacute":"ǵ","Gamma":"Γ","gamma":"γ","Gammad":"Ϝ","gammad":"ϝ","gap":"⪆","Gbreve":"Ğ","gbreve":"ğ","Gcedil":"Ģ","Gcirc":"Ĝ","gcirc":"ĝ","Gcy":"Г","gcy":"г","Gdot":"Ġ","gdot":"ġ","ge":"≥","gE":"≧","gEl":"⪌","gel":"⋛","geq":"≥","geqq":"≧","geqslant":"⩾","gescc":"⪩","ges":"⩾","gesdot":"⪀","gesdoto":"⪂","gesdotol":"⪄","gesl":"⋛︀","gesles":"⪔","Gfr":"𝔊","gfr":"𝔤","gg":"≫","Gg":"⋙","ggg":"⋙","gimel":"ℷ","GJcy":"Ѓ","gjcy":"ѓ","gla":"⪥","gl":"≷","glE":"⪒","glj":"⪤","gnap":"⪊","gnapprox":"⪊","gne":"⪈","gnE":"≩","gneq":"⪈","gneqq":"≩","gnsim":"⋧","Gopf":"𝔾","gopf":"𝕘","grave":"`","GreaterEqual":"≥","GreaterEqualLess":"⋛","GreaterFullEqual":"≧","GreaterGreater":"⪢","GreaterLess":"≷","GreaterSlantEqual":"⩾","GreaterTilde":"≳","Gscr":"𝒢","gscr":"","gsim":"≳","gsime":"⪎","gsiml":"⪐","gtcc":"⪧","gtcir":"⩺","gt":">","GT":">","Gt":"≫","gtdot":"⋗","gtlPar":"⦕","gtquest":"⩼","gtrapprox":"⪆","gtrarr":"⥸","gtrdot":"⋗","gtreqless":"⋛","gtreqqless":"⪌","gtrless":"≷","gtrsim":"≳","gvertneqq":"≩︀","gvnE":"≩︀","Hacek":"ˇ","hairsp":"","half":"½","hamilt":"","HARDcy":"Ъ","hardcy":"ъ","harrcir":"⥈","harr":"↔","hArr":"⇔","harrw":"↭","Hat":"^","hbar":"ℏ","Hcirc":"Ĥ","hcirc":"ĥ","hearts":"♥","heartsuit":"♥","hellip":"…","hercon":"⊹","hfr":"𝔥","Hfr":"","HilbertSpace":"","hksearow":"⤥","hkswarow":"⤦","hoarr":"⇿","homtht":"∻","hookleftarrow":"↩","hookrightarrow":"↪","hopf":"𝕙","Hopf":"","horbar":"―","HorizontalLine":"─","hscr":"𝒽","Hscr":"","hslash":"ℏ","Hstrok":"Ħ","hstrok":"ħ","HumpDownHump":"≎","HumpEqual":"≏","hybull":"","hyphen":"","Iacute":"Í","iacute":"í","ic":"","Icirc":"Î","icirc":"î","Icy":"И","icy":"и","Idot":"İ","IEcy":"Е","iecy":"е","iexcl":"¡","iff":"⇔","ifr":"𝔦","Ifr":"","Igrave":"Ì","igrave":"ì","ii":"","iiiint":"⨌","iiint":"∭","iinfin":"⧜","iiota":"℩","IJlig":"IJ","ijlig":"ij","Imacr":"Ī","imacr":"ī","image":"","ImaginaryI":"","imagline":"","imagpart":"","imath":"ı","Im":"","imof":"⊷","imped":"Ƶ","Implies":"⇒","incare":"℅","in":"∈","infin":"∞","infintie":"⧝","inodot":"ı","intcal":"⊺","int":"∫","Int":"∬","integers":"","Integral":"∫","intercal":"⊺","Intersection":"⋂","intlarhk":"⨗","intprod":"⨼","InvisibleComma":"","InvisibleTimes":"","IOcy":"Ё","iocy":"ё","Iogon":"Į","iogon":"į","Iopf":"𝕀","iopf":"𝕚","Iota":"Ι","iota":"ι","iprod":"⨼","iquest":"¿","iscr":"𝒾","Iscr":"","isin":"∈","isindot":"⋵","isinE":"⋹","isins":"⋴","isinsv":"⋳","isinv":"∈","it":"","Itilde":"Ĩ","itilde":"ĩ","Iukcy":"І","iukcy":"і","Iuml":"Ï","iuml":"ï","Jcirc":"Ĵ","jcirc":"ĵ","Jcy":"Й","jcy":"й","Jfr":"𝔍","jfr":"𝔧","jmath":"ȷ","Jopf":"𝕁","jopf":"𝕛","Jscr":"𝒥","jscr":"𝒿","Jsercy":"Ј","jsercy":"ј","Jukcy":"Є","jukcy":"є","Kappa":"Κ","kappa":"κ","kappav":"ϰ","Kcedil":"Ķ","kcedil":"ķ","Kcy":"К","kcy":"к","Kfr":"𝔎","kfr":"𝔨","kgreen":"ĸ","KHcy":"Х","khcy":"х","KJcy":"Ќ","kjcy":"ќ","Kopf":"𝕂","kopf":"𝕜","Kscr":"𝒦","kscr":"𝓀","lAarr":"⇚","Lacute":"Ĺ","lacute":"ĺ","laemptyv":"⦴","lagran":"","Lambda":"Λ","lambda":"λ","lang":"⟨","Lang":"⟪","langd":"⦑","langle":"⟨","lap":"⪅","Laplacetrf":"","laquo":"«","larrb":"⇤","larrbfs":"⤟","larr":"←","Larr":"↞","lArr":"⇐","larrfs":"⤝","larrhk":"↩","larrlp":"↫","larrpl":"⤹","larrsim":"⥳","larrtl":"↢","latail":"⤙","lAtail":"⤛","lat":"⪫","late":"⪭","lates":"⪭︀","lbarr":"⤌","lBarr":"⤎","lbbrk":"","lbrace":"{","lbrack":"[","lbrke":"⦋","lbrksld":"⦏","lbrkslu":"⦍","Lcaron":"Ľ","lcaron":"ľ","Lcedil":"Ļ","lcedil":"ļ","lceil":"⌈","lcub":"{","Lcy":"Л","lcy":"л","ldca":"⤶","ldquo":"“","ldquor":"„","ldrdhar":"⥧","ldrushar":"⥋","ldsh":"↲","le":"≤","lE":"≦","LeftAngleBracket":"⟨","LeftArrowBar":"⇤","leftarrow":"←","LeftArrow":"←","Leftarrow":"⇐","LeftArrowRightArrow":"⇆","leftarrowtail":"↢","LeftCeiling":"⌈","LeftDoubleBracket":"⟦","LeftDownTeeVector":"⥡","LeftDownVectorBar":"⥙","LeftDownVector":"⇃","LeftFloor":"⌊","leftharpoondown":"↽","leftharpoonup":"↼","leftleftarrows":"⇇","leftrightarrow":"↔","LeftRightArrow":"↔","Leftrightarrow":"⇔","leftrightarrows":"⇆","leftrightharpoons":"⇋","leftrightsquigarrow":"↭","LeftRightVector":"⥎","LeftTeeArrow":"↤","LeftTee":"⊣","LeftTeeVector":"⥚","leftthreetimes":"⋋","LeftTriangleBar":"⧏","LeftTriangle":"⊲","LeftTriangleEqual":"⊴","LeftUpDownVector":"⥑","LeftUpTeeVector":"⥠","LeftUpVectorBar":"⥘","LeftUpVector":"↿","LeftVectorBar":"⥒","LeftVector":"↼","lEg":"⪋","leg":"⋚","leq":"≤","leqq":"≦","leqslant":"⩽","lescc":"⪨","les":"⩽","lesdot":"⩿","lesdoto":"⪁","lesdotor":"⪃","lesg":"⋚︀","lesges":"⪓","lessapprox":"⪅","lessdot":"⋖","lesseqgtr":"⋚","lesseqqgtr":"⪋","LessEqualGreater":"⋚","LessFullEqual":"≦","LessGreater":"≶","lessgtr":"≶","LessLess":"⪡","lesssim":"≲","LessSlantEqual":"⩽","LessTilde":"≲","lfisht":"⥼","lfloor":"⌊","Lfr":"𝔏","lfr":"𝔩","lg":"≶","lgE":"⪑","lHar":"⥢","lhard":"↽","lharu":"↼","lharul":"⥪","lhblk":"▄","LJcy":"Љ","ljcy":"љ","llarr":"⇇","ll":"≪","Ll":"⋘","llcorner":"⌞","Lleftarrow":"⇚","llhard":"⥫","lltri":"◺","Lmidot":"Ŀ","lmidot":"ŀ","lmoustache":"⎰","lmoust":"⎰","lnap":"⪉","lnapprox":"⪉","lne":"⪇","lnE":"≨","lneq":"⪇","lneqq":"≨","lnsim":"⋦","loang":"⟬","loarr":"⇽","lobrk":"⟦","longleftarrow":"⟵","LongLeftArrow":"⟵","Longleftarrow":"⟸","longleftrightarrow":"⟷","LongLeftRightArrow":"⟷","Longleftrightarrow":"⟺","longmapsto":"⟼","longrightarrow":"⟶","LongRightArrow":"⟶","Longrightarrow":"⟹","looparrowleft":"↫","looparrowright":"↬","lopar":"⦅","Lopf":"𝕃","lopf":"𝕝","loplus":"⨭","lotimes":"⨴","lowast":"","lowbar":"_","LowerLeftArrow":"↙","LowerRightArrow":"↘","loz":"◊","lozenge":"◊","lozf":"⧫","lpar":"(","lparlt":"⦓","lrarr":"⇆","lrcorner":"⌟","lrhar":"⇋","lrhard":"⥭","lrm":"","lrtri":"⊿","lsaquo":"","lscr":"𝓁","Lscr":"","lsh":"↰","Lsh":"↰","lsim":"≲","lsime":"⪍","lsimg":"⪏","lsqb":"[","lsquo":"","lsquor":"","Lstrok":"Ł","lstrok":"ł","ltcc":"⪦","ltcir":"⩹","lt":"<","LT":"<","Lt":"≪","ltdot":"⋖","lthree":"⋋","ltimes":"⋉","ltlarr":"⥶","ltquest":"⩻","ltri":"◃","ltrie":"⊴","ltrif":"◂","ltrPar":"⦖","lurdshar":"⥊","luruhar":"⥦","lvertneqq":"≨︀","lvnE":"≨︀","macr":"¯","male":"♂","malt":"✠","maltese":"✠","Map":"⤅","map":"↦","mapsto":"↦","mapstodown":"↧","mapstoleft":"↤","mapstoup":"↥","marker":"▮","mcomma":"⨩","Mcy":"М","mcy":"м","mdash":"—","mDDot":"∺","measuredangle":"∡","MediumSpace":"","Mellintrf":"","Mfr":"𝔐","mfr":"𝔪","mho":"℧","micro":"µ","midast":"*","midcir":"⫰","mid":"","middot":"·","minusb":"⊟","minus":"","minusd":"∸","minusdu":"⨪","MinusPlus":"∓","mlcp":"⫛","mldr":"…","mnplus":"∓","models":"⊧","Mopf":"𝕄","mopf":"𝕞","mp":"∓","mscr":"𝓂","Mscr":"","mstpos":"∾","Mu":"Μ","mu":"μ","multimap":"⊸","mumap":"⊸","nabla":"∇","Nacute":"Ń","nacute":"ń","nang":"∠⃒","nap":"≉","napE":"⩰̸","napid":"≋̸","napos":"ʼn","napprox":"≉","natural":"♮","naturals":"","natur":"♮","nbsp":" ","nbump":"≎̸","nbumpe":"≏̸","ncap":"⩃","Ncaron":"Ň","ncaron":"ň","Ncedil":"Ņ","ncedil":"ņ","ncong":"≇","ncongdot":"⩭̸","ncup":"⩂","Ncy":"Н","ncy":"н","ndash":"","nearhk":"⤤","nearr":"↗","neArr":"⇗","nearrow":"↗","ne":"≠","nedot":"≐̸","NegativeMediumSpace":"","NegativeThickSpace":"","NegativeThinSpace":"","NegativeVeryThinSpace":"","nequiv":"≢","nesear":"⤨","nesim":"≂̸","NestedGreaterGreater":"≫","NestedLessLess":"≪","NewLine":"\\n","nexist":"∄","nexists":"∄","Nfr":"𝔑","nfr":"𝔫","ngE":"≧̸","nge":"≱","ngeq":"≱","ngeqq":"≧̸","ngeqslant":"⩾̸","nges":"⩾̸","nGg":"⋙̸","ngsim":"≵","nGt":"≫⃒","ngt":"≯","ngtr":"≯","nGtv":"≫̸","nharr":"↮","nhArr":"⇎","nhpar":"⫲","ni":"∋","nis":"⋼","nisd":"⋺","niv":"∋","NJcy":"Њ","njcy":"њ","nlarr":"↚","nlArr":"⇍","nldr":"‥","nlE":"≦̸","nle":"≰","nleftarrow":"↚","nLeftarrow":"⇍","nleftrightarrow":"↮","nLeftrightarrow":"⇎","nleq":"≰","nleqq":"≦̸","nleqslant":"⩽̸","nles":"⩽̸","nless":"≮","nLl":"⋘̸","nlsim":"≴","nLt":"≪⃒","nlt":"≮","nltri":"⋪","nltrie":"⋬","nLtv":"≪̸","nmid":"∤","NoBreak":"","NonBreakingSpace":" ","nopf":"𝕟","Nopf":"","Not":"⫬","not":"¬","NotCongruent":"≢","NotCupCap":"≭","NotDoubleVerticalBar":"∦","NotElement":"∉","NotEqual":"≠","NotEqualTilde":"≂̸","NotExists":"∄","NotGreater":"≯","NotGreaterEqual":"≱","NotGreaterFullEqual":"≧̸","NotGreaterGreater":"≫̸","NotGreaterLess":"≹","NotGreaterSlantEqual":"⩾̸","NotGreaterTilde":"≵","NotHumpDownHump":"≎̸","NotHumpEqual":"≏̸","notin":"∉","notindot":"⋵̸","notinE":"⋹̸","notinva":"∉","notinvb":"⋷","notinvc":"⋶","NotLeftTriangleBar":"⧏̸","NotLeftTriangle":"⋪","NotLeftTriangleEqual":"⋬","NotLess":"≮","NotLessEqual":"≰","NotLessGreater":"≸","NotLessLess":"≪̸","NotLessSlantEqual":"⩽̸","NotLessTilde":"≴","NotNestedGreaterGreater":"⪢̸","NotNestedLessLess":"⪡̸","notni":"∌","notniva":"∌","notnivb":"⋾","notnivc":"⋽","NotPrecedes":"⊀","NotPrecedesEqual":"⪯̸","NotPrecedesSlantEqual":"⋠","NotReverseElement":"∌","NotRightTriangleBar":"⧐̸","NotRightTriangle":"⋫","NotRightTriangleEqual":"⋭","NotSquareSubset":"⊏̸","NotSquareSubsetEqual":"⋢","NotSquareSuperset":"⊐̸","NotSquareSupersetEqual":"⋣","NotSubset":"⊂⃒","NotSubsetEqual":"⊈","NotSucceeds":"⊁","NotSucceedsEqual":"⪰̸","NotSucceedsSlantEqual":"⋡","NotSucceedsTilde":"≿̸","NotSuperset":"⊃⃒","NotSupersetEqual":"⊉","NotTilde":"≁","NotTildeEqual":"≄","NotTildeFullEqual":"≇","NotTildeTilde":"≉","NotVerticalBar":"∤","nparallel":"∦","npar":"∦","nparsl":"⫽⃥","npart":"∂̸","npolint":"⨔","npr":"⊀","nprcue":"⋠","nprec":"⊀","npreceq":"⪯̸","npre":"⪯̸","nrarrc":"⤳̸","nrarr":"↛","nrArr":"⇏","nrarrw":"↝̸","nrightarrow":"↛","nRightarrow":"⇏","nrtri":"⋫","nrtrie":"⋭","nsc":"⊁","nsccue":"⋡","nsce":"⪰̸","Nscr":"𝒩","nscr":"𝓃","nshortmid":"∤","nshortparallel":"∦","nsim":"≁","nsime":"≄","nsimeq":"≄","nsmid":"∤","nspar":"∦","nsqsube":"⋢","nsqsupe":"⋣","nsub":"⊄","nsubE":"⫅̸","nsube":"⊈","nsubset":"⊂⃒","nsubseteq":"⊈","nsubseteqq":"⫅̸","nsucc":"⊁","nsucceq":"⪰̸","nsup":"⊅","nsupE":"⫆̸","nsupe":"⊉","nsupset":"⊃⃒","nsupseteq":"⊉","nsupseteqq":"⫆̸","ntgl":"≹","Ntilde":"Ñ","ntilde":"ñ","ntlg":"≸","ntriangleleft":"⋪","ntrianglelefteq":"⋬","ntriangleright":"⋫","ntrianglerighteq":"⋭","Nu":"Ν","nu":"ν","num":"#","numero":"№","numsp":"","nvap":"≍⃒","nvdash":"⊬","nvDash":"⊭","nVdash":"⊮","nVDash":"⊯","nvge":"≥⃒","nvgt":">⃒","nvHarr":"⤄","nvinfin":"⧞","nvlArr":"⤂","nvle":"≤⃒","nvlt":"<⃒","nvltrie":"⊴⃒","nvrArr":"⤃","nvrtrie":"⊵⃒","nvsim":"∼⃒","nwarhk":"⤣","nwarr":"↖","nwArr":"⇖","nwarrow":"↖","nwnear":"⤧","Oacute":"Ó","oacute":"ó","oast":"⊛","Ocirc":"Ô","ocirc":"ô","ocir":"⊚","Ocy":"О","ocy":"о","odash":"⊝","Odblac":"Ő","odblac":"ő","odiv":"⨸","odot":"⊙","odsold":"⦼","OElig":"Œ","oelig":"œ","ofcir":"⦿","Ofr":"𝔒","ofr":"𝔬","ogon":"˛","Ograve":"Ò","ograve":"ò","ogt":"⧁","ohbar":"⦵","ohm":"Ω","oint":"∮","olarr":"↺","olcir":"⦾","olcross":"⦻","oline":"‾","olt":"⧀","Omacr":"Ō","omacr":"ō","Omega":"Ω","omega":"ω","Omicron":"Ο","omicron":"ο","omid":"⦶","ominus":"⊖","Oopf":"𝕆","oopf":"𝕠","opar":"⦷","OpenCurlyDoubleQuote":"“","OpenCurlyQuote":"","operp":"⦹","oplus":"⊕","orarr":"↻","Or":"⩔","or":"","ord":"⩝","order":"","orderof":"","ordf":"ª","ordm":"º","origof":"⊶","oror":"⩖","orslope":"⩗","orv":"⩛","oS":"Ⓢ","Oscr":"𝒪","oscr":"","Oslash":"Ø","oslash":"ø","osol":"⊘","Otilde":"Õ","otilde":"õ","otimesas":"⨶","Otimes":"⨷","otimes":"⊗","Ouml":"Ö","ouml":"ö","ovbar":"⌽","OverBar":"‾","OverBrace":"⏞","OverBracket":"⎴","OverParenthesis":"⏜","para":"¶","parallel":"∥","par":"∥","parsim":"⫳","parsl":"⫽","part":"∂","PartialD":"∂","Pcy":"П","pcy":"п","percnt":"%","period":".","permil":"‰","perp":"⊥","pertenk":"‱","Pfr":"𝔓","pfr":"𝔭","Phi":"Φ","phi":"φ","phiv":"ϕ","phmmat":"","phone":"☎","Pi":"Π","pi":"π","pitchfork":"⋔","piv":"ϖ","planck":"ℏ","planckh":"","plankv":"ℏ","plusacir":"⨣","plusb":"⊞","pluscir":"⨢","plus":"+","plusdo":"∔","plusdu":"⨥","pluse":"⩲","PlusMinus":"±","plusmn":"±","plussim":"⨦","plustwo":"⨧","pm":"±","Poincareplane":"","pointint":"⨕","popf":"𝕡","Popf":"","pound":"£","prap":"⪷","Pr":"⪻","pr":"≺","prcue":"≼","precapprox":"⪷","prec":"≺","preccurlyeq":"≼","Precedes":"≺","PrecedesEqual":"⪯","PrecedesSlantEqual":"≼","PrecedesTilde":"≾","preceq":"⪯","precnapprox":"⪹","precneqq":"⪵","precnsim":"⋨","pre":"⪯","prE":"⪳","precsim":"≾","prime":"","Prime":"″","primes":"","prnap":"⪹","prnE":"⪵","prnsim":"⋨","prod":"∏","Product":"∏","profalar":"⌮","profline":"⌒","profsurf":"⌓","prop":"∝","Proportional":"∝","Proportion":"∷","propto":"∝","prsim":"≾","prurel":"⊰","Pscr":"𝒫","pscr":"𝓅","Psi":"Ψ","psi":"ψ","puncsp":"","Qfr":"𝔔","qfr":"𝔮","qint":"⨌","qopf":"𝕢","Qopf":"","qprime":"⁗","Qscr":"𝒬","qscr":"𝓆","quaternions":"","quatint":"⨖","quest":"?","questeq":"≟","quot":"\\"","QUOT":"\\"","rAarr":"⇛","race":"∽̱","Racute":"Ŕ","racute":"ŕ","radic":"√","raemptyv":"⦳","rang":"⟩","Rang":"⟫","rangd":"⦒","range":"⦥","rangle":"⟩","raquo":"»","rarrap":"⥵","rarrb":"⇥","rarrbfs":"⤠","rarrc":"⤳","rarr":"→","Rarr":"↠","rArr":"⇒","rarrfs":"⤞","rarrhk":"↪","rarrlp":"↬","rarrpl":"⥅","rarrsim":"⥴","Rarrtl":"⤖","rarrtl":"↣","rarrw":"↝","ratail":"⤚","rAtail":"⤜","ratio":"","rationals":"","rbarr":"⤍","rBarr":"⤏","RBarr":"⤐","rbbrk":"","rbrace":"}","rbrack":"]","rbrke":"⦌","rbrksld":"⦎","rbrkslu":"⦐","Rcaron":"Ř","rcaron":"ř","Rcedil":"Ŗ","rcedil":"ŗ","rceil":"⌉","rcub":"}","Rcy":"Р","rcy":"р","rdca":"⤷","rdldhar":"⥩","rdquo":"”","rdquor":"”","rdsh":"↳","real":"","realine":"","realpart":"","reals":"","Re":"","rect":"▭","reg":"®","REG":"®","ReverseElement":"∋","ReverseEquilibrium":"⇋","ReverseUpEquilibrium":"⥯","rfisht":"⥽","rfloor":"⌋","rfr":"𝔯","Rfr":"","rHar":"⥤","rhard":"⇁","rharu":"⇀","rharul":"⥬","Rho":"Ρ","rho":"ρ","rhov":"ϱ","RightAngleBracket":"⟩","RightArrowBar":"⇥","rightarrow":"→","RightArrow":"→","Rightarrow":"⇒","RightArrowLeftArrow":"⇄","rightarrowtail":"↣","RightCeiling":"⌉","RightDoubleBracket":"⟧","RightDownTeeVector":"⥝","RightDownVectorBar":"⥕","RightDownVector":"⇂","RightFloor":"⌋","rightharpoondown":"⇁","rightharpoonup":"⇀","rightleftarrows":"⇄","rightleftharpoons":"⇌","rightrightarrows":"⇉","rightsquigarrow":"↝","RightTeeArrow":"↦","RightTee":"⊢","RightTeeVector":"⥛","rightthreetimes":"⋌","RightTriangleBar":"⧐","RightTriangle":"⊳","RightTriangleEqual":"⊵","RightUpDownVector":"⥏","RightUpTeeVector":"⥜","RightUpVectorBar":"⥔","RightUpVector":"↾","RightVectorBar":"⥓","RightVector":"⇀","ring":"˚","risingdotseq":"≓","rlarr":"⇄","rlhar":"⇌","rlm":"","rmoustache":"⎱","rmoust":"⎱","rnmid":"⫮","roang":"⟭","roarr":"⇾","robrk":"⟧","ropar":"⦆","ropf":"𝕣","Ropf":"","roplus":"⨮","rotimes":"⨵","RoundImplies":"⥰","rpar":")","rpargt":"⦔","rppolint":"⨒","rrarr":"⇉","Rrightarrow":"⇛","rsaquo":"","rscr":"𝓇","Rscr":"","rsh":"↱","Rsh":"↱","rsqb":"]","rsquo":"","rsquor":"","rthree":"⋌","rtimes":"⋊","rtri":"▹","rtrie":"⊵","rtrif":"▸","rtriltri":"⧎","RuleDelayed":"⧴","ruluhar":"⥨","rx":"℞","Sacute":"Ś","sacute":"ś","sbquo":"","scap":"⪸","Scaron":"Š","scaron":"š","Sc":"⪼","sc":"≻","sccue":"≽","sce":"⪰","scE":"⪴","Scedil":"Ş","scedil":"ş","Scirc":"Ŝ","scirc":"ŝ","scnap":"⪺","scnE":"⪶","scnsim":"⋩","scpolint":"⨓","scsim":"≿","Scy":"С","scy":"с","sdotb":"⊡","sdot":"⋅","sdote":"⩦","searhk":"⤥","searr":"↘","seArr":"⇘","searrow":"↘","sect":"§","semi":";","seswar":"⤩","setminus":"","setmn":"","sext":"✶","Sfr":"𝔖","sfr":"𝔰","sfrown":"⌢","sharp":"♯","SHCHcy":"Щ","shchcy":"щ","SHcy":"Ш","shcy":"ш","ShortDownArrow":"↓","ShortLeftArrow":"←","shortmid":"","shortparallel":"∥","ShortRightArrow":"→","ShortUpArrow":"↑","shy":"­","Sigma":"Σ","sigma":"σ","sigmaf":"ς","sigmav":"ς","sim":"","simdot":"⩪","sime":"≃","simeq":"≃","simg":"⪞","simgE":"⪠","siml":"⪝","simlE":"⪟","simne":"≆","simplus":"⨤","simrarr":"⥲","slarr":"←","SmallCircle":"∘","smallsetminus":"","smashp":"⨳","smeparsl":"⧤","smid":"","smile":"⌣","smt":"⪪","smte":"⪬","smtes":"⪬︀","SOFTcy":"Ь","softcy":"ь","solbar":"⌿","solb":"⧄","sol":"/","Sopf":"𝕊","sopf":"𝕤","spades":"♠","spadesuit":"♠","spar":"∥","sqcap":"⊓","sqcaps":"⊓︀","sqcup":"⊔","sqcups":"⊔︀","Sqrt":"√","sqsub":"⊏","sqsube":"⊑","sqsubset":"⊏","sqsubseteq":"⊑","sqsup":"⊐","sqsupe":"⊒","sqsupset":"⊐","sqsupseteq":"⊒","square":"□","Square":"□","SquareIntersection":"⊓","SquareSubset":"⊏","SquareSubsetEqual":"⊑","SquareSuperset":"⊐","SquareSupersetEqual":"⊒","SquareUnion":"⊔","squarf":"▪","squ":"□","squf":"▪","srarr":"→","Sscr":"𝒮","sscr":"𝓈","ssetmn":"","ssmile":"⌣","sstarf":"⋆","Star":"⋆","star":"☆","starf":"★","straightepsilon":"ϵ","straightphi":"ϕ","strns":"¯","sub":"⊂","Sub":"⋐","subdot":"⪽","subE":"⫅","sube":"⊆","subedot":"⫃","submult":"⫁","subnE":"⫋","subne":"⊊","subplus":"⪿","subrarr":"⥹","subset":"⊂","Subset":"⋐","subseteq":"⊆","subseteqq":"⫅","SubsetEqual":"⊆","subsetneq":"⊊","subsetneqq":"⫋","subsim":"⫇","subsub":"⫕","subsup":"⫓","succapprox":"⪸","succ":"≻","succcurlyeq":"≽","Succeeds":"≻","SucceedsEqual":"⪰","SucceedsSlantEqual":"≽","SucceedsTilde":"≿","succeq":"⪰","succnapprox":"⪺","succneqq":"⪶","succnsim":"⋩","succsim":"≿","SuchThat":"∋","sum":"∑","Sum":"∑","sung":"♪","sup1":"¹","sup2":"²","sup3":"³","sup":"⊃","Sup":"⋑","supdot":"⪾","supdsub":"⫘","supE":"⫆","supe":"⊇","supedot":"⫄","Superset":"⊃","SupersetEqual":"⊇","suphsol":"⟉","suphsub":"⫗","suplarr":"⥻","supmult":"⫂","supnE":"⫌","supne":"⊋","supplus":"⫀","supset":"⊃","Supset":"⋑","supseteq":"⊇","supseteqq":"⫆","supsetneq":"⊋","supsetneqq":"⫌","supsim":"⫈","supsub":"⫔","supsup":"⫖","swarhk":"⤦","swarr":"↙","swArr":"⇙","swarrow":"↙","swnwar":"⤪","szlig":"ß","Tab":"\\t","target":"⌖","Tau":"Τ","tau":"τ","tbrk":"⎴","Tcaron":"Ť","tcaron":"ť","Tcedil":"Ţ","tcedil":"ţ","Tcy":"Т","tcy":"т","tdot":"⃛","telrec":"⌕","Tfr":"𝔗","tfr":"𝔱","there4":"∴","therefore":"∴","Therefore":"∴","Theta":"Θ","theta":"θ","thetasym":"ϑ","thetav":"ϑ","thickapprox":"≈","thicksim":"","ThickSpace":"","ThinSpace":"","thinsp":"","thkap":"≈","thksim":"","THORN":"Þ","thorn":"þ","tilde":"˜","Tilde":"","TildeEqual":"≃","TildeFullEqual":"≅","TildeTilde":"≈","timesbar":"⨱","timesb":"⊠","times":"×","timesd":"⨰","tint":"∭","toea":"⤨","topbot":"⌶","topcir":"⫱","top":"","Topf":"𝕋","topf":"𝕥","topfork":"⫚","tosa":"⤩","tprime":"‴","trade":"™","TRADE":"™","triangle":"▵","triangledown":"▿","triangleleft":"◃","trianglelefteq":"⊴","triangleq":"≜","triangleright":"▹","trianglerighteq":"⊵","tridot":"◬","trie":"≜","triminus":"⨺","TripleDot":"⃛","triplus":"⨹","trisb":"⧍","tritime":"⨻","trpezium":"⏢","Tscr":"𝒯","tscr":"𝓉","TScy":"Ц","tscy":"ц","TSHcy":"Ћ","tshcy":"ћ","Tstrok":"Ŧ","tstrok":"ŧ","twixt":"≬","twoheadleftarrow":"↞","twoheadrightarrow":"↠","Uacute":"Ú","uacute":"ú","uarr":"↑","Uarr":"↟","uArr":"⇑","Uarrocir":"⥉","Ubrcy":"Ў","ubrcy":"ў","Ubreve":"Ŭ","ubreve":"ŭ","Ucirc":"Û","ucirc":"û","Ucy":"У","ucy":"у","udarr":"⇅","Udblac":"Ű","udblac":"ű","udhar":"⥮","ufisht":"⥾","Ufr":"𝔘","ufr":"𝔲","Ugrave":"Ù","ugrave":"ù","uHar":"⥣","uharl":"↿","uharr":"↾","uhblk":"▀","ulcorn":"⌜","ulcorner":"⌜","ulcrop":"⌏","ultri":"◸","Umacr":"Ū","umacr":"ū","uml":"¨","UnderBar":"_","UnderBrace":"⏟","UnderBracket":"⎵","UnderParenthesis":"⏝","Union":"","UnionPlus":"⊎","Uogon":"Ų","uogon":"ų","Uopf":"𝕌","uopf":"𝕦","UpArrowBar":"⤒","uparrow":"↑","UpArrow":"↑","Uparrow":"⇑","UpArrowDownArrow":"⇅","updownarrow":"↕","UpDownArrow":"↕","Updownarrow":"⇕","UpEquilibrium":"⥮","upharpoonleft":"↿","upharpoonright":"↾","uplus":"⊎","UpperLeftArrow":"↖","UpperRightArrow":"↗","upsi":"υ","Upsi":"ϒ","upsih":"ϒ","Upsilon":"Υ","upsilon":"υ","UpTeeArrow":"↥","UpTee":"⊥","upuparrows":"⇈","urcorn":"⌝","urcorner":"⌝","urcrop":"⌎","Uring":"Ů","uring":"ů","urtri":"◹","Uscr":"𝒰","uscr":"𝓊","utdot":"⋰","Utilde":"Ũ","utilde":"ũ","utri":"▵","utrif":"▴","uuarr":"⇈","Uuml":"Ü","uuml":"ü","uwangle":"⦧","vangrt":"⦜","varepsilon":"ϵ","varkappa":"ϰ","varnothing":"∅","varphi":"ϕ","varpi":"ϖ","varpropto":"∝","varr":"↕","vArr":"⇕","varrho":"ϱ","varsigma":"ς","varsubsetneq":"⊊︀","varsubsetneqq":"⫋︀","varsupsetneq":"⊋︀","varsupsetneqq":"⫌︀","vartheta":"ϑ","vartriangleleft":"⊲","vartriangleright":"⊳","vBar":"⫨","Vbar":"⫫","vBarv":"⫩","Vcy":"В","vcy":"в","vdash":"⊢","vDash":"⊨","Vdash":"⊩","VDash":"⊫","Vdashl":"⫦","veebar":"⊻","vee":"","Vee":"","veeeq":"≚","vellip":"⋮","verbar":"|","Verbar":"‖","vert":"|","Vert":"‖","VerticalBar":"","VerticalLine":"|","VerticalSeparator":"❘","VerticalTilde":"≀","VeryThinSpace":"","Vfr":"𝔙","vfr":"𝔳","vltri":"⊲","vnsub":"⊂⃒","vnsup":"⊃⃒","Vopf":"𝕍","vopf":"𝕧","vprop":"∝","vrtri":"⊳","Vscr":"𝒱","vscr":"𝓋","vsubnE":"⫋︀","vsubne":"⊊︀","vsupnE":"⫌︀","vsupne":"⊋︀","Vvdash":"⊪","vzigzag":"⦚","Wcirc":"Ŵ","wcirc":"ŵ","wedbar":"⩟","wedge":"∧","Wedge":"⋀","wedgeq":"≙","weierp":"℘","Wfr":"𝔚","wfr":"𝔴","Wopf":"𝕎","wopf":"𝕨","wp":"℘","wr":"≀","wreath":"≀","Wscr":"𝒲","wscr":"𝓌","xcap":"⋂","xcirc":"◯","xcup":"","xdtri":"▽","Xfr":"𝔛","xfr":"𝔵","xharr":"⟷","xhArr":"⟺","Xi":"Ξ","xi":"ξ","xlarr":"⟵","xlArr":"⟸","xmap":"⟼","xnis":"⋻","xodot":"⨀","Xopf":"𝕏","xopf":"𝕩","xoplus":"⨁","xotime":"⨂","xrarr":"⟶","xrArr":"⟹","Xscr":"𝒳","xscr":"𝓍","xsqcup":"⨆","xuplus":"⨄","xutri":"△","xvee":"","xwedge":"⋀","Yacute":"Ý","yacute":"ý","YAcy":"Я","yacy":"я","Ycirc":"Ŷ","ycirc":"ŷ","Ycy":"Ы","ycy":"ы","yen":"¥","Yfr":"𝔜","yfr":"𝔶","YIcy":"Ї","yicy":"ї","Yopf":"𝕐","yopf":"𝕪","Yscr":"𝒴","yscr":"𝓎","YUcy":"Ю","yucy":"ю","yuml":"ÿ","Yuml":"Ÿ","Zacute":"Ź","zacute":"ź","Zcaron":"Ž","zcaron":"ž","Zcy":"З","zcy":"з","Zdot":"Ż","zdot":"ż","zeetrf":"","ZeroWidthSpace":"","Zeta":"Ζ","zeta":"ζ","zfr":"𝔷","Zfr":"","ZHcy":"Ж","zhcy":"ж","zigrarr":"⇝","zopf":"𝕫","Zopf":"","Zscr":"𝒵","zscr":"𝓏","zwj":"","zwnj":""}');
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __nccwpck_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __nccwpck_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// @ts-check
const core = __nccwpck_require__(2186);
const {"main": markdownlintCli2} = __nccwpck_require__(9247);
const logMessage = core.info;
const logError = (error) => {
// eslint-disable-next-line init-declarations
let annotation;
const match = error.match(/^([^:]+):(\d+)(?::(\d+))?\s(\S+)\s(.+)$/u);
if (match) {
const [
,
file,
startLineString,
startColumnString,
,
title
] = match;
const startLine = Number(startLineString);
annotation = {
title,
file,
startLine
};
if (startColumnString) {
// @ts-ignore
annotation.startColumn = Number(startColumnString);
}
}
core.error(error, annotation);
};
const separator = core.getInput("separator") || "\n";
const argv =
core.getInput("globs").
split(separator).
filter(String);
const parameters = {
argv,
logMessage,
logError
};
let invoke = true;
const command = core.getInput("command");
switch (command) {
case "":
// Default behavior
break;
case "config":
parameters.name = "markdownlint-cli2-config";
break;
case "fix":
parameters.name = "markdownlint-cli2-fix";
parameters.fixDefault = true;
break;
default:
core.setFailed(`Unsupported command: ${command}`);
invoke = false;
break;
}
if (invoke) {
markdownlintCli2(parameters).then(
(code) => code && core.setFailed(`Failed with exit code: ${code}`),
(error) => core.setFailed(`Failed due to error: ${error}`)
);
}
})();
module.exports = __webpack_exports__;
/******/ })()
;