diff --git a/README.md b/README.md index 3f79e64..54afce5 100644 --- a/README.md +++ b/README.md @@ -35,10 +35,10 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Configure AWS Credentials - uses: aws-actions/configure-aws-credentials@v1 + uses: aws-actions/configure-aws-credentials@v2 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} diff --git a/dist/index.js b/dist/index.js index ef757ed..08ff264 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,14 +1,13 @@ -module.exports = /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 2932: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const core = __webpack_require__(2186); -const fs = __webpack_require__(5747); -const YAML = __webpack_require__(3552); -const shell = __webpack_require__(3516); +const core = __nccwpck_require__(2186); +const fs = __nccwpck_require__(7147); +const YAML = __nccwpck_require__(4083); +const shell = __nccwpck_require__(3516); const deployAll = ({ functions, yml, zipParams, alias, layer }) => { let success = true; @@ -51,19 +50,33 @@ module.exports = run; /***/ }), /***/ 7351: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ (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 (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; + 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 })); -const os = __importStar(__webpack_require__(2087)); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(2037)); +const utils_1 = __nccwpck_require__(5278); /** * Commands * @@ -117,28 +130,14 @@ class Command { return cmdStr; } } -/** - * 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; function escapeData(s) { - return toCommandValue(s) + return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { - return toCommandValue(s) + return utils_1.toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') @@ -150,10 +149,29 @@ function escapeProperty(s) { /***/ }), /***/ 2186: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ (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) { @@ -163,17 +181,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __webpack_require__(7351); -const os = __importStar(__webpack_require__(2087)); -const path = __importStar(__webpack_require__(5622)); +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 */ @@ -198,8 +213,12 @@ var ExitCode; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { - const convertedVal = command_1.toCommandValue(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; @@ -216,12 +235,20 @@ exports.setSecret = setSecret; * @param inputPath */ function addPath(inputPath) { - command_1.issueCommand('add-path', {}, 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. The value is also trimmed. + * 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. @@ -232,9 +259,52 @@ function getInput(name, options) { 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. * @@ -243,7 +313,12 @@ exports.getInput = getInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { - command_1.issueCommand('set-output', { 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; /** @@ -289,19 +364,30 @@ 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) { - command_1.issue('error', message instanceof Error ? message.toString() : message); +function error(message, properties = {}) { + command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** - * Adds an warning issue + * 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) { - command_1.issue('warning', message instanceof Error ? message.toString() : message); +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 @@ -361,7 +447,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { 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; /** @@ -374,1813 +464,2604 @@ 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 /***/ }), -/***/ 9417: -/***/ ((module) => { +/***/ 717: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; +// 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' + }); } - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; +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 -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; +/***/ }), - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } +/***/ 8041: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - bi = str.indexOf(b, i + 1); - } +"use strict"; - i = ai < bi && ai >= 0 ? ai : bi; +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); } - - if (begs.length) { - result = [ left, right ]; + 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}`); + } + }); } - } - - return result; } - +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map /***/ }), -/***/ 3717: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var concatMap = __webpack_require__(6891); -var balanced = __webpack_require__(9417); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +/***/ 2981: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} +"use strict"; -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); +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, '/'); } - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +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, '\\'); } - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balanced('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; +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 -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); -} +/***/ }), -function identity(e) { - return e; -} +/***/ 1327: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} +"use strict"; -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); +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 = ''; } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; }); - } } - } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +/***/ }), - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; +/***/ 5278: +/***/ ((__unused_webpack_module, exports) => { - var N; +"use strict"; - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; +// 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 ''; } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); + else if (typeof input === 'string' || input instanceof String) { + return input; } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); + return 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 expansions; + 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 /***/ }), -/***/ 6891: -/***/ ((module) => { +/***/ 5526: +/***/ (function(__unused_webpack_module, exports) { -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; +"use strict"; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; +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 /***/ }), -/***/ 6863: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch - -var fs = __webpack_require__(5747) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync +/***/ 6255: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(1734) +"use strict"; -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} - -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } - - if (typeof cache === 'function') { - cb = cache - cache = null - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) +/* 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; } - }) -} - -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } - - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er + 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()); + }); + })); + }); } - } } - -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} - -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} - - -/***/ }), - -/***/ 1734: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var pathModule = __webpack_require__(5622); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(5747); - -// JavaScript implementation of realpath, ported from node pre-v6 - -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; - - return callback; - - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); +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; + } + } } - } - - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); } - } -} - -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} - -var normalize = pathModule.normalize; - -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} - -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} - -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); } - } - - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); } - - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } - - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; + 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(); } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; + 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 - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - - if (cache) cache[original] = p; - - return p; -}; - - -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } - - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; +/***/ }), - start(); +/***/ 9835: +/***/ ((__unused_webpack_module, exports) => { - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +"use strict"; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); +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); } - } - - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); + else { + return undefined; } - - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; } + 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 (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} +//# sourceMappingURL=proxy.js.map - return fs.lstat(base, gotStat); - } - - function gotStat(err, stat) { - if (err) return cb(err); +/***/ }), - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } +/***/ 9417: +/***/ ((module) => { - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); +"use strict"; - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); - function gotTarget(err, target, base) { - if (err) return cb(err); + var r = range(a, b, str); - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; -/***/ }), + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; -/***/ 7625: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } -exports.alphasort = alphasort -exports.alphasorti = alphasorti -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored + bi = str.indexOf(b, i + 1); + } -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} + i = ai < bi && ai >= 0 ? ai : bi; + } -var path = __webpack_require__(5622) -var minimatch = __webpack_require__(3973) -var isAbsolute = __webpack_require__(8714) -var Minimatch = minimatch.Minimatch + if (begs.length) { + result = [ left, right ]; + } + } -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) + return result; } -function alphasort (a, b) { - return a.localeCompare(b) -} -function setupIgnores (self, options) { - self.ignore = options.ignore || [] +/***/ }), - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] +/***/ 3717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} +var concatMap = __nccwpck_require__(6891); +var balanced = __nccwpck_require__(9417); -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } +module.exports = expandTop; - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -function setopts (self, pattern, options) { - if (!options) - options = {} +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - setupIgnores(self, options) +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd - } + var parts = []; + var m = balanced('{', '}', str); - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") + if (!m) + return str.split(','); - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options + parts.push.apply(parts, p); + + return parts; } -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) +function expandTop(str) { + if (!str) + return []; - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); } - if (!nou) - all = Object.keys(all) - - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) + return expand(escapeBraces(str), true).map(unescapeBraces); +} - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) - } - } +function identity(e) { + return e; +} - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} - self.found = all +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; } -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' +function expand(str, isTop) { + var expansions = []; - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); } + return [str]; } - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) + var n; + if (isSequence) { + n = m.body.split(/\.\./); } else { - abs = path.resolve(f) + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - return abs -} + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + var N; -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + N = []; -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) + return expansions; } + /***/ }), -/***/ 1957: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 6891: +/***/ ((module) => { -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; -module.exports = glob +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; -var fs = __webpack_require__(5747) -var rp = __webpack_require__(6863) -var minimatch = __webpack_require__(3973) -var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(4124) -var EE = __webpack_require__(8614).EventEmitter -var path = __webpack_require__(5622) -var assert = __webpack_require__(2357) -var isAbsolute = __webpack_require__(8714) -var globSync = __webpack_require__(9010) -var common = __webpack_require__(7625) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __webpack_require__(2492) -var util = __webpack_require__(1669) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored -var once = __webpack_require__(1223) +/***/ }), -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} +/***/ 6863: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch - return new Glob(pattern, options, cb) +var fs = __nccwpck_require__(7147) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync + +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __nccwpck_require__(1734) + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) } -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } -// old api surface -glob.glob = glob + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) +} -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) } - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } } - return origin } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} - var g = new Glob(pattern, options) - var set = g.minimatch.set +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} - if (!pattern) - return false - if (set.length > 1) - return true +/***/ }), - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } +/***/ 1734: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return false -} +// 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. -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null +var pathModule = __nccwpck_require__(1017); +var isWindows = process.platform === 'win32'; +var fs = __nccwpck_require__(7147); + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } } - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } } +} - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} - setopts(this, pattern, options) - this._didRealPath = false +var normalize = pathModule.normalize; - // process each pattern in the minimatch set - var n = this.minimatch.set.length +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) - } +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); - var self = this - this._processing = 0 + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } - this._emitQueue = [] - this._processQueue = [] - this.paused = false + var original = p, + seenLinks = {}, + knownHard = {}; - if (this.noprocess) - return this + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; - if (n === 0) - return done() + start(); - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; } } -} - -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - if (this.realpath && !this._didRealpath) - return this._realpath() + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; - common.finish(this) - this.emit('end', this.found) -} + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } -Glob.prototype._realpath = function () { - if (this._didRealpath) - return + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } - this._didRealpath = true + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } - var n = this.matches.length - if (n === 0) - return this._finish() + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) + if (cache) cache[original] = p; - function next () { - if (--n === 0) - self._finish() - } -} + return p; +}; -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() - var found = Object.keys(matchset) - var self = this - var n = found.length +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } - if (n === 0) - return cb() + // make p is absolute + p = pathModule.resolve(p); - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) -} + var original = p, + seenLinks = {}, + knownHard = {}; -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + start(); -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } } -} -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); } + + return fs.lstat(base, gotStat); } -} -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') + function gotStat(err, stat) { + if (err) return cb(err); - if (this.aborted) - return + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); } - //console.error('PROCESS %d', this._processing, pattern) + function gotTarget(err, target, base) { + if (err) return cb(err); - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); } - // now n is the index of the first one that is *not* a string. - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } +/***/ }), - var remain = pattern.slice(n) +/***/ 7625: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored - var abs = this._makeAbs(read) +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() +var fs = __nccwpck_require__(7147) +var path = __nccwpck_require__(1017) +var minimatch = __nccwpck_require__(3973) +var isAbsolute = __nccwpck_require__(8714) +var Minimatch = minimatch.Minimatch - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +function alphasort (a, b) { + return a.localeCompare(b, 'en') } -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } } -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' +function setopts (self, pattern, options) { + if (!options) + options = {} - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") } + pattern = "**/" + pattern } - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + self.fs = options.fs || fs - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + setupIgnores(self, options) - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + // always treat \ in patterns as escapes, not path separators + options.allowWindowsEscape = false + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) else - e = prefix + e + m.forEach(function (m) { + all[m] = true + }) } - this._process([e].concat(remain), index, inGlobStar, cb) } - cb() -} -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return + if (!nou) + all = Object.keys(all) - if (isIgnored(this, e)) - return + if (!self.nosort) + all = all.sort(alphasort) - if (this.paused) { - this._emitQueue.push([index, e]) - return + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } } - var abs = isAbsolute(e) ? e : this._makeAbs(e) + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) - if (this.mark) - e = this._mark(e) + self.found = all +} - if (this.absolute) - e = abs +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' - if (this.matches[index][e]) - return + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } } - this.matches[index][e] = true - - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) - - this.emit('match', e) + return m } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return - - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) - - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) - - if (lstatcb) - fs.lstat(abs, lstatcb) - - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() - - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) } -} - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) + return abs +} - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() - if (Array.isArray(c)) - return cb(null, c) - } +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false - var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) } -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) } -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } +/***/ }), - this.cache[abs] = entries - return cb(null, entries) -} +/***/ 1957: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break +module.exports = glob - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +var rp = __nccwpck_require__(6863) +var minimatch = __nccwpck_require__(3973) +var Minimatch = minimatch.Minimatch +var inherits = __nccwpck_require__(4124) +var EE = (__nccwpck_require__(2361).EventEmitter) +var path = __nccwpck_require__(1017) +var assert = __nccwpck_require__(9491) +var isAbsolute = __nccwpck_require__(8714) +var globSync = __nccwpck_require__(9010) +var common = __nccwpck_require__(7625) +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __nccwpck_require__(2492) +var util = __nccwpck_require__(3837) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } +var once = __nccwpck_require__(1223) - return cb() -} +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + return new Glob(pattern, options, cb) +} -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() +// old api surface +glob.glob = glob - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} - var isSym = this.symlinks[abs] - var len = entries.length +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() + var g = new Glob(pattern, options) + var set = g.minimatch.set - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + if (!pattern) + return false - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) + if (set.length > 1) + return true - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true } - cb() -} - -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) + return false } -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { - - //console.error('ps2', prefix, exists) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} + setopts(this, pattern, options) + this._didRealPath = false -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + // process each pattern in the minimatch set + var n = this.minimatch.set.length - if (f.length > this.maxLength) - return cb() + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } - if (Array.isArray(c)) - c = 'DIR' + var self = this + this._processing = 0 - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) + this._emitQueue = [] + this._processQueue = [] + this.paused = false - if (needDir && c === 'FILE') - return cb() + if (this.noprocess) + return this - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + if (n === 0) + return done() - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) } + sync = false - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } } } } -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } - - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat - - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return - if (needDir && c === 'FILE') - return cb() + if (this.realpath && !this._didRealpath) + return this._realpath() - return cb(null, c, stat) + common.finish(this) + this.emit('end', this.found) } +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true -/***/ }), + var n = this.matches.length + if (n === 0) + return this._finish() -/***/ 9010: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) -module.exports = globSync -globSync.GlobSync = GlobSync + function next () { + if (--n === 0) + self._finish() + } +} -var fs = __webpack_require__(5747) -var rp = __webpack_require__(6863) -var minimatch = __webpack_require__(3973) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(1957).Glob -var util = __webpack_require__(1669) -var path = __webpack_require__(5622) -var assert = __webpack_require__(2357) -var isAbsolute = __webpack_require__(8714) -var common = __webpack_require__(7625) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + var found = Object.keys(matchset) + var self = this + var n = found.length - return new GlobSync(pattern, options).found -} + if (n === 0) + return cb() -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} - setopts(this, pattern, options) +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} - if (this.noprocess) - return this +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') } - this._finish() } -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) } - }) + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } } - common.finish(this) } +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 @@ -2189,12 +3070,12 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { } // now n is the index of the first one that is *not* a string. - // See if there's anything else + // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: - this._processSimple(pattern.join('/'), index) + this._processSimple(pattern.join('/'), index, cb) return case 0: @@ -2217,7 +3098,10 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix @@ -2226,24 +3110,29 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { var abs = this._makeAbs(read) - //if ignored, skip processing + //if ignored, skip _processing if (childrenIgnored(this, read)) - return + return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) - return + return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. @@ -2267,10 +3156,12 @@ GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, } } + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) - return + return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or @@ -2284,7 +3175,7 @@ GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { - if (prefix.slice(-1) !== '/') + if (prefix !== '/') e = prefix + '/' + e else e = prefix + e @@ -2296,7 +3187,7 @@ GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, this._emitMatch(index, e) } // This was the last one, and no stats were needed - return + return cb() } // now test all matched entries as stand-ins for that part @@ -2305,27 +3196,36 @@ GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) } + cb() } +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return -GlobSync.prototype._emitMatch = function (index, e) { if (isIgnored(this, e)) return - var abs = this._makeAbs(e) + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) - if (this.absolute) { + if (this.absolute) e = abs - } if (this.matches[index][e]) return @@ -2338,66 +3238,84 @@ GlobSync.prototype._emitMatch = function (index, e) { this.matches[index][e] = true - if (this.stat) - this._stat(e) + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) } +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return -GlobSync.prototype._readdirInGlobStar = function (abs) { // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) - return this._readdir(abs, false) + return this._readdir(abs, false, cb) - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym + if (lstatcb) + self.fs.lstat(abs, lstatcb) - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() - return entries + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } } -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) + return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') - return null + return cb() if (Array.isArray(c)) - return c + return cb(null, c) } - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null + var self = this + self.fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) } } -GlobSync.prototype._readdirEntries = function (abs, entries) { +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. @@ -2413,12 +3331,13 @@ GlobSync.prototype._readdirEntries = function (abs, entries) { } this.cache[abs] = entries - - // mark and cache dir-ness - return entries + return cb(null, entries) } -GlobSync.prototype._readdirError = function (f, er) { +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 @@ -2429,7 +3348,8 @@ GlobSync.prototype._readdirError = function (f, er) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code - throw error + this.emit('error', error) + this.abort() } break @@ -2442,11809 +3362,15099 @@ GlobSync.prototype._readdirError = function (f, er) { default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } if (!this.silent) console.error('glob error', er) break } -} - -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) - - var len = entries.length - var isSym = this.symlinks[abs] - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) - - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} - -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return - - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) -} - -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] - - if (Array.isArray(c)) - c = 'DIR' - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - - if (needDir && c === 'FILE') - return false - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } - - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat - } - } - - this.statCache[abs] = stat - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return false - - return c -} - -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} - -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} - - -/***/ }), - -/***/ 2492: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var wrappy = __webpack_require__(2940) -var reqs = Object.create(null) -var once = __webpack_require__(1223) - -module.exports = wrappy(inflight) - -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} - -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) - - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} - -function slice (args) { - var length = args.length - var array = [] - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} - - -/***/ }), - -/***/ 4124: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -try { - var util = __webpack_require__(1669); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __webpack_require__(8544); + return cb() } +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} -/***/ }), -/***/ 8544: -/***/ ((module) => { +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -/***/ }), + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) -/***/ 3973: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + var isSym = this.symlinks[abs] + var len = entries.length -module.exports = minimatch -minimatch.Minimatch = Minimatch + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() -var path = { sep: '/' } -try { - path = __webpack_require__(5622) -} catch (er) {} + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(3717) + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() } -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { -// * => any number of characters -var star = qmark + '*?' + //console.error('ps2', prefix, exists) -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + if (!this.matches[index]) + this.matches[index] = Object.create(null) -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() } -// normalizes slashes. -var slashSplit = /\/+/ +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} + if (f.length > this.maxLength) + return cb() -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch + if (Array.isArray(c)) + c = 'DIR' - var orig = minimatch + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } } - return m -} + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + self.fs.lstat(abs, statcb) -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } } -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() } - if (!options) options = {} + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) - // "" only matches "" - if (pattern.trim() === '') return p === '' + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c - return new Minimatch(pattern, options).match(p) + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } +/***/ }), - if (!options) options = {} - pattern = pattern.trim() +/***/ 9010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } +module.exports = globSync +globSync.GlobSync = GlobSync - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false +var rp = __nccwpck_require__(6863) +var minimatch = __nccwpck_require__(3973) +var Minimatch = minimatch.Minimatch +var Glob = (__nccwpck_require__(1957).Glob) +var util = __nccwpck_require__(3837) +var path = __nccwpck_require__(1017) +var assert = __nccwpck_require__(9491) +var isAbsolute = __nccwpck_require__(8714) +var common = __nccwpck_require__(7625) +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored - // make the set of regexps etc. - this.make() +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found } -Minimatch.prototype.debug = function () {} +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') - var pattern = this.pattern - var options = this.options + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) } - if (!pattern) { - this.empty = true - return + this._finish() +} + +GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) } + common.finish(this) +} - // step 1: figure out negation, etc. - this.parseNegate() - // step 2: expand braces - var set = this.globSet = this.braceExpand() +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync) - if (options.debug) this.debug = console.error + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. - this.debug(this.pattern, set) + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - this.debug(this.pattern, set) + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + var remain = pattern.slice(n) - this.debug(this.pattern, set) + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + var abs = this._makeAbs(read) - this.debug(this.pattern, set) + //if ignored, skip processing + if (childrenIgnored(this, read)) + return - this.set = set + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) } -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 - if (options.nonegate) return +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } } - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. -Minimatch.prototype.braceExpand = braceExpand + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) } + // This was the last one, and no stats were needed + return } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern - - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) } +} - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - return expand(pattern) -} +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs } - var options = this.options + if (this.matches[index][e]) + return - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this + this.matches[index][e] = true - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null } } - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false + return entries +} - case '\\': - clearStateChar() - escaping = true - continue +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue + if (Array.isArray(c)) + return c + } - case '(': - if (inClass) { - re += '(' - continue - } + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} - if (!stateChar) { - re += '\\(' - continue - } +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue + this.cache[abs] = entries - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } + // mark and cache dir-ness + return entries +} - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break - clearStateChar() - re += '|' - continue + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - if (inClass) { - re += '\\' + c - continue - } + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } + var len = entries.length + var isSym = this.symlinks[abs] - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return - // finish up the class. - hasMagic = true - inClass = false - re += c + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) continue - default: - // swallow any state char that wasn't consumed - clearStateChar() + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} - re += c +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) - } // switch - } // for + if (!this.matches[index]) + this.matches[index] = Object.create(null) - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } } - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) + // Mark this as a match + this._emitMatch(index, prefix) +} - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } + if (f.length > this.maxLength) + return false - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } + if (Array.isArray(c)) + c = 'DIR' - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) + if (needDir && c === 'FILE') + return false - nlLast += nlAfter + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } } - nlAfter = cleanAfter - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe } - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } + this.statCache[abs] = stat - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } + this.cache[abs] = this.cache[abs] || c - regExp._glob = pattern - regExp._src = re + if (needDir && c === 'FILE') + return false - return regExp + return c } -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) } -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') +/***/ }), - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' +/***/ 2492: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' +var wrappy = __nccwpck_require__(2940) +var reqs = Object.create(null) +var once = __nccwpck_require__(1223) - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) } - return this.regexp } -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list } -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' +function slice (args) { + var length = args.length + var array = [] - if (f === '/' && partial) return true + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} - var options = this.options - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } +/***/ }), - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) +/***/ 4124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. +try { + var util = __nccwpck_require__(3837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} - var set = this.set - this.debug(this.pattern, 'set', set) - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } +/***/ }), - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] +/***/ 8544: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor } } +} - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate + +/***/ }), + +/***/ 3973: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = (function () { try { return __nccwpck_require__(1017) } catch (e) {}}()) || { + sep: '/' } +minimatch.sep = path.sep -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __nccwpck_require__(3717) - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} - this.debug('matchOne', file.length, pattern.length) +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] +// * => any number of characters +var star = qmark + '*?' - this.debug(pattern, p, f) +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) +function ext (a, b) { + b = b || {} + var t = {} + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + return t +} - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } +minimatch.defaults = function (def) { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + var orig = minimatch - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } + var m = function minimatch (p, pattern, options) { + return orig(p, pattern, ext(def, options)) + } - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + m.Minimatch.defaults = function defaults (options) { + return orig.defaults(ext(def, options)).Minimatch + } - if (!hit) return false + m.filter = function filter (pattern, options) { + return orig.filter(pattern, ext(def, options)) } - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* + m.defaults = function defaults (options) { + return orig.defaults(ext(def, options)) + } - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd + m.makeRe = function makeRe (pattern, options) { + return orig.makeRe(pattern, ext(def, options)) } - // should be unreachable. - throw new Error('wtf?') + m.braceExpand = function braceExpand (pattern, options) { + return orig.braceExpand(pattern, ext(def, options)) + } + + m.match = function (list, pattern, options) { + return orig.match(list, pattern, ext(def, options)) + } + + return m } -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') +Minimatch.defaults = function (def) { + return minimatch.defaults(def).Minimatch } -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +function minimatch (p, pattern, options) { + assertValidPattern(pattern) + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) } +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } -/***/ }), + assertValidPattern(pattern) -/***/ 1223: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (!options) options = {} -var wrappy = __webpack_require__(2940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + pattern = pattern.trim() -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true + // windows support: need to use /, not \ + if (!options.allowWindowsEscape && path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) }) - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 }) -}) -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f + this.debug(this.pattern, set) + + this.set = set } -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) } +Minimatch.prototype.braceExpand = braceExpand -/***/ }), +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } -/***/ 8714: -/***/ ((module) => { + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern -"use strict"; + assertValidPattern(pattern) + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } -function posix(path) { - return path.charAt(0) === '/'; + return expand(pattern) } -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); +var MAX_PATTERN_LENGTH = 1024 * 64 +var assertValidPattern = function (pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } - // UNC paths are always absolute - return Boolean(result[2] || isUnc); + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } } -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + assertValidPattern(pattern) + var options = this.options -/***/ }), + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' -/***/ 5123: -/***/ ((module) => { + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this -module.exports = [ - 'cat', - 'cd', - 'chmod', - 'cp', - 'dirs', - 'echo', - 'exec', - 'find', - 'grep', - 'head', - 'ln', - 'ls', - 'mkdir', - 'mv', - 'pwd', - 'rm', - 'sed', - 'set', - 'sort', - 'tail', - 'tempdir', - 'test', - 'to', - 'toEnd', - 'touch', - 'uniq', - 'which', -]; + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } -/***/ }), + switch (c) { + /* istanbul ignore next */ + case '/': { + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + } -/***/ 3516: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + case '\\': + clearStateChar() + escaping = true + continue -// -// ShellJS -// Unix shell commands on top of Node's API -// -// Copyright (c) 2012 Artur Adib -// http://github.com/shelljs/shelljs -// + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) -function __ncc_wildcard$0 (arg) { - if (arg === "cat.js" || arg === "cat") return __webpack_require__(271); - else if (arg === "cd.js" || arg === "cd") return __webpack_require__(2051); - else if (arg === "chmod.js" || arg === "chmod") return __webpack_require__(4975); - else if (arg === "common.js" || arg === "common") return __webpack_require__(3687); - else if (arg === "cp.js" || arg === "cp") return __webpack_require__(4932); - else if (arg === "dirs.js" || arg === "dirs") return __webpack_require__(1178); - else if (arg === "echo.js" || arg === "echo") return __webpack_require__(243); - else if (arg === "error.js" || arg === "error") return __webpack_require__(232); - else if (arg === "exec-child.js" || arg === "exec-child") return __webpack_require__(9607); - else if (arg === "exec.js" || arg === "exec") return __webpack_require__(896); - else if (arg === "find.js" || arg === "find") return __webpack_require__(7838); - else if (arg === "grep.js" || arg === "grep") return __webpack_require__(7417); - else if (arg === "head.js" || arg === "head") return __webpack_require__(6613); - else if (arg === "ln.js" || arg === "ln") return __webpack_require__(5787); - else if (arg === "ls.js" || arg === "ls") return __webpack_require__(5561); - else if (arg === "mkdir.js" || arg === "mkdir") return __webpack_require__(2695); - else if (arg === "mv.js" || arg === "mv") return __webpack_require__(9849); - else if (arg === "popd.js" || arg === "popd") return __webpack_require__(227); - else if (arg === "pushd.js" || arg === "pushd") return __webpack_require__(4177); - else if (arg === "pwd.js" || arg === "pwd") return __webpack_require__(8553); - else if (arg === "rm.js" || arg === "rm") return __webpack_require__(2830); - else if (arg === "sed.js" || arg === "sed") return __webpack_require__(5899); - else if (arg === "set.js" || arg === "set") return __webpack_require__(1411); - else if (arg === "sort.js" || arg === "sort") return __webpack_require__(2116); - else if (arg === "tail.js" || arg === "tail") return __webpack_require__(2284); - else if (arg === "tempdir.js" || arg === "tempdir") return __webpack_require__(6150); - else if (arg === "test.js" || arg === "test") return __webpack_require__(9723); - else if (arg === "to.js" || arg === "to") return __webpack_require__(1961); - else if (arg === "toEnd.js" || arg === "toEnd") return __webpack_require__(3736); - else if (arg === "touch.js" || arg === "touch") return __webpack_require__(8358); - else if (arg === "uniq.js" || arg === "uniq") return __webpack_require__(7286); - else if (arg === "which.js" || arg === "which") return __webpack_require__(4766); -} -var common = __webpack_require__(3687); + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -//@ -//@ All commands run synchronously, unless otherwise stated. -//@ All commands accept standard bash globbing characters (`*`, `?`, etc.), -//@ compatible with the [node `glob` module](https://github.com/isaacs/node-glob). -//@ -//@ For less-commonly used commands and features, please check out our [wiki -//@ page](https://github.com/shelljs/shelljs/wiki). -//@ + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue -// Include the docs for all the default commands -//@commands + case '(': + if (inClass) { + re += '(' + continue + } -// Load all default commands -__webpack_require__(5123).forEach(function (command) { - __ncc_wildcard$0(command); -}); + if (!stateChar) { + re += '\\(' + continue + } -//@ -//@ ### exit(code) -//@ -//@ Exits the current process with the given exit `code`. -exports.exit = process.exit; + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue -//@include ./src/error -exports.error = __webpack_require__(232); + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -//@include ./src/common -exports.ShellString = common.ShellString; + if (inClass) { + re += '\\' + c + continue + } -//@ -//@ ### env['VAR_NAME'] -//@ -//@ Object containing environment variables (both getter and setter). Shortcut -//@ to `process.env`. -exports.env = process.env; + inClass = true + classStart = i + reClassStart = re.length + re += c + continue -//@ -//@ ### Pipes -//@ -//@ Examples: -//@ -//@ ```javascript -//@ grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); -//@ echo('files with o\'s in the name:\n' + ls().grep('o')); -//@ cat('test.js').exec('node'); // pipe to exec() call -//@ ``` -//@ -//@ Commands can send their output to another command in a pipe-like fashion. -//@ `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand -//@ side of a pipe. Pipes can be chained. + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } -//@ -//@ ## Configuration -//@ + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } -exports.config = common.config; + // finish up the class. + hasMagic = true + inClass = false + re += c + continue -//@ -//@ ### config.silent -//@ -//@ Example: -//@ -//@ ```javascript -//@ var sh = require('shelljs'); -//@ var silentState = sh.config.silent; // save old silent state -//@ sh.config.silent = true; -//@ /* ... */ -//@ sh.config.silent = silentState; // restore old silent state -//@ ``` -//@ -//@ Suppresses all command output if `true`, except for `echo()` calls. -//@ Default is `false`. + default: + // swallow any state char that wasn't consumed + clearStateChar() -//@ -//@ ### config.fatal -//@ -//@ Example: -//@ -//@ ```javascript -//@ require('shelljs/global'); -//@ config.fatal = true; // or set('-e'); -//@ cp('this_file_does_not_exist', '/dev/null'); // throws Error here -//@ /* more commands... */ -//@ ``` -//@ -//@ If `true`, the script will throw a Javascript error when any shell.js -//@ command encounters an error. Default is `false`. This is analogous to -//@ Bash's `set -e`. + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } -//@ -//@ ### config.verbose -//@ -//@ Example: -//@ -//@ ```javascript -//@ config.verbose = true; // or set('-v'); -//@ cd('dir/'); -//@ rm('-rf', 'foo.txt', 'bar.txt'); -//@ exec('echo hello'); -//@ ``` -//@ -//@ Will print each command as follows: -//@ -//@ ``` -//@ cd dir/ -//@ rm -rf foo.txt bar.txt -//@ exec echo hello -//@ ``` + re += c -//@ -//@ ### config.globOptions -//@ -//@ Example: -//@ -//@ ```javascript -//@ config.globOptions = {nodir: true}; -//@ ``` -//@ -//@ Use this value for calls to `glob.sync()` instead of the default options. + } // switch + } // for -//@ -//@ ### config.reset() -//@ -//@ Example: -//@ -//@ ```javascript -//@ var shell = require('shelljs'); -//@ // Make changes to shell.config, and do stuff... -//@ /* ... */ -//@ shell.config.reset(); // reset to original state -//@ // Do more stuff, but with original settings -//@ /* ... */ -//@ ``` -//@ -//@ Reset `shell.config` to the defaults: -//@ -//@ ```javascript -//@ { -//@ fatal: false, -//@ globOptions: {}, -//@ maxdepth: 255, -//@ noglob: false, -//@ silent: false, -//@ verbose: false, -//@ } -//@ ``` + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } -/***/ }), + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) -/***/ 271: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -common.register('cat', _cat, { - canReceivePipe: true, - cmdOptions: { - 'n': 'number', - }, -}); + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } -//@ -//@ ### cat([options,] file [, file ...]) -//@ ### cat([options,] file_array) -//@ -//@ Available options: -//@ -//@ + `-n`: number all output lines -//@ -//@ Examples: -//@ -//@ ```javascript -//@ var str = cat('file*.txt'); -//@ var str = cat('file1', 'file2'); -//@ var str = cat(['file1', 'file2']); // same as above -//@ ``` -//@ -//@ Returns a string containing the given file, or a concatenated string -//@ containing the files if more than one file is given (a new line character is -//@ introduced between each file). -function _cat(options, files) { - var cat = common.readFromPipe(); + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '[': case '.': case '(': addPatternStart = true + } - if (!files && !cat) common.error('no paths given'); + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] - files = [].slice.call(arguments, 1); + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) - files.forEach(function (file) { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file); - } else if (common.statFollowLinks(file).isDirectory()) { - common.error(file + ': Is a directory'); + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } + nlAfter = cleanAfter - cat += fs.readFileSync(file, 'utf8'); - }); + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } - if (options.number) { - cat = addNumbers(cat); + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re } - return cat; -} -module.exports = _cat; + if (addPatternStart) { + re = patternStart + re + } -function addNumbers(cat) { - var lines = cat.split('\n'); - var lastLine = lines.pop(); + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } - lines = lines.map(function (line, i) { - return numberedLine(i + 1, line); - }); + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } - if (lastLine.length) { - lastLine = numberedLine(lines.length + 1, lastLine); + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } - lines.push(lastLine); - return lines.join('\n'); + regExp._glob = pattern + regExp._src = re + + return regExp } -function numberedLine(n, line) { - // GNU cat use six pad start number + tab. See http://lingrok.org/xref/coreutils/src/cat.c#57 - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart - var number = (' ' + n).slice(-6) + '\t'; - return number + line; +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() } +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp -/***/ }), + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set -/***/ 2051: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options -var os = __webpack_require__(2087); -var common = __webpack_require__(3687); + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' -common.register('cd', _cd, {}); + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') -//@ -//@ ### cd([dir]) -//@ -//@ Changes to directory `dir` for the duration of the script. Changes to home -//@ directory if no argument is supplied. -function _cd(options, dir) { - if (!dir) dir = os.homedir(); + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' - if (dir === '-') { - if (!process.env.OLDPWD) { - common.error('could not find previous directory'); - } else { - dir = process.env.OLDPWD; - } - } + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' try { - var curDir = process.cwd(); - process.chdir(dir); - process.env.OLDPWD = curDir; - } catch (e) { - // something went wrong, let's figure out the error - var err; - try { - common.statFollowLinks(dir); // if this succeeds, it must be some sort of file - err = 'not a directory: ' + dir; - } catch (e2) { - err = 'no such file or directory: ' + dir; - } - if (err) common.error(err); + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false } - return ''; + return this.regexp } -module.exports = _cd; +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} -/***/ }), - -/***/ 4975: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +Minimatch.prototype.match = function match (f, partial) { + if (typeof partial === 'undefined') partial = this.partial + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); + if (f === '/' && partial) return true -var PERMS = (function (base) { - return { - OTHER_EXEC: base.EXEC, - OTHER_WRITE: base.WRITE, - OTHER_READ: base.READ, + var options = this.options - GROUP_EXEC: base.EXEC << 3, - GROUP_WRITE: base.WRITE << 3, - GROUP_READ: base.READ << 3, + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } - OWNER_EXEC: base.EXEC << 6, - OWNER_WRITE: base.WRITE << 6, - OWNER_READ: base.READ << 6, + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - // Literal octal numbers are apparently not allowed in "strict" javascript. - STICKY: parseInt('01000', 8), - SETGID: parseInt('02000', 8), - SETUID: parseInt('04000', 8), + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - TYPE_MASK: parseInt('0770000', 8), - }; -}({ - EXEC: 1, - WRITE: 2, - READ: 4, -})); + var set = this.set + this.debug(this.pattern, 'set', set) -common.register('chmod', _chmod, { -}); + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } -//@ -//@ ### chmod([options,] octal_mode || octal_string, file) -//@ ### chmod([options,] symbolic_mode, file) -//@ -//@ Available options: -//@ -//@ + `-v`: output a diagnostic for every file processed//@ -//@ + `-c`: like verbose, but report only when a change is made//@ -//@ + `-R`: change files and directories recursively//@ -//@ -//@ Examples: -//@ -//@ ```javascript -//@ chmod(755, '/Users/brandon'); -//@ chmod('755', '/Users/brandon'); // same as above -//@ chmod('u+x', '/Users/brandon'); -//@ chmod('-R', 'a-w', '/Users/brandon'); -//@ ``` -//@ -//@ Alters the permissions of a file or directory by either specifying the -//@ absolute permissions in octal form or expressing the changes in symbols. -//@ This command tries to mimic the POSIX behavior as much as possible. -//@ Notable exceptions: -//@ -//@ + In symbolic modes, `a-r` and `-r` are identical. No consideration is -//@ given to the `umask`. -//@ + There is no "quiet" option, since default behavior is to run silent. -function _chmod(options, mode, filePattern) { - if (!filePattern) { - if (options.length > 0 && options.charAt(0) === '-') { - // Special case where the specified file permissions started with - to subtract perms, which - // get picked up by the option parser as command flags. - // If we are down by one argument and options starts with -, shift everything over. - [].unshift.call(arguments, ''); - } else { - common.error('You must specify a file.'); + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } } - options = common.parseOptions(options, { - 'R': 'recursive', - 'c': 'changes', - 'v': 'verbose', - }); + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - filePattern = [].slice.call(arguments, 2); + this.debug('matchOne', file.length, pattern.length) - var files; + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] - // TODO: replace this with a call to common.expand() - if (options.recursive) { - files = []; - filePattern.forEach(function addFile(expandedFile) { - var stat = common.statNoFollowLinks(expandedFile); + this.debug(pattern, p, f) - if (!stat.isSymbolicLink()) { - files.push(expandedFile); + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false - if (stat.isDirectory()) { // intentionally does not follow symlinks. - fs.readdirSync(expandedFile).forEach(function (child) { - addFile(expandedFile + '/' + child); - }); + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false } + return true } - }); - } else { - files = filePattern; - } - files.forEach(function innerChmod(file) { - file = path.resolve(file); - if (!fs.existsSync(file)) { - common.error('File not found: ' + file); + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false } - // When recursing, don't follow symlinks. - if (options.recursive && common.statNoFollowLinks(file).isSymbolicLink()) { - return; + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) } - var stat = common.statFollowLinks(file); - var isDir = stat.isDirectory(); - var perms = stat.mode; - var type = perms & PERMS.TYPE_MASK; + if (!hit) return false + } - var newPerms = perms; + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* - if (isNaN(parseInt(mode, 8))) { - // parse options - mode.split(',').forEach(function (symbolicMode) { - var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; - var matches = pattern.exec(symbolicMode); + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } - if (matches) { - var applyTo = matches[1]; - var operator = matches[2]; - var change = matches[3]; + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') +} - var changeOwner = applyTo.indexOf('u') !== -1 || applyTo === 'a' || applyTo === ''; - var changeGroup = applyTo.indexOf('g') !== -1 || applyTo === 'a' || applyTo === ''; - var changeOther = applyTo.indexOf('o') !== -1 || applyTo === 'a' || applyTo === ''; +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} - var changeRead = change.indexOf('r') !== -1; - var changeWrite = change.indexOf('w') !== -1; - var changeExec = change.indexOf('x') !== -1; - var changeExecDir = change.indexOf('X') !== -1; - var changeSticky = change.indexOf('t') !== -1; - var changeSetuid = change.indexOf('s') !== -1; +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} - if (changeExecDir && isDir) { - changeExec = true; - } - var mask = 0; - if (changeOwner) { - mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0); - } - if (changeGroup) { - mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0); - } - if (changeOther) { - mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0); - } +/***/ }), - // Sticky bit is special - it's not tied to user, group or other. - if (changeSticky) { - mask |= PERMS.STICKY; - } +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - switch (operator) { - case '+': - newPerms |= mask; - break; +var wrappy = __nccwpck_require__(2940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) - case '-': - newPerms &= ~mask; - break; +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} - case '=': - newPerms = type + mask; - // According to POSIX, when using = to explicitly set the - // permissions, setuid and setgid can never be cleared. - if (common.statFollowLinks(file).isDirectory()) { - newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; - } - break; - default: - common.error('Could not recognize operator: `' + operator + '`'); - } +/***/ }), - if (options.verbose) { - console.log(file + ' -> ' + newPerms.toString(8)); - } +/***/ 8714: +/***/ ((module) => { - if (perms !== newPerms) { - if (!options.verbose && options.changes) { - console.log(file + ' -> ' + newPerms.toString(8)); - } - fs.chmodSync(file, newPerms); - perms = newPerms; // for the next round of changes! - } - } else { - common.error('Invalid symbolic mode change: ' + symbolicMode); - } - }); - } else { - // they gave us a full number - newPerms = type + parseInt(mode, 8); +"use strict"; - // POSIX rules are that setuid and setgid can only be added using numeric - // form, but not cleared. - if (common.statFollowLinks(file).isDirectory()) { - newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; - } - fs.chmodSync(file, newPerms); - } - }); - return ''; +function posix(path) { + return path.charAt(0) === '/'; } -module.exports = _chmod; +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); -/***/ }), - -/***/ 3687: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} -"use strict"; -// Ignore warning about 'new String()' -/* eslint no-new-wrappers: 0 */ +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; -var os = __webpack_require__(2087); -var fs = __webpack_require__(5747); -var glob = __webpack_require__(1957); -var shell = __webpack_require__(3516); +/***/ }), -var shellMethods = Object.create(shell); +/***/ 5123: +/***/ ((module) => { -exports.extend = Object.assign; +module.exports = [ + 'cat', + 'cd', + 'chmod', + 'cp', + 'dirs', + 'echo', + 'exec', + 'find', + 'grep', + 'head', + 'ln', + 'ls', + 'mkdir', + 'mv', + 'pwd', + 'rm', + 'sed', + 'set', + 'sort', + 'tail', + 'tempdir', + 'test', + 'to', + 'toEnd', + 'touch', + 'uniq', + 'which', +]; -// Check if we're running under electron -var isElectron = Boolean(process.versions.electron); -// Module globals (assume no execPath by default) -var DEFAULT_CONFIG = { - fatal: false, - globOptions: {}, - maxdepth: 255, - noglob: false, - silent: false, - verbose: false, - execPath: null, - bufLength: 64 * 1024, // 64KB -}; +/***/ }), -var config = { - reset: function () { - Object.assign(this, DEFAULT_CONFIG); - if (!isElectron) { - this.execPath = process.execPath; - } - }, - resetForTesting: function () { - this.reset(); - this.silent = true; - }, -}; +/***/ 3516: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -config.reset(); -exports.config = config; +// +// ShellJS +// Unix shell commands on top of Node's API +// +// Copyright (c) 2012 Artur Adib +// http://github.com/shelljs/shelljs +// -// Note: commands should generally consider these as read-only values. -var state = { - error: null, - errorCode: 0, - currentCmd: 'shell.js', -}; -exports.state = state; +function __ncc_wildcard$0 (arg) { + if (arg === "cat.js" || arg === "cat") return __nccwpck_require__(271); + else if (arg === "cd.js" || arg === "cd") return __nccwpck_require__(2051); + else if (arg === "chmod.js" || arg === "chmod") return __nccwpck_require__(4975); + else if (arg === "common.js" || arg === "common") return __nccwpck_require__(3687); + else if (arg === "cp.js" || arg === "cp") return __nccwpck_require__(4932); + else if (arg === "dirs.js" || arg === "dirs") return __nccwpck_require__(1178); + else if (arg === "echo.js" || arg === "echo") return __nccwpck_require__(243); + else if (arg === "error.js" || arg === "error") return __nccwpck_require__(232); + else if (arg === "exec-child.js" || arg === "exec-child") return __nccwpck_require__(9607); + else if (arg === "exec.js" || arg === "exec") return __nccwpck_require__(896); + else if (arg === "find.js" || arg === "find") return __nccwpck_require__(7838); + else if (arg === "grep.js" || arg === "grep") return __nccwpck_require__(7417); + else if (arg === "head.js" || arg === "head") return __nccwpck_require__(6613); + else if (arg === "ln.js" || arg === "ln") return __nccwpck_require__(5787); + else if (arg === "ls.js" || arg === "ls") return __nccwpck_require__(5561); + else if (arg === "mkdir.js" || arg === "mkdir") return __nccwpck_require__(2695); + else if (arg === "mv.js" || arg === "mv") return __nccwpck_require__(9849); + else if (arg === "popd.js" || arg === "popd") return __nccwpck_require__(227); + else if (arg === "pushd.js" || arg === "pushd") return __nccwpck_require__(4177); + else if (arg === "pwd.js" || arg === "pwd") return __nccwpck_require__(8553); + else if (arg === "rm.js" || arg === "rm") return __nccwpck_require__(2830); + else if (arg === "sed.js" || arg === "sed") return __nccwpck_require__(5899); + else if (arg === "set.js" || arg === "set") return __nccwpck_require__(1411); + else if (arg === "sort.js" || arg === "sort") return __nccwpck_require__(2116); + else if (arg === "tail.js" || arg === "tail") return __nccwpck_require__(2284); + else if (arg === "tempdir.js" || arg === "tempdir") return __nccwpck_require__(6150); + else if (arg === "test.js" || arg === "test") return __nccwpck_require__(9723); + else if (arg === "to.js" || arg === "to") return __nccwpck_require__(1961); + else if (arg === "toEnd.js" || arg === "toEnd") return __nccwpck_require__(3736); + else if (arg === "touch.js" || arg === "touch") return __nccwpck_require__(8358); + else if (arg === "uniq.js" || arg === "uniq") return __nccwpck_require__(7286); + else if (arg === "which.js" || arg === "which") return __nccwpck_require__(6478); +} +var common = __nccwpck_require__(3687); -delete process.env.OLDPWD; // initially, there's no previous directory +//@ +//@ All commands run synchronously, unless otherwise stated. +//@ All commands accept standard bash globbing characters (`*`, `?`, etc.), +//@ compatible with the [node `glob` module](https://github.com/isaacs/node-glob). +//@ +//@ For less-commonly used commands and features, please check out our [wiki +//@ page](https://github.com/shelljs/shelljs/wiki). +//@ -// Reliably test if something is any sort of javascript object -function isObject(a) { - return typeof a === 'object' && a !== null; -} -exports.isObject = isObject; +// Include the docs for all the default commands +//@commands -function log() { - /* istanbul ignore next */ - if (!config.silent) { - console.error.apply(console, arguments); - } -} -exports.log = log; +// Load all default commands +(__nccwpck_require__(5123).forEach)(function (command) { + __ncc_wildcard$0(command); +}); -// Converts strings to be equivalent across all platforms. Primarily responsible -// for making sure we use '/' instead of '\' as path separators, but this may be -// expanded in the future if necessary -function convertErrorOutput(msg) { - if (typeof msg !== 'string') { - throw new TypeError('input must be a string'); - } - return msg.replace(/\\/g, '/'); -} -exports.convertErrorOutput = convertErrorOutput; +//@ +//@ ### exit(code) +//@ +//@ Exits the current process with the given exit `code`. +exports.exit = process.exit; -// Shows error message. Throws if config.fatal is true -function error(msg, _code, options) { - // Validate input - if (typeof msg !== 'string') throw new Error('msg must be a string'); +//@include ./src/error +exports.error = __nccwpck_require__(232); - var DEFAULT_OPTIONS = { - continue: false, - code: 1, - prefix: state.currentCmd + ': ', - silent: false, - }; +//@include ./src/common +exports.ShellString = common.ShellString; - if (typeof _code === 'number' && isObject(options)) { - options.code = _code; - } else if (isObject(_code)) { // no 'code' - options = _code; - } else if (typeof _code === 'number') { // no 'options' - options = { code: _code }; - } else if (typeof _code !== 'number') { // only 'msg' - options = {}; - } - options = Object.assign({}, DEFAULT_OPTIONS, options); +//@ +//@ ### env['VAR_NAME'] +//@ +//@ Object containing environment variables (both getter and setter). Shortcut +//@ to `process.env`. +exports.env = process.env; - if (!state.errorCode) state.errorCode = options.code; +//@ +//@ ### Pipes +//@ +//@ Examples: +//@ +//@ ```javascript +//@ grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); +//@ echo('files with o\'s in the name:\n' + ls().grep('o')); +//@ cat('test.js').exec('node'); // pipe to exec() call +//@ ``` +//@ +//@ Commands can send their output to another command in a pipe-like fashion. +//@ `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand +//@ side of a pipe. Pipes can be chained. - var logEntry = convertErrorOutput(options.prefix + msg); - state.error = state.error ? state.error + '\n' : ''; - state.error += logEntry; +//@ +//@ ## Configuration +//@ - // Throw an error, or log the entry - if (config.fatal) throw new Error(logEntry); - if (msg.length > 0 && !options.silent) log(logEntry); +exports.config = common.config; - if (!options.continue) { - throw { - msg: 'earlyExit', - retValue: (new ShellString('', state.error, state.errorCode)), - }; - } -} -exports.error = error; +//@ +//@ ### config.silent +//@ +//@ Example: +//@ +//@ ```javascript +//@ var sh = require('shelljs'); +//@ var silentState = sh.config.silent; // save old silent state +//@ sh.config.silent = true; +//@ /* ... */ +//@ sh.config.silent = silentState; // restore old silent state +//@ ``` +//@ +//@ Suppresses all command output if `true`, except for `echo()` calls. +//@ Default is `false`. //@ -//@ ### ShellString(str) +//@ ### config.fatal //@ -//@ Examples: +//@ Example: //@ //@ ```javascript -//@ var foo = ShellString('hello world'); +//@ require('shelljs/global'); +//@ config.fatal = true; // or set('-e'); +//@ cp('this_file_does_not_exist', '/dev/null'); // throws Error here +//@ /* more commands... */ //@ ``` //@ -//@ Turns a regular string into a string-like object similar to what each -//@ command returns. This has special methods, like `.to()` and `.toEnd()`. -function ShellString(stdout, stderr, code) { - var that; - if (stdout instanceof Array) { - that = stdout; - that.stdout = stdout.join('\n'); - if (stdout.length > 0) that.stdout += '\n'; - } else { - that = new String(stdout); - that.stdout = stdout; - } - that.stderr = stderr; - that.code = code; - // A list of all commands that can appear on the right-hand side of a pipe - // (populated by calls to common.wrap()) - pipeMethods.forEach(function (cmd) { - that[cmd] = shellMethods[cmd].bind(that); - }); - return that; -} +//@ If `true`, the script will throw a Javascript error when any shell.js +//@ command encounters an error. Default is `false`. This is analogous to +//@ Bash's `set -e`. -exports.ShellString = ShellString; +//@ +//@ ### config.verbose +//@ +//@ Example: +//@ +//@ ```javascript +//@ config.verbose = true; // or set('-v'); +//@ cd('dir/'); +//@ rm('-rf', 'foo.txt', 'bar.txt'); +//@ exec('echo hello'); +//@ ``` +//@ +//@ Will print each command as follows: +//@ +//@ ``` +//@ cd dir/ +//@ rm -rf foo.txt bar.txt +//@ exec echo hello +//@ ``` -// Returns {'alice': true, 'bob': false} when passed a string and dictionary as follows: -// parseOptions('-a', {'a':'alice', 'b':'bob'}); -// Returns {'reference': 'string-value', 'bob': false} when passed two dictionaries of the form: -// parseOptions({'-r': 'string-value'}, {'r':'reference', 'b':'bob'}); -// Throws an error when passed a string that does not start with '-': -// parseOptions('a', {'a':'alice'}); // throws -function parseOptions(opt, map, errorOptions) { - // Validate input - if (typeof opt !== 'string' && !isObject(opt)) { - throw new Error('options must be strings or key-value pairs'); - } else if (!isObject(map)) { - throw new Error('parseOptions() internal error: map must be an object'); - } else if (errorOptions && !isObject(errorOptions)) { - throw new Error('parseOptions() internal error: errorOptions must be object'); - } +//@ +//@ ### config.globOptions +//@ +//@ Example: +//@ +//@ ```javascript +//@ config.globOptions = {nodir: true}; +//@ ``` +//@ +//@ Use this value for calls to `glob.sync()` instead of the default options. - if (opt === '--') { - // This means there are no options. - return {}; - } +//@ +//@ ### config.reset() +//@ +//@ Example: +//@ +//@ ```javascript +//@ var shell = require('shelljs'); +//@ // Make changes to shell.config, and do stuff... +//@ /* ... */ +//@ shell.config.reset(); // reset to original state +//@ // Do more stuff, but with original settings +//@ /* ... */ +//@ ``` +//@ +//@ Reset `shell.config` to the defaults: +//@ +//@ ```javascript +//@ { +//@ fatal: false, +//@ globOptions: {}, +//@ maxdepth: 255, +//@ noglob: false, +//@ silent: false, +//@ verbose: false, +//@ } +//@ ``` - // All options are false by default - var options = {}; - Object.keys(map).forEach(function (letter) { - var optName = map[letter]; - if (optName[0] !== '!') { - options[optName] = false; - } - }); - if (opt === '') return options; // defaults +/***/ }), - if (typeof opt === 'string') { - if (opt[0] !== '-') { - throw new Error("Options string must start with a '-'"); - } +/***/ 271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // e.g. chars = ['R', 'f'] - var chars = opt.slice(1).split(''); +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); - chars.forEach(function (c) { - if (c in map) { - var optionName = map[c]; - if (optionName[0] === '!') { - options[optionName.slice(1)] = false; - } else { - options[optionName] = true; - } - } else { - error('option not recognized: ' + c, errorOptions || {}); - } - }); - } else { // opt is an Object - Object.keys(opt).forEach(function (key) { - // key is a string of the form '-r', '-d', etc. - var c = key[1]; - if (c in map) { - var optionName = map[c]; - options[optionName] = opt[key]; // assign the given value - } else { - error('option not recognized: ' + c, errorOptions || {}); - } - }); - } - return options; -} -exports.parseOptions = parseOptions; +common.register('cat', _cat, { + canReceivePipe: true, + cmdOptions: { + 'n': 'number', + }, +}); -// Expands wildcards with matching (ie. existing) file names. -// For example: -// expand(['file*.js']) = ['file1.js', 'file2.js', ...] -// (if the files 'file1.js', 'file2.js', etc, exist in the current dir) -function expand(list) { - if (!Array.isArray(list)) { - throw new TypeError('must be an array'); - } - var expanded = []; - list.forEach(function (listEl) { - // Don't expand non-strings - if (typeof listEl !== 'string') { - expanded.push(listEl); - } else { - var ret; - try { - ret = glob.sync(listEl, config.globOptions); - // if nothing matched, interpret the string literally - ret = ret.length > 0 ? ret : [listEl]; - } catch (e) { - // if glob fails, interpret the string literally - ret = [listEl]; - } - expanded = expanded.concat(ret); - } - }); - return expanded; -} -exports.expand = expand; +//@ +//@ ### cat([options,] file [, file ...]) +//@ ### cat([options,] file_array) +//@ +//@ Available options: +//@ +//@ + `-n`: number all output lines +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = cat('file*.txt'); +//@ var str = cat('file1', 'file2'); +//@ var str = cat(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Returns a string containing the given file, or a concatenated string +//@ containing the files if more than one file is given (a new line character is +//@ introduced between each file). +function _cat(options, files) { + var cat = common.readFromPipe(); -// Normalizes Buffer creation, using Buffer.alloc if possible. -// Also provides a good default buffer length for most use cases. -var buffer = typeof Buffer.alloc === 'function' ? - function (len) { - return Buffer.alloc(len || config.bufLength); - } : - function (len) { - return new Buffer(len || config.bufLength); - }; -exports.buffer = buffer; + if (!files && !cat) common.error('no paths given'); -// Normalizes _unlinkSync() across platforms to match Unix behavior, i.e. -// file can be unlinked even if it's read-only, see https://github.com/joyent/node/issues/3006 -function unlinkSync(file) { - try { - fs.unlinkSync(file); - } catch (e) { - // Try to override file permission - /* istanbul ignore next */ - if (e.code === 'EPERM') { - fs.chmodSync(file, '0666'); - fs.unlinkSync(file); - } else { - throw e; - } - } -} -exports.unlinkSync = unlinkSync; + files = [].slice.call(arguments, 1); -// wrappers around common.statFollowLinks and common.statNoFollowLinks that clarify intent -// and improve readability -function statFollowLinks() { - return fs.statSync.apply(fs, arguments); -} -exports.statFollowLinks = statFollowLinks; + files.forEach(function (file) { + if (!fs.existsSync(file)) { + common.error('no such file or directory: ' + file); + } else if (common.statFollowLinks(file).isDirectory()) { + common.error(file + ': Is a directory'); + } -function statNoFollowLinks() { - return fs.lstatSync.apply(fs, arguments); -} -exports.statNoFollowLinks = statNoFollowLinks; + cat += fs.readFileSync(file, 'utf8'); + }); -// e.g. 'shelljs_a5f185d0443ca...' -function randomFileName() { - function randomHash(count) { - if (count === 1) { - return parseInt(16 * Math.random(), 10).toString(16); - } - var hash = ''; - for (var i = 0; i < count; i++) { - hash += randomHash(1); - } - return hash; + if (options.number) { + cat = addNumbers(cat); } - return 'shelljs_' + randomHash(20); + return cat; } -exports.randomFileName = randomFileName; +module.exports = _cat; -// Common wrapper for all Unix-like commands that performs glob expansion, -// command-logging, and other nice things -function wrap(cmd, fn, options) { - options = options || {}; - return function () { - var retValue = null; +function addNumbers(cat) { + var lines = cat.split('\n'); + var lastLine = lines.pop(); - state.currentCmd = cmd; - state.error = null; - state.errorCode = 0; + lines = lines.map(function (line, i) { + return numberedLine(i + 1, line); + }); - try { - var args = [].slice.call(arguments, 0); + if (lastLine.length) { + lastLine = numberedLine(lines.length + 1, lastLine); + } + lines.push(lastLine); - // Log the command to stderr, if appropriate - if (config.verbose) { - console.error.apply(console, [cmd].concat(args)); - } + return lines.join('\n'); +} - // If this is coming from a pipe, let's set the pipedValue (otherwise, set - // it to the empty string) - state.pipedValue = (this && typeof this.stdout === 'string') ? this.stdout : ''; +function numberedLine(n, line) { + // GNU cat use six pad start number + tab. See http://lingrok.org/xref/coreutils/src/cat.c#57 + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart + var number = (' ' + n).slice(-6) + '\t'; + return number + line; +} - if (options.unix === false) { // this branch is for exec() - retValue = fn.apply(this, args); - } else { // and this branch is for everything else - if (isObject(args[0]) && args[0].constructor.name === 'Object') { - // a no-op, allowing the syntax `touch({'-r': file}, ...)` - } else if (args.length === 0 || typeof args[0] !== 'string' || args[0].length <= 1 || args[0][0] !== '-') { - args.unshift(''); // only add dummy option if '-option' not already present - } - // flatten out arrays that are arguments, to make the syntax: - // `cp([file1, file2, file3], dest);` - // equivalent to: - // `cp(file1, file2, file3, dest);` - args = args.reduce(function (accum, cur) { - if (Array.isArray(cur)) { - return accum.concat(cur); - } - accum.push(cur); - return accum; - }, []); +/***/ }), - // Convert ShellStrings (basically just String objects) to regular strings - args = args.map(function (arg) { - if (isObject(arg) && arg.constructor.name === 'String') { - return arg.toString(); - } - return arg; - }); +/***/ 2051: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Expand the '~' if appropriate - var homeDir = os.homedir(); - args = args.map(function (arg) { - if (typeof arg === 'string' && arg.slice(0, 2) === '~/' || arg === '~') { - return arg.replace(/^~/, homeDir); - } - return arg; - }); +var os = __nccwpck_require__(2037); +var common = __nccwpck_require__(3687); - // Perform glob-expansion on all arguments after globStart, but preserve - // the arguments before it (like regexes for sed and grep) - if (!config.noglob && options.allowGlobbing === true) { - args = args.slice(0, options.globStart).concat(expand(args.slice(options.globStart))); - } +common.register('cd', _cd, {}); - try { - // parse options if options are provided - if (isObject(options.cmdOptions)) { - args[0] = parseOptions(args[0], options.cmdOptions); - } +//@ +//@ ### cd([dir]) +//@ +//@ Changes to directory `dir` for the duration of the script. Changes to home +//@ directory if no argument is supplied. +function _cd(options, dir) { + if (!dir) dir = os.homedir(); - retValue = fn.apply(this, args); - } catch (e) { - /* istanbul ignore else */ - if (e.msg === 'earlyExit') { - retValue = e.retValue; - } else { - throw e; // this is probably a bug that should be thrown up the call stack - } - } - } - } catch (e) { - /* istanbul ignore next */ - if (!state.error) { - // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... - e.name = 'ShellJSInternalError'; - throw e; - } - if (config.fatal) throw e; + if (dir === '-') { + if (!process.env.OLDPWD) { + common.error('could not find previous directory'); + } else { + dir = process.env.OLDPWD; } + } - if (options.wrapOutput && - (typeof retValue === 'string' || Array.isArray(retValue))) { - retValue = new ShellString(retValue, state.error, state.errorCode); + try { + var curDir = process.cwd(); + process.chdir(dir); + process.env.OLDPWD = curDir; + } catch (e) { + // something went wrong, let's figure out the error + var err; + try { + common.statFollowLinks(dir); // if this succeeds, it must be some sort of file + err = 'not a directory: ' + dir; + } catch (e2) { + err = 'no such file or directory: ' + dir; } + if (err) common.error(err); + } + return ''; +} +module.exports = _cd; - state.currentCmd = 'shell.js'; - return retValue; - }; -} // wrap -exports.wrap = wrap; -// This returns all the input that is piped into the current command (or the -// empty string, if this isn't on the right-hand side of a pipe -function _readFromPipe() { - return state.pipedValue; -} -exports.readFromPipe = _readFromPipe; +/***/ }), -var DEFAULT_WRAP_OPTIONS = { - allowGlobbing: true, - canReceivePipe: false, - cmdOptions: null, - globStart: 1, - pipeOnly: false, - wrapOutput: true, - unix: true, -}; +/***/ 4975: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// This is populated during plugin registration -var pipeMethods = []; +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); -// Register a new ShellJS command -function _register(name, implementation, wrapOptions) { - wrapOptions = wrapOptions || {}; +var PERMS = (function (base) { + return { + OTHER_EXEC: base.EXEC, + OTHER_WRITE: base.WRITE, + OTHER_READ: base.READ, - // Validate options - Object.keys(wrapOptions).forEach(function (option) { - if (!DEFAULT_WRAP_OPTIONS.hasOwnProperty(option)) { - throw new Error("Unknown option '" + option + "'"); - } - if (typeof wrapOptions[option] !== typeof DEFAULT_WRAP_OPTIONS[option]) { - throw new TypeError("Unsupported type '" + typeof wrapOptions[option] + - "' for option '" + option + "'"); - } - }); + GROUP_EXEC: base.EXEC << 3, + GROUP_WRITE: base.WRITE << 3, + GROUP_READ: base.READ << 3, - // If an option isn't specified, use the default - wrapOptions = Object.assign({}, DEFAULT_WRAP_OPTIONS, wrapOptions); + OWNER_EXEC: base.EXEC << 6, + OWNER_WRITE: base.WRITE << 6, + OWNER_READ: base.READ << 6, - if (shell.hasOwnProperty(name)) { - throw new Error('Command `' + name + '` already exists'); - } + // Literal octal numbers are apparently not allowed in "strict" javascript. + STICKY: parseInt('01000', 8), + SETGID: parseInt('02000', 8), + SETUID: parseInt('04000', 8), - if (wrapOptions.pipeOnly) { - wrapOptions.canReceivePipe = true; - shellMethods[name] = wrap(name, implementation, wrapOptions); - } else { - shell[name] = wrap(name, implementation, wrapOptions); - } + TYPE_MASK: parseInt('0770000', 8), + }; +}({ + EXEC: 1, + WRITE: 2, + READ: 4, +})); - if (wrapOptions.canReceivePipe) { - pipeMethods.push(name); +common.register('chmod', _chmod, { +}); + +//@ +//@ ### chmod([options,] octal_mode || octal_string, file) +//@ ### chmod([options,] symbolic_mode, file) +//@ +//@ Available options: +//@ +//@ + `-v`: output a diagnostic for every file processed//@ +//@ + `-c`: like verbose, but report only when a change is made//@ +//@ + `-R`: change files and directories recursively//@ +//@ +//@ Examples: +//@ +//@ ```javascript +//@ chmod(755, '/Users/brandon'); +//@ chmod('755', '/Users/brandon'); // same as above +//@ chmod('u+x', '/Users/brandon'); +//@ chmod('-R', 'a-w', '/Users/brandon'); +//@ ``` +//@ +//@ Alters the permissions of a file or directory by either specifying the +//@ absolute permissions in octal form or expressing the changes in symbols. +//@ This command tries to mimic the POSIX behavior as much as possible. +//@ Notable exceptions: +//@ +//@ + In symbolic modes, `a-r` and `-r` are identical. No consideration is +//@ given to the `umask`. +//@ + There is no "quiet" option, since default behavior is to run silent. +function _chmod(options, mode, filePattern) { + if (!filePattern) { + if (options.length > 0 && options.charAt(0) === '-') { + // Special case where the specified file permissions started with - to subtract perms, which + // get picked up by the option parser as command flags. + // If we are down by one argument and options starts with -, shift everything over. + [].unshift.call(arguments, ''); + } else { + common.error('You must specify a file.'); + } } -} -exports.register = _register; + options = common.parseOptions(options, { + 'R': 'recursive', + 'c': 'changes', + 'v': 'verbose', + }); -/***/ }), + filePattern = [].slice.call(arguments, 2); -/***/ 4932: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + var files; -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); -var common = __webpack_require__(3687); + // TODO: replace this with a call to common.expand() + if (options.recursive) { + files = []; + filePattern.forEach(function addFile(expandedFile) { + var stat = common.statNoFollowLinks(expandedFile); -common.register('cp', _cp, { - cmdOptions: { - 'f': '!no_force', - 'n': 'no_force', - 'u': 'update', - 'R': 'recursive', - 'r': 'recursive', - 'L': 'followsymlink', - 'P': 'noFollowsymlink', - }, - wrapOutput: false, -}); + if (!stat.isSymbolicLink()) { + files.push(expandedFile); -// Buffered file copy, synchronous -// (Using readFileSync() + writeFileSync() could easily cause a memory overflow -// with large files) -function copyFileSync(srcFile, destFile, options) { - if (!fs.existsSync(srcFile)) { - common.error('copyFileSync: no such file or directory: ' + srcFile); + if (stat.isDirectory()) { // intentionally does not follow symlinks. + fs.readdirSync(expandedFile).forEach(function (child) { + addFile(expandedFile + '/' + child); + }); + } + } + }); + } else { + files = filePattern; } - var isWindows = process.platform === 'win32'; - - // Check the mtimes of the files if the '-u' flag is provided - try { - if (options.update && common.statFollowLinks(srcFile).mtime < fs.statSync(destFile).mtime) { - return; + files.forEach(function innerChmod(file) { + file = path.resolve(file); + if (!fs.existsSync(file)) { + common.error('File not found: ' + file); } - } catch (e) { - // If we're here, destFile probably doesn't exist, so just do a normal copy - } - if (common.statNoFollowLinks(srcFile).isSymbolicLink() && !options.followsymlink) { - try { - common.statNoFollowLinks(destFile); - common.unlinkSync(destFile); // re-link it - } catch (e) { - // it doesn't exist, so no work needs to be done + // When recursing, don't follow symlinks. + if (options.recursive && common.statNoFollowLinks(file).isSymbolicLink()) { + return; } - var symlinkFull = fs.readlinkSync(srcFile); - fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); - } else { - var buf = common.buffer(); - var bufLength = buf.length; - var bytesRead = bufLength; - var pos = 0; - var fdr = null; - var fdw = null; + var stat = common.statFollowLinks(file); + var isDir = stat.isDirectory(); + var perms = stat.mode; + var type = perms & PERMS.TYPE_MASK; - try { - fdr = fs.openSync(srcFile, 'r'); - } catch (e) { - /* istanbul ignore next */ - common.error('copyFileSync: could not read src file (' + srcFile + ')'); - } + var newPerms = perms; - try { - fdw = fs.openSync(destFile, 'w'); - } catch (e) { - /* istanbul ignore next */ - common.error('copyFileSync: could not write to dest file (code=' + e.code + '):' + destFile); - } + if (isNaN(parseInt(mode, 8))) { + // parse options + mode.split(',').forEach(function (symbolicMode) { + var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; + var matches = pattern.exec(symbolicMode); - while (bytesRead === bufLength) { - bytesRead = fs.readSync(fdr, buf, 0, bufLength, pos); - fs.writeSync(fdw, buf, 0, bytesRead); - pos += bytesRead; - } + if (matches) { + var applyTo = matches[1]; + var operator = matches[2]; + var change = matches[3]; - fs.closeSync(fdr); - fs.closeSync(fdw); + var changeOwner = applyTo.indexOf('u') !== -1 || applyTo === 'a' || applyTo === ''; + var changeGroup = applyTo.indexOf('g') !== -1 || applyTo === 'a' || applyTo === ''; + var changeOther = applyTo.indexOf('o') !== -1 || applyTo === 'a' || applyTo === ''; - fs.chmodSync(destFile, common.statFollowLinks(srcFile).mode); - } -} + var changeRead = change.indexOf('r') !== -1; + var changeWrite = change.indexOf('w') !== -1; + var changeExec = change.indexOf('x') !== -1; + var changeExecDir = change.indexOf('X') !== -1; + var changeSticky = change.indexOf('t') !== -1; + var changeSetuid = change.indexOf('s') !== -1; -// Recursively copies 'sourceDir' into 'destDir' -// Adapted from https://github.com/ryanmcgrath/wrench-js -// -// Copyright (c) 2010 Ryan McGrath -// Copyright (c) 2012 Artur Adib -// -// Licensed under the MIT License -// http://www.opensource.org/licenses/mit-license.php -function cpdirSyncRecursive(sourceDir, destDir, currentDepth, opts) { - if (!opts) opts = {}; + if (changeExecDir && isDir) { + changeExec = true; + } - // Ensure there is not a run away recursive copy - if (currentDepth >= common.config.maxdepth) return; - currentDepth++; + var mask = 0; + if (changeOwner) { + mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0); + } + if (changeGroup) { + mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0); + } + if (changeOther) { + mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0); + } - var isWindows = process.platform === 'win32'; + // Sticky bit is special - it's not tied to user, group or other. + if (changeSticky) { + mask |= PERMS.STICKY; + } - // Create the directory where all our junk is moving to; read the mode of the - // source directory and mirror it - try { - fs.mkdirSync(destDir); - } catch (e) { - // if the directory already exists, that's okay - if (e.code !== 'EEXIST') throw e; - } + switch (operator) { + case '+': + newPerms |= mask; + break; - var files = fs.readdirSync(sourceDir); + case '-': + newPerms &= ~mask; + break; - for (var i = 0; i < files.length; i++) { - var srcFile = sourceDir + '/' + files[i]; - var destFile = destDir + '/' + files[i]; - var srcFileStat = common.statNoFollowLinks(srcFile); + case '=': + newPerms = type + mask; - var symlinkFull; - if (opts.followsymlink) { - if (cpcheckcycle(sourceDir, srcFile)) { - // Cycle link found. - console.error('Cycle link found.'); - symlinkFull = fs.readlinkSync(srcFile); - fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); - continue; - } - } - if (srcFileStat.isDirectory()) { - /* recursion this thing right on back. */ - cpdirSyncRecursive(srcFile, destFile, currentDepth, opts); - } else if (srcFileStat.isSymbolicLink() && !opts.followsymlink) { - symlinkFull = fs.readlinkSync(srcFile); - try { - common.statNoFollowLinks(destFile); - common.unlinkSync(destFile); // re-link it - } catch (e) { - // it doesn't exist, so no work needs to be done - } - fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); - } else if (srcFileStat.isSymbolicLink() && opts.followsymlink) { - srcFileStat = common.statFollowLinks(srcFile); - if (srcFileStat.isDirectory()) { - cpdirSyncRecursive(srcFile, destFile, currentDepth, opts); - } else { - copyFileSync(srcFile, destFile, opts); - } - } else { - /* At this point, we've hit a file actually worth copying... so copy it on over. */ - if (fs.existsSync(destFile) && opts.no_force) { - common.log('skipping existing file: ' + files[i]); - } else { - copyFileSync(srcFile, destFile, opts); - } - } - } // for files + // According to POSIX, when using = to explicitly set the + // permissions, setuid and setgid can never be cleared. + if (common.statFollowLinks(file).isDirectory()) { + newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; + } + break; + default: + common.error('Could not recognize operator: `' + operator + '`'); + } - // finally change the mode for the newly created directory (otherwise, we - // couldn't add files to a read-only directory). - var checkDir = common.statFollowLinks(sourceDir); - fs.chmodSync(destDir, checkDir.mode); -} // cpdirSyncRecursive + if (options.verbose) { + console.log(file + ' -> ' + newPerms.toString(8)); + } -// Checks if cureent file was created recently -function checkRecentCreated(sources, index) { - var lookedSource = sources[index]; - return sources.slice(0, index).some(function (src) { - return path.basename(src) === path.basename(lookedSource); - }); -} + if (perms !== newPerms) { + if (!options.verbose && options.changes) { + console.log(file + ' -> ' + newPerms.toString(8)); + } + fs.chmodSync(file, newPerms); + perms = newPerms; // for the next round of changes! + } + } else { + common.error('Invalid symbolic mode change: ' + symbolicMode); + } + }); + } else { + // they gave us a full number + newPerms = type + parseInt(mode, 8); -function cpcheckcycle(sourceDir, srcFile) { - var srcFileStat = common.statNoFollowLinks(srcFile); - if (srcFileStat.isSymbolicLink()) { - // Do cycle check. For example: - // $ mkdir -p 1/2/3/4 - // $ cd 1/2/3/4 - // $ ln -s ../../3 link - // $ cd ../../../.. - // $ cp -RL 1 copy - var cyclecheck = common.statFollowLinks(srcFile); - if (cyclecheck.isDirectory()) { - var sourcerealpath = fs.realpathSync(sourceDir); - var symlinkrealpath = fs.realpathSync(srcFile); - var re = new RegExp(symlinkrealpath); - if (re.test(sourcerealpath)) { - return true; + // POSIX rules are that setuid and setgid can only be added using numeric + // form, but not cleared. + if (common.statFollowLinks(file).isDirectory()) { + newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; } + + fs.chmodSync(file, newPerms); } - } - return false; + }); + return ''; } +module.exports = _chmod; -//@ -//@ ### cp([options,] source [, source ...], dest) -//@ ### cp([options,] source_array, dest) -//@ -//@ Available options: -//@ -//@ + `-f`: force (default behavior) -//@ + `-n`: no-clobber -//@ + `-u`: only copy if `source` is newer than `dest` -//@ + `-r`, `-R`: recursive -//@ + `-L`: follow symlinks -//@ + `-P`: don't follow symlinks -//@ -//@ Examples: -//@ -//@ ```javascript -//@ cp('file1', 'dir1'); -//@ cp('-R', 'path/to/dir/', '~/newCopy/'); -//@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); -//@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above -//@ ``` -//@ -//@ Copies files. -function _cp(options, sources, dest) { - // If we're missing -R, it actually implies -L (unless -P is explicit) - if (options.followsymlink) { - options.noFollowsymlink = false; - } - if (!options.recursive && !options.noFollowsymlink) { - options.followsymlink = true; - } - - // Get sources, dest - if (arguments.length < 3) { - common.error('missing and/or '); - } else { - sources = [].slice.call(arguments, 1, arguments.length - 1); - dest = arguments[arguments.length - 1]; - } - var destExists = fs.existsSync(dest); - var destStat = destExists && common.statFollowLinks(dest); +/***/ }), - // Dest is not existing dir, but multiple sources given - if ((!destExists || !destStat.isDirectory()) && sources.length > 1) { - common.error('dest is not a directory (too many sources)'); - } +/***/ 3687: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Dest is an existing file, but -n is given - if (destExists && destStat.isFile() && options.no_force) { - return new common.ShellString('', '', 0); - } +"use strict"; +// Ignore warning about 'new String()' +/* eslint no-new-wrappers: 0 */ - sources.forEach(function (src, srcIndex) { - if (!fs.existsSync(src)) { - if (src === '') src = "''"; // if src was empty string, display empty string - common.error('no such file or directory: ' + src, { continue: true }); - return; // skip file - } - var srcStat = common.statFollowLinks(src); - if (!options.noFollowsymlink && srcStat.isDirectory()) { - if (!options.recursive) { - // Non-Recursive - common.error("omitting directory '" + src + "'", { continue: true }); - } else { - // Recursive - // 'cp /a/source dest' should create 'source' in 'dest' - var newDest = (destStat && destStat.isDirectory()) ? - path.join(dest, path.basename(src)) : - dest; - try { - common.statFollowLinks(path.dirname(dest)); - cpdirSyncRecursive(src, newDest, 0, { no_force: options.no_force, followsymlink: options.followsymlink }); - } catch (e) { - /* istanbul ignore next */ - common.error("cannot create directory '" + dest + "': No such file or directory"); - } - } - } else { - // If here, src is a file +var os = __nccwpck_require__(2037); +var fs = __nccwpck_require__(7147); +var glob = __nccwpck_require__(1957); +var shell = __nccwpck_require__(3516); - // When copying to '/path/dir': - // thisDest = '/path/dir/file1' - var thisDest = dest; - if (destStat && destStat.isDirectory()) { - thisDest = path.normalize(dest + '/' + path.basename(src)); - } +var shellMethods = Object.create(shell); - var thisDestExists = fs.existsSync(thisDest); - if (thisDestExists && checkRecentCreated(sources, srcIndex)) { - // cannot overwrite file created recently in current execution, but we want to continue copying other files - if (!options.no_force) { - common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true }); - } - return; - } +exports.extend = Object.assign; - if (thisDestExists && options.no_force) { - return; // skip file - } +// Check if we're running under electron +var isElectron = Boolean(process.versions.electron); - if (path.relative(src, thisDest) === '') { - // a file cannot be copied to itself, but we want to continue copying other files - common.error("'" + thisDest + "' and '" + src + "' are the same file", { continue: true }); - return; - } +// Module globals (assume no execPath by default) +var DEFAULT_CONFIG = { + fatal: false, + globOptions: {}, + maxdepth: 255, + noglob: false, + silent: false, + verbose: false, + execPath: null, + bufLength: 64 * 1024, // 64KB +}; - copyFileSync(src, thisDest, options); +var config = { + reset: function () { + Object.assign(this, DEFAULT_CONFIG); + if (!isElectron) { + this.execPath = process.execPath; } - }); // forEach(src) + }, + resetForTesting: function () { + this.reset(); + this.silent = true; + }, +}; - return new common.ShellString('', common.state.error, common.state.errorCode); +config.reset(); +exports.config = config; + +// Note: commands should generally consider these as read-only values. +var state = { + error: null, + errorCode: 0, + currentCmd: 'shell.js', +}; +exports.state = state; + +delete process.env.OLDPWD; // initially, there's no previous directory + +// Reliably test if something is any sort of javascript object +function isObject(a) { + return typeof a === 'object' && a !== null; } -module.exports = _cp; +exports.isObject = isObject; + +function log() { + /* istanbul ignore next */ + if (!config.silent) { + console.error.apply(console, arguments); + } +} +exports.log = log; +// Converts strings to be equivalent across all platforms. Primarily responsible +// for making sure we use '/' instead of '\' as path separators, but this may be +// expanded in the future if necessary +function convertErrorOutput(msg) { + if (typeof msg !== 'string') { + throw new TypeError('input must be a string'); + } + return msg.replace(/\\/g, '/'); +} +exports.convertErrorOutput = convertErrorOutput; -/***/ }), +// Shows error message. Throws if config.fatal is true +function error(msg, _code, options) { + // Validate input + if (typeof msg !== 'string') throw new Error('msg must be a string'); -/***/ 1178: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + var DEFAULT_OPTIONS = { + continue: false, + code: 1, + prefix: state.currentCmd + ': ', + silent: false, + }; -var common = __webpack_require__(3687); -var _cd = __webpack_require__(2051); -var path = __webpack_require__(5622); + if (typeof _code === 'number' && isObject(options)) { + options.code = _code; + } else if (isObject(_code)) { // no 'code' + options = _code; + } else if (typeof _code === 'number') { // no 'options' + options = { code: _code }; + } else if (typeof _code !== 'number') { // only 'msg' + options = {}; + } + options = Object.assign({}, DEFAULT_OPTIONS, options); -common.register('dirs', _dirs, { - wrapOutput: false, -}); -common.register('pushd', _pushd, { - wrapOutput: false, -}); -common.register('popd', _popd, { - wrapOutput: false, -}); + if (!state.errorCode) state.errorCode = options.code; -// Pushd/popd/dirs internals -var _dirStack = []; + var logEntry = convertErrorOutput(options.prefix + msg); + state.error = state.error ? state.error + '\n' : ''; + state.error += logEntry; -function _isStackIndex(index) { - return (/^[\-+]\d+$/).test(index); -} + // Throw an error, or log the entry + if (config.fatal) throw new Error(logEntry); + if (msg.length > 0 && !options.silent) log(logEntry); -function _parseStackIndex(index) { - if (_isStackIndex(index)) { - if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd - return (/^-/).test(index) ? Number(index) - 1 : Number(index); - } - common.error(index + ': directory stack index out of range'); - } else { - common.error(index + ': invalid number'); + if (!options.continue) { + throw { + msg: 'earlyExit', + retValue: (new ShellString('', state.error, state.errorCode)), + }; } } +exports.error = error; -function _actualDirStack() { - return [process.cwd()].concat(_dirStack); -} - -//@ -//@ ### pushd([options,] [dir | '-N' | '+N']) -//@ -//@ Available options: -//@ -//@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. -//@ + `-q`: Supresses output to the console. -//@ -//@ Arguments: //@ -//@ + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. -//@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. -//@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. +//@ ### ShellString(str) //@ //@ Examples: //@ //@ ```javascript -//@ // process.cwd() === '/usr' -//@ pushd('/etc'); // Returns /etc /usr -//@ pushd('+1'); // Returns /usr /etc +//@ var foo = ShellString('hello world'); //@ ``` //@ -//@ Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. -function _pushd(options, dir) { - if (_isStackIndex(options)) { - dir = options; - options = ''; +//@ Turns a regular string into a string-like object similar to what each +//@ command returns. This has special methods, like `.to()` and `.toEnd()`. +function ShellString(stdout, stderr, code) { + var that; + if (stdout instanceof Array) { + that = stdout; + that.stdout = stdout.join('\n'); + if (stdout.length > 0) that.stdout += '\n'; + } else { + that = new String(stdout); + that.stdout = stdout; } - - options = common.parseOptions(options, { - 'n': 'no-cd', - 'q': 'quiet', + that.stderr = stderr; + that.code = code; + // A list of all commands that can appear on the right-hand side of a pipe + // (populated by calls to common.wrap()) + pipeMethods.forEach(function (cmd) { + that[cmd] = shellMethods[cmd].bind(that); }); + return that; +} - var dirs = _actualDirStack(); - - if (dir === '+0') { - return dirs; // +0 is a noop - } else if (!dir) { - if (dirs.length > 1) { - dirs = dirs.splice(1, 1).concat(dirs); - } else { - return common.error('no other directory'); - } - } else if (_isStackIndex(dir)) { - var n = _parseStackIndex(dir); - dirs = dirs.slice(n).concat(dirs.slice(0, n)); - } else { - if (options['no-cd']) { - dirs.splice(1, 0, dir); - } else { - dirs.unshift(dir); - } - } +exports.ShellString = ShellString; - if (options['no-cd']) { - dirs = dirs.slice(1); - } else { - dir = path.resolve(dirs.shift()); - _cd('', dir); +// Returns {'alice': true, 'bob': false} when passed a string and dictionary as follows: +// parseOptions('-a', {'a':'alice', 'b':'bob'}); +// Returns {'reference': 'string-value', 'bob': false} when passed two dictionaries of the form: +// parseOptions({'-r': 'string-value'}, {'r':'reference', 'b':'bob'}); +// Throws an error when passed a string that does not start with '-': +// parseOptions('a', {'a':'alice'}); // throws +function parseOptions(opt, map, errorOptions) { + // Validate input + if (typeof opt !== 'string' && !isObject(opt)) { + throw new Error('options must be strings or key-value pairs'); + } else if (!isObject(map)) { + throw new Error('parseOptions() internal error: map must be an object'); + } else if (errorOptions && !isObject(errorOptions)) { + throw new Error('parseOptions() internal error: errorOptions must be object'); } - _dirStack = dirs; - return _dirs(options.quiet ? '-q' : ''); -} -exports.pushd = _pushd; - -//@ -//@ -//@ ### popd([options,] ['-N' | '+N']) -//@ -//@ Available options: -//@ -//@ + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. -//@ + `-q`: Supresses output to the console. -//@ -//@ Arguments: -//@ -//@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. -//@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. -//@ -//@ Examples: -//@ -//@ ```javascript -//@ echo(process.cwd()); // '/usr' -//@ pushd('/etc'); // '/etc /usr' -//@ echo(process.cwd()); // '/etc' -//@ popd(); // '/usr' -//@ echo(process.cwd()); // '/usr' -//@ ``` -//@ -//@ When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. -function _popd(options, index) { - if (_isStackIndex(options)) { - index = options; - options = ''; + if (opt === '--') { + // This means there are no options. + return {}; } - options = common.parseOptions(options, { - 'n': 'no-cd', - 'q': 'quiet', + // All options are false by default + var options = {}; + Object.keys(map).forEach(function (letter) { + var optName = map[letter]; + if (optName[0] !== '!') { + options[optName] = false; + } }); - if (!_dirStack.length) { - return common.error('directory stack empty'); - } + if (opt === '') return options; // defaults - index = _parseStackIndex(index || '+0'); + if (typeof opt === 'string') { + if (opt[0] !== '-') { + throw new Error("Options string must start with a '-'"); + } - if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) { - index = index > 0 ? index - 1 : index; - _dirStack.splice(index, 1); - } else { - var dir = path.resolve(_dirStack.shift()); - _cd('', dir); - } + // e.g. chars = ['R', 'f'] + var chars = opt.slice(1).split(''); - return _dirs(options.quiet ? '-q' : ''); + chars.forEach(function (c) { + if (c in map) { + var optionName = map[c]; + if (optionName[0] === '!') { + options[optionName.slice(1)] = false; + } else { + options[optionName] = true; + } + } else { + error('option not recognized: ' + c, errorOptions || {}); + } + }); + } else { // opt is an Object + Object.keys(opt).forEach(function (key) { + // key is a string of the form '-r', '-d', etc. + var c = key[1]; + if (c in map) { + var optionName = map[c]; + options[optionName] = opt[key]; // assign the given value + } else { + error('option not recognized: ' + c, errorOptions || {}); + } + }); + } + return options; } -exports.popd = _popd; +exports.parseOptions = parseOptions; -//@ -//@ -//@ ### dirs([options | '+N' | '-N']) -//@ -//@ Available options: -//@ -//@ + `-c`: Clears the directory stack by deleting all of the elements. -//@ + `-q`: Supresses output to the console. -//@ -//@ Arguments: -//@ -//@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. -//@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. -//@ -//@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. -//@ -//@ See also: `pushd`, `popd` -function _dirs(options, index) { - if (_isStackIndex(options)) { - index = options; - options = ''; +// Expands wildcards with matching (ie. existing) file names. +// For example: +// expand(['file*.js']) = ['file1.js', 'file2.js', ...] +// (if the files 'file1.js', 'file2.js', etc, exist in the current dir) +function expand(list) { + if (!Array.isArray(list)) { + throw new TypeError('must be an array'); } - - options = common.parseOptions(options, { - 'c': 'clear', - 'q': 'quiet', + var expanded = []; + list.forEach(function (listEl) { + // Don't expand non-strings + if (typeof listEl !== 'string') { + expanded.push(listEl); + } else { + var ret; + try { + ret = glob.sync(listEl, config.globOptions); + // if nothing matched, interpret the string literally + ret = ret.length > 0 ? ret : [listEl]; + } catch (e) { + // if glob fails, interpret the string literally + ret = [listEl]; + } + expanded = expanded.concat(ret); + } }); + return expanded; +} +exports.expand = expand; - if (options.clear) { - _dirStack = []; - return _dirStack; +// Normalizes Buffer creation, using Buffer.alloc if possible. +// Also provides a good default buffer length for most use cases. +var buffer = typeof Buffer.alloc === 'function' ? + function (len) { + return Buffer.alloc(len || config.bufLength); + } : + function (len) { + return new Buffer(len || config.bufLength); + }; +exports.buffer = buffer; + +// Normalizes _unlinkSync() across platforms to match Unix behavior, i.e. +// file can be unlinked even if it's read-only, see https://github.com/joyent/node/issues/3006 +function unlinkSync(file) { + try { + fs.unlinkSync(file); + } catch (e) { + // Try to override file permission + /* istanbul ignore next */ + if (e.code === 'EPERM') { + fs.chmodSync(file, '0666'); + fs.unlinkSync(file); + } else { + throw e; + } } +} +exports.unlinkSync = unlinkSync; - var stack = _actualDirStack(); +// wrappers around common.statFollowLinks and common.statNoFollowLinks that clarify intent +// and improve readability +function statFollowLinks() { + return fs.statSync.apply(fs, arguments); +} +exports.statFollowLinks = statFollowLinks; - if (index) { - index = _parseStackIndex(index); +function statNoFollowLinks() { + return fs.lstatSync.apply(fs, arguments); +} +exports.statNoFollowLinks = statNoFollowLinks; - if (index < 0) { - index = stack.length + index; +// e.g. 'shelljs_a5f185d0443ca...' +function randomFileName() { + function randomHash(count) { + if (count === 1) { + return parseInt(16 * Math.random(), 10).toString(16); } - - if (!options.quiet) { - common.log(stack[index]); + var hash = ''; + for (var i = 0; i < count; i++) { + hash += randomHash(1); } - return stack[index]; - } - - if (!options.quiet) { - common.log(stack.join(' ')); + return hash; } - return stack; + return 'shelljs_' + randomHash(20); } -exports.dirs = _dirs; - - -/***/ }), - -/***/ 243: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var format = __webpack_require__(1669).format; +exports.randomFileName = randomFileName; -var common = __webpack_require__(3687); +// Common wrapper for all Unix-like commands that performs glob expansion, +// command-logging, and other nice things +function wrap(cmd, fn, options) { + options = options || {}; + return function () { + var retValue = null; -common.register('echo', _echo, { - allowGlobbing: false, -}); + state.currentCmd = cmd; + state.error = null; + state.errorCode = 0; -//@ -//@ ### echo([options,] string [, string ...]) -//@ -//@ Available options: -//@ -//@ + `-e`: interpret backslash escapes (default) -//@ + `-n`: remove trailing newline from output -//@ -//@ Examples: -//@ -//@ ```javascript -//@ echo('hello world'); -//@ var str = echo('hello world'); -//@ echo('-n', 'no newline at end'); -//@ ``` -//@ -//@ Prints `string` to stdout, and returns string with additional utility methods -//@ like `.to()`. -function _echo(opts) { - // allow strings starting with '-', see issue #20 - var messages = [].slice.call(arguments, opts ? 0 : 1); - var options = {}; + try { + var args = [].slice.call(arguments, 0); - // If the first argument starts with '-', parse it as options string. - // If parseOptions throws, it wasn't an options string. - try { - options = common.parseOptions(messages[0], { - 'e': 'escapes', - 'n': 'no_newline', - }, { - silent: true, - }); + // Log the command to stderr, if appropriate + if (config.verbose) { + console.error.apply(console, [cmd].concat(args)); + } - // Allow null to be echoed - if (messages[0]) { - messages.shift(); - } - } catch (_) { - // Clear out error if an error occurred - common.state.error = null; - } + // If this is coming from a pipe, let's set the pipedValue (otherwise, set + // it to the empty string) + state.pipedValue = (this && typeof this.stdout === 'string') ? this.stdout : ''; - var output = format.apply(null, messages); + if (options.unix === false) { // this branch is for exec() + retValue = fn.apply(this, args); + } else { // and this branch is for everything else + if (isObject(args[0]) && args[0].constructor.name === 'Object') { + // a no-op, allowing the syntax `touch({'-r': file}, ...)` + } else if (args.length === 0 || typeof args[0] !== 'string' || args[0].length <= 1 || args[0][0] !== '-') { + args.unshift(''); // only add dummy option if '-option' not already present + } - // Add newline if -n is not passed. - if (!options.no_newline) { - output += '\n'; - } + // flatten out arrays that are arguments, to make the syntax: + // `cp([file1, file2, file3], dest);` + // equivalent to: + // `cp(file1, file2, file3, dest);` + args = args.reduce(function (accum, cur) { + if (Array.isArray(cur)) { + return accum.concat(cur); + } + accum.push(cur); + return accum; + }, []); - process.stdout.write(output); + // Convert ShellStrings (basically just String objects) to regular strings + args = args.map(function (arg) { + if (isObject(arg) && arg.constructor.name === 'String') { + return arg.toString(); + } + return arg; + }); - return output; -} + // Expand the '~' if appropriate + var homeDir = os.homedir(); + args = args.map(function (arg) { + if (typeof arg === 'string' && arg.slice(0, 2) === '~/' || arg === '~') { + return arg.replace(/^~/, homeDir); + } + return arg; + }); -module.exports = _echo; + // Perform glob-expansion on all arguments after globStart, but preserve + // the arguments before it (like regexes for sed and grep) + if (!config.noglob && options.allowGlobbing === true) { + args = args.slice(0, options.globStart).concat(expand(args.slice(options.globStart))); + } + try { + // parse options if options are provided + if (isObject(options.cmdOptions)) { + args[0] = parseOptions(args[0], options.cmdOptions); + } -/***/ }), + retValue = fn.apply(this, args); + } catch (e) { + /* istanbul ignore else */ + if (e.msg === 'earlyExit') { + retValue = e.retValue; + } else { + throw e; // this is probably a bug that should be thrown up the call stack + } + } + } + } catch (e) { + /* istanbul ignore next */ + if (!state.error) { + // If state.error hasn't been set it's an error thrown by Node, not us - probably a bug... + e.name = 'ShellJSInternalError'; + throw e; + } + if (config.fatal) throw e; + } -/***/ 232: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + if (options.wrapOutput && + (typeof retValue === 'string' || Array.isArray(retValue))) { + retValue = new ShellString(retValue, state.error, state.errorCode); + } -var common = __webpack_require__(3687); + state.currentCmd = 'shell.js'; + return retValue; + }; +} // wrap +exports.wrap = wrap; -//@ -//@ ### error() -//@ -//@ Tests if error occurred in the last command. Returns a truthy value if an -//@ error returned, or a falsy value otherwise. -//@ -//@ **Note**: do not rely on the -//@ return value to be an error message. If you need the last error message, use -//@ the `.stderr` attribute from the last command's return value instead. -function error() { - return common.state.error; +// This returns all the input that is piped into the current command (or the +// empty string, if this isn't on the right-hand side of a pipe +function _readFromPipe() { + return state.pipedValue; } -module.exports = error; - - -/***/ }), - -/***/ 9607: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +exports.readFromPipe = _readFromPipe; -/* module decorator */ module = __webpack_require__.nmd(module); -if (require.main !== module) { - throw new Error('This file should not be required'); -} +var DEFAULT_WRAP_OPTIONS = { + allowGlobbing: true, + canReceivePipe: false, + cmdOptions: null, + globStart: 1, + pipeOnly: false, + wrapOutput: true, + unix: true, +}; -var childProcess = __webpack_require__(3129); -var fs = __webpack_require__(5747); +// This is populated during plugin registration +var pipeMethods = []; -var paramFilePath = process.argv[2]; +// Register a new ShellJS command +function _register(name, implementation, wrapOptions) { + wrapOptions = wrapOptions || {}; -var serializedParams = fs.readFileSync(paramFilePath, 'utf8'); -var params = JSON.parse(serializedParams); + // Validate options + Object.keys(wrapOptions).forEach(function (option) { + if (!DEFAULT_WRAP_OPTIONS.hasOwnProperty(option)) { + throw new Error("Unknown option '" + option + "'"); + } + if (typeof wrapOptions[option] !== typeof DEFAULT_WRAP_OPTIONS[option]) { + throw new TypeError("Unsupported type '" + typeof wrapOptions[option] + + "' for option '" + option + "'"); + } + }); -var cmd = params.command; -var execOptions = params.execOptions; -var pipe = params.pipe; -var stdoutFile = params.stdoutFile; -var stderrFile = params.stderrFile; + // If an option isn't specified, use the default + wrapOptions = Object.assign({}, DEFAULT_WRAP_OPTIONS, wrapOptions); -var c = childProcess.exec(cmd, execOptions, function (err) { - if (!err) { - process.exitCode = 0; - } else if (err.code === undefined) { - process.exitCode = 1; - } else { - process.exitCode = err.code; + if (shell.hasOwnProperty(name)) { + throw new Error('Command `' + name + '` already exists'); } -}); - -var stdoutStream = fs.createWriteStream(stdoutFile); -var stderrStream = fs.createWriteStream(stderrFile); -c.stdout.pipe(stdoutStream); -c.stderr.pipe(stderrStream); -c.stdout.pipe(process.stdout); -c.stderr.pipe(process.stderr); + if (wrapOptions.pipeOnly) { + wrapOptions.canReceivePipe = true; + shellMethods[name] = wrap(name, implementation, wrapOptions); + } else { + shell[name] = wrap(name, implementation, wrapOptions); + } -if (pipe) { - c.stdin.end(pipe); + if (wrapOptions.canReceivePipe) { + pipeMethods.push(name); + } } +exports.register = _register; /***/ }), -/***/ 896: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var common = __webpack_require__(3687); -var _tempDir = __webpack_require__(6150).tempDir; -var _pwd = __webpack_require__(8553); -var path = __webpack_require__(5622); -var fs = __webpack_require__(5747); -var child = __webpack_require__(3129); +/***/ 4932: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024; -var DEFAULT_ERROR_CODE = 1; +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var common = __nccwpck_require__(3687); -common.register('exec', _exec, { - unix: false, - canReceivePipe: true, +common.register('cp', _cp, { + cmdOptions: { + 'f': '!no_force', + 'n': 'no_force', + 'u': 'update', + 'R': 'recursive', + 'r': 'recursive', + 'L': 'followsymlink', + 'P': 'noFollowsymlink', + }, wrapOutput: false, }); -// We use this function to run `exec` synchronously while also providing realtime -// output. -function execSync(cmd, opts, pipe) { - if (!common.config.execPath) { - common.error('Unable to find a path to the node binary. Please manually set config.execPath'); +// Buffered file copy, synchronous +// (Using readFileSync() + writeFileSync() could easily cause a memory overflow +// with large files) +function copyFileSync(srcFile, destFile, options) { + if (!fs.existsSync(srcFile)) { + common.error('copyFileSync: no such file or directory: ' + srcFile); } - var tempDir = _tempDir(); - var paramsFile = path.resolve(tempDir + '/' + common.randomFileName()); - var stderrFile = path.resolve(tempDir + '/' + common.randomFileName()); - var stdoutFile = path.resolve(tempDir + '/' + common.randomFileName()); + var isWindows = process.platform === 'win32'; - opts = common.extend({ - silent: common.config.silent, - cwd: _pwd().toString(), - env: process.env, - maxBuffer: DEFAULT_MAXBUFFER_SIZE, - encoding: 'utf8', - }, opts); + // Check the mtimes of the files if the '-u' flag is provided + try { + if (options.update && common.statFollowLinks(srcFile).mtime < fs.statSync(destFile).mtime) { + return; + } + } catch (e) { + // If we're here, destFile probably doesn't exist, so just do a normal copy + } - if (fs.existsSync(paramsFile)) common.unlinkSync(paramsFile); - if (fs.existsSync(stderrFile)) common.unlinkSync(stderrFile); - if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile); + if (common.statNoFollowLinks(srcFile).isSymbolicLink() && !options.followsymlink) { + try { + common.statNoFollowLinks(destFile); + common.unlinkSync(destFile); // re-link it + } catch (e) { + // it doesn't exist, so no work needs to be done + } - opts.cwd = path.resolve(opts.cwd); + var symlinkFull = fs.readlinkSync(srcFile); + fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); + } else { + var buf = common.buffer(); + var bufLength = buf.length; + var bytesRead = bufLength; + var pos = 0; + var fdr = null; + var fdw = null; - var paramsToSerialize = { - command: cmd, - execOptions: opts, - pipe: pipe, - stdoutFile: stdoutFile, - stderrFile: stderrFile, - }; + try { + fdr = fs.openSync(srcFile, 'r'); + } catch (e) { + /* istanbul ignore next */ + common.error('copyFileSync: could not read src file (' + srcFile + ')'); + } - fs.writeFileSync(paramsFile, JSON.stringify(paramsToSerialize), 'utf8'); + try { + fdw = fs.openSync(destFile, 'w'); + } catch (e) { + /* istanbul ignore next */ + common.error('copyFileSync: could not write to dest file (code=' + e.code + '):' + destFile); + } - var execArgs = [ - __webpack_require__.ab + "exec-child.js", - paramsFile, - ]; + while (bytesRead === bufLength) { + bytesRead = fs.readSync(fdr, buf, 0, bufLength, pos); + fs.writeSync(fdw, buf, 0, bytesRead); + pos += bytesRead; + } - /* istanbul ignore else */ - if (opts.silent) { - opts.stdio = 'ignore'; - } else { - opts.stdio = [0, 1, 2]; + fs.closeSync(fdr); + fs.closeSync(fdw); + + fs.chmodSync(destFile, common.statFollowLinks(srcFile).mode); } +} - var code = 0; +// Recursively copies 'sourceDir' into 'destDir' +// Adapted from https://github.com/ryanmcgrath/wrench-js +// +// Copyright (c) 2010 Ryan McGrath +// Copyright (c) 2012 Artur Adib +// +// Licensed under the MIT License +// http://www.opensource.org/licenses/mit-license.php +function cpdirSyncRecursive(sourceDir, destDir, currentDepth, opts) { + if (!opts) opts = {}; - // Welcome to the future - try { - // Bad things if we pass in a `shell` option to child_process.execFileSync, - // so we need to explicitly remove it here. - delete opts.shell; + // Ensure there is not a run away recursive copy + if (currentDepth >= common.config.maxdepth) return; + currentDepth++; - child.execFileSync(common.config.execPath, execArgs, opts); - } catch (e) { - // Commands with non-zero exit code raise an exception. - code = e.status || DEFAULT_ERROR_CODE; - } + var isWindows = process.platform === 'win32'; - // fs.readFileSync uses buffer encoding by default, so call - // it without the encoding option if the encoding is 'buffer'. - // Also, if the exec timeout is too short for node to start up, - // the files will not be created, so these calls will throw. - var stdout = ''; - var stderr = ''; - if (opts.encoding === 'buffer') { - stdout = fs.readFileSync(stdoutFile); - stderr = fs.readFileSync(stderrFile); - } else { - stdout = fs.readFileSync(stdoutFile, opts.encoding); - stderr = fs.readFileSync(stderrFile, opts.encoding); + // Create the directory where all our junk is moving to; read the mode of the + // source directory and mirror it + try { + fs.mkdirSync(destDir); + } catch (e) { + // if the directory already exists, that's okay + if (e.code !== 'EEXIST') throw e; } - // No biggie if we can't erase the files now -- they're in a temp dir anyway - try { common.unlinkSync(paramsFile); } catch (e) {} - try { common.unlinkSync(stderrFile); } catch (e) {} - try { common.unlinkSync(stdoutFile); } catch (e) {} - - if (code !== 0) { - // Note: `silent` should be unconditionally true to avoid double-printing - // the command's stderr, and to avoid printing any stderr when the user has - // set `shell.config.silent`. - common.error(stderr, code, { continue: true, silent: true }); - } - var obj = common.ShellString(stdout, stderr, code); - return obj; -} // execSync() + var files = fs.readdirSync(sourceDir); -// Wrapper around exec() to enable echoing output to console in real time -function execAsync(cmd, opts, pipe, callback) { - opts = common.extend({ - silent: common.config.silent, - cwd: _pwd().toString(), - env: process.env, - maxBuffer: DEFAULT_MAXBUFFER_SIZE, - encoding: 'utf8', - }, opts); + for (var i = 0; i < files.length; i++) { + var srcFile = sourceDir + '/' + files[i]; + var destFile = destDir + '/' + files[i]; + var srcFileStat = common.statNoFollowLinks(srcFile); - var c = child.exec(cmd, opts, function (err, stdout, stderr) { - if (callback) { - if (!err) { - callback(0, stdout, stderr); - } else if (err.code === undefined) { - // See issue #536 - /* istanbul ignore next */ - callback(1, stdout, stderr); + var symlinkFull; + if (opts.followsymlink) { + if (cpcheckcycle(sourceDir, srcFile)) { + // Cycle link found. + console.error('Cycle link found.'); + symlinkFull = fs.readlinkSync(srcFile); + fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); + continue; + } + } + if (srcFileStat.isDirectory()) { + /* recursion this thing right on back. */ + cpdirSyncRecursive(srcFile, destFile, currentDepth, opts); + } else if (srcFileStat.isSymbolicLink() && !opts.followsymlink) { + symlinkFull = fs.readlinkSync(srcFile); + try { + common.statNoFollowLinks(destFile); + common.unlinkSync(destFile); // re-link it + } catch (e) { + // it doesn't exist, so no work needs to be done + } + fs.symlinkSync(symlinkFull, destFile, isWindows ? 'junction' : null); + } else if (srcFileStat.isSymbolicLink() && opts.followsymlink) { + srcFileStat = common.statFollowLinks(srcFile); + if (srcFileStat.isDirectory()) { + cpdirSyncRecursive(srcFile, destFile, currentDepth, opts); } else { - callback(err.code, stdout, stderr); + copyFileSync(srcFile, destFile, opts); + } + } else { + /* At this point, we've hit a file actually worth copying... so copy it on over. */ + if (fs.existsSync(destFile) && opts.no_force) { + common.log('skipping existing file: ' + files[i]); + } else { + copyFileSync(srcFile, destFile, opts); } } - }); + } // for files + + // finally change the mode for the newly created directory (otherwise, we + // couldn't add files to a read-only directory). + var checkDir = common.statFollowLinks(sourceDir); + fs.chmodSync(destDir, checkDir.mode); +} // cpdirSyncRecursive - if (pipe) c.stdin.end(pipe); +// Checks if cureent file was created recently +function checkRecentCreated(sources, index) { + var lookedSource = sources[index]; + return sources.slice(0, index).some(function (src) { + return path.basename(src) === path.basename(lookedSource); + }); +} - if (!opts.silent) { - c.stdout.pipe(process.stdout); - c.stderr.pipe(process.stderr); +function cpcheckcycle(sourceDir, srcFile) { + var srcFileStat = common.statNoFollowLinks(srcFile); + if (srcFileStat.isSymbolicLink()) { + // Do cycle check. For example: + // $ mkdir -p 1/2/3/4 + // $ cd 1/2/3/4 + // $ ln -s ../../3 link + // $ cd ../../../.. + // $ cp -RL 1 copy + var cyclecheck = common.statFollowLinks(srcFile); + if (cyclecheck.isDirectory()) { + var sourcerealpath = fs.realpathSync(sourceDir); + var symlinkrealpath = fs.realpathSync(srcFile); + var re = new RegExp(symlinkrealpath); + if (re.test(sourcerealpath)) { + return true; + } + } } - - return c; + return false; } //@ -//@ ### exec(command [, options] [, callback]) +//@ ### cp([options,] source [, source ...], dest) +//@ ### cp([options,] source_array, dest) //@ //@ Available options: //@ -//@ + `async`: Asynchronous execution. If a callback is provided, it will be set to -//@ `true`, regardless of the passed value (default: `false`). -//@ + `silent`: Do not echo program output to console (default: `false`). -//@ + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and -//@ what is written to stdout and stderr when not in silent mode (default: `'utf8'`). -//@ + and any option available to Node.js's -//@ [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) +//@ + `-f`: force (default behavior) +//@ + `-n`: no-clobber +//@ + `-u`: only copy if `source` is newer than `dest` +//@ + `-r`, `-R`: recursive +//@ + `-L`: follow symlinks +//@ + `-P`: don't follow symlinks //@ //@ Examples: //@ //@ ```javascript -//@ var version = exec('node --version', {silent:true}).stdout; -//@ -//@ var child = exec('some_long_running_process', {async:true}); -//@ child.stdout.on('data', function(data) { -//@ /* ... do something with data ... */ -//@ }); -//@ -//@ exec('some_long_running_process', function(code, stdout, stderr) { -//@ console.log('Exit code:', code); -//@ console.log('Program output:', stdout); -//@ console.log('Program stderr:', stderr); -//@ }); +//@ cp('file1', 'dir1'); +//@ cp('-R', 'path/to/dir/', '~/newCopy/'); +//@ cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); +//@ cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above //@ ``` //@ -//@ Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous -//@ mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object -//@ of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process -//@ object, and the `callback` receives the arguments `(code, stdout, stderr)`. -//@ -//@ Not seeing the behavior you want? `exec()` runs everything through `sh` -//@ by default (or `cmd.exe` on Windows), which differs from `bash`. If you -//@ need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. -function _exec(command, options, callback) { - options = options || {}; - if (!command) common.error('must specify command'); - - var pipe = common.readFromPipe(); - - // Callback is defined instead of options. - if (typeof options === 'function') { - callback = options; - options = { async: true }; +//@ Copies files. +function _cp(options, sources, dest) { + // If we're missing -R, it actually implies -L (unless -P is explicit) + if (options.followsymlink) { + options.noFollowsymlink = false; } - - // Callback is defined with options. - if (typeof options === 'object' && typeof callback === 'function') { - options.async = true; + if (!options.recursive && !options.noFollowsymlink) { + options.followsymlink = true; } - options = common.extend({ - silent: common.config.silent, - async: false, - }, options); - - if (options.async) { - return execAsync(command, options, pipe, callback); + // Get sources, dest + if (arguments.length < 3) { + common.error('missing and/or '); } else { - return execSync(command, options, pipe); + sources = [].slice.call(arguments, 1, arguments.length - 1); + dest = arguments[arguments.length - 1]; } -} -module.exports = _exec; - - -/***/ }), - -/***/ 7838: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var path = __webpack_require__(5622); -var common = __webpack_require__(3687); -var _ls = __webpack_require__(5561); -common.register('find', _find, {}); + var destExists = fs.existsSync(dest); + var destStat = destExists && common.statFollowLinks(dest); -//@ -//@ ### find(path [, path ...]) -//@ ### find(path_array) -//@ -//@ Examples: -//@ -//@ ```javascript -//@ find('src', 'lib'); -//@ find(['src', 'lib']); // same as above -//@ find('.').filter(function(file) { return file.match(/\.js$/); }); -//@ ``` -//@ -//@ Returns array of all files (however deep) in the given paths. -//@ -//@ The main difference from `ls('-R', path)` is that the resulting file names -//@ include the base directories (e.g., `lib/resources/file1` instead of just `file1`). -function _find(options, paths) { - if (!paths) { - common.error('no path specified'); - } else if (typeof paths === 'string') { - paths = [].slice.call(arguments, 1); + // Dest is not existing dir, but multiple sources given + if ((!destExists || !destStat.isDirectory()) && sources.length > 1) { + common.error('dest is not a directory (too many sources)'); } - var list = []; + // Dest is an existing file, but -n is given + if (destExists && destStat.isFile() && options.no_force) { + return new common.ShellString('', '', 0); + } - function pushFile(file) { - if (process.platform === 'win32') { - file = file.replace(/\\/g, '/'); + sources.forEach(function (src, srcIndex) { + if (!fs.existsSync(src)) { + if (src === '') src = "''"; // if src was empty string, display empty string + common.error('no such file or directory: ' + src, { continue: true }); + return; // skip file } - list.push(file); - } + var srcStat = common.statFollowLinks(src); + if (!options.noFollowsymlink && srcStat.isDirectory()) { + if (!options.recursive) { + // Non-Recursive + common.error("omitting directory '" + src + "'", { continue: true }); + } else { + // Recursive + // 'cp /a/source dest' should create 'source' in 'dest' + var newDest = (destStat && destStat.isDirectory()) ? + path.join(dest, path.basename(src)) : + dest; - // why not simply do `ls('-R', paths)`? because the output wouldn't give the base dirs - // to get the base dir in the output, we need instead `ls('-R', 'dir/*')` for every directory + try { + common.statFollowLinks(path.dirname(dest)); + cpdirSyncRecursive(src, newDest, 0, { no_force: options.no_force, followsymlink: options.followsymlink }); + } catch (e) { + /* istanbul ignore next */ + common.error("cannot create directory '" + dest + "': No such file or directory"); + } + } + } else { + // If here, src is a file - paths.forEach(function (file) { - var stat; - try { - stat = common.statFollowLinks(file); - } catch (e) { - common.error('no such file or directory: ' + file); - } + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (destStat && destStat.isDirectory()) { + thisDest = path.normalize(dest + '/' + path.basename(src)); + } - pushFile(file); + var thisDestExists = fs.existsSync(thisDest); + if (thisDestExists && checkRecentCreated(sources, srcIndex)) { + // cannot overwrite file created recently in current execution, but we want to continue copying other files + if (!options.no_force) { + common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true }); + } + return; + } - if (stat.isDirectory()) { - _ls({ recursive: true, all: true }, file).forEach(function (subfile) { - pushFile(path.join(file, subfile)); - }); + if (thisDestExists && options.no_force) { + return; // skip file + } + + if (path.relative(src, thisDest) === '') { + // a file cannot be copied to itself, but we want to continue copying other files + common.error("'" + thisDest + "' and '" + src + "' are the same file", { continue: true }); + return; + } + + copyFileSync(src, thisDest, options); } - }); + }); // forEach(src) - return list; + return new common.ShellString('', common.state.error, common.state.errorCode); } -module.exports = _find; +module.exports = _cp; /***/ }), -/***/ 7417: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 1178: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +var common = __nccwpck_require__(3687); +var _cd = __nccwpck_require__(2051); +var path = __nccwpck_require__(1017); -common.register('grep', _grep, { - globStart: 2, // don't glob-expand the regex - canReceivePipe: true, - cmdOptions: { - 'v': 'inverse', - 'l': 'nameOnly', - 'i': 'ignoreCase', - }, +common.register('dirs', _dirs, { + wrapOutput: false, +}); +common.register('pushd', _pushd, { + wrapOutput: false, +}); +common.register('popd', _popd, { + wrapOutput: false, }); +// Pushd/popd/dirs internals +var _dirStack = []; + +function _isStackIndex(index) { + return (/^[\-+]\d+$/).test(index); +} + +function _parseStackIndex(index) { + if (_isStackIndex(index)) { + if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd + return (/^-/).test(index) ? Number(index) - 1 : Number(index); + } + common.error(index + ': directory stack index out of range'); + } else { + common.error(index + ': invalid number'); + } +} + +function _actualDirStack() { + return [process.cwd()].concat(_dirStack); +} + //@ -//@ ### grep([options,] regex_filter, file [, file ...]) -//@ ### grep([options,] regex_filter, file_array) +//@ ### pushd([options,] [dir | '-N' | '+N']) //@ //@ Available options: //@ -//@ + `-v`: Invert `regex_filter` (only print non-matching lines). -//@ + `-l`: Print only filenames of matching files. -//@ + `-i`: Ignore case. +//@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. +//@ + `-q`: Supresses output to the console. +//@ +//@ Arguments: +//@ +//@ + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. +//@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. +//@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. //@ //@ Examples: //@ //@ ```javascript -//@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); -//@ grep('GLOBAL_VARIABLE', '*.js'); +//@ // process.cwd() === '/usr' +//@ pushd('/etc'); // Returns /etc /usr +//@ pushd('+1'); // Returns /usr /etc //@ ``` //@ -//@ Reads input string from given files and returns a string containing all lines of the -//@ file that match the given `regex_filter`. -function _grep(options, regex, files) { - // Check if this is coming from a pipe - var pipe = common.readFromPipe(); - - if (!files && !pipe) common.error('no paths given', 2); +//@ Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. +function _pushd(options, dir) { + if (_isStackIndex(options)) { + dir = options; + options = ''; + } - files = [].slice.call(arguments, 2); + options = common.parseOptions(options, { + 'n': 'no-cd', + 'q': 'quiet', + }); - if (pipe) { - files.unshift('-'); - } + var dirs = _actualDirStack(); - var grep = []; - if (options.ignoreCase) { - regex = new RegExp(regex, 'i'); - } - files.forEach(function (file) { - if (!fs.existsSync(file) && file !== '-') { - common.error('no such file or directory: ' + file, 2, { continue: true }); - return; + if (dir === '+0') { + return dirs; // +0 is a noop + } else if (!dir) { + if (dirs.length > 1) { + dirs = dirs.splice(1, 1).concat(dirs); + } else { + return common.error('no other directory'); } - - var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); - if (options.nameOnly) { - if (contents.match(regex)) { - grep.push(file); - } + } else if (_isStackIndex(dir)) { + var n = _parseStackIndex(dir); + dirs = dirs.slice(n).concat(dirs.slice(0, n)); + } else { + if (options['no-cd']) { + dirs.splice(1, 0, dir); } else { - var lines = contents.split('\n'); - lines.forEach(function (line) { - var matched = line.match(regex); - if ((options.inverse && !matched) || (!options.inverse && matched)) { - grep.push(line); - } - }); + dirs.unshift(dir); } - }); - - return grep.join('\n') + '\n'; -} -module.exports = _grep; + } + if (options['no-cd']) { + dirs = dirs.slice(1); + } else { + dir = path.resolve(dirs.shift()); + _cd('', dir); + } -/***/ }), + _dirStack = dirs; + return _dirs(options.quiet ? '-q' : ''); +} +exports.pushd = _pushd; -/***/ 6613: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +//@ +//@ +//@ ### popd([options,] ['-N' | '+N']) +//@ +//@ Available options: +//@ +//@ + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. +//@ + `-q`: Supresses output to the console. +//@ +//@ Arguments: +//@ +//@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. +//@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ echo(process.cwd()); // '/usr' +//@ pushd('/etc'); // '/etc /usr' +//@ echo(process.cwd()); // '/etc' +//@ popd(); // '/usr' +//@ echo(process.cwd()); // '/usr' +//@ ``` +//@ +//@ When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. +function _popd(options, index) { + if (_isStackIndex(options)) { + index = options; + options = ''; + } -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); + options = common.parseOptions(options, { + 'n': 'no-cd', + 'q': 'quiet', + }); -common.register('head', _head, { - canReceivePipe: true, - cmdOptions: { - 'n': 'numLines', - }, -}); + if (!_dirStack.length) { + return common.error('directory stack empty'); + } -// Reads |numLines| lines or the entire file, whichever is less. -function readSomeLines(file, numLines) { - var buf = common.buffer(); - var bufLength = buf.length; - var bytesRead = bufLength; - var pos = 0; + index = _parseStackIndex(index || '+0'); - var fdr = fs.openSync(file, 'r'); - var numLinesRead = 0; - var ret = ''; - while (bytesRead === bufLength && numLinesRead < numLines) { - bytesRead = fs.readSync(fdr, buf, 0, bufLength, pos); - var bufStr = buf.toString('utf8', 0, bytesRead); - numLinesRead += bufStr.split('\n').length - 1; - ret += bufStr; - pos += bytesRead; + if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) { + index = index > 0 ? index - 1 : index; + _dirStack.splice(index, 1); + } else { + var dir = path.resolve(_dirStack.shift()); + _cd('', dir); } - fs.closeSync(fdr); - return ret; + return _dirs(options.quiet ? '-q' : ''); } +exports.popd = _popd; //@ -//@ ### head([{'-n': \},] file [, file ...]) -//@ ### head([{'-n': \},] file_array) +//@ +//@ ### dirs([options | '+N' | '-N']) //@ //@ Available options: //@ -//@ + `-n `: Show the first `` lines of the files +//@ + `-c`: Clears the directory stack by deleting all of the elements. +//@ + `-q`: Supresses output to the console. //@ -//@ Examples: +//@ Arguments: //@ -//@ ```javascript -//@ var str = head({'-n': 1}, 'file*.txt'); -//@ var str = head('file1', 'file2'); -//@ var str = head(['file1', 'file2']); // same as above -//@ ``` +//@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. +//@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. //@ -//@ Read the start of a file. -function _head(options, files) { - var head = []; - var pipe = common.readFromPipe(); +//@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. +//@ +//@ See also: `pushd`, `popd` +function _dirs(options, index) { + if (_isStackIndex(options)) { + index = options; + options = ''; + } - if (!files && !pipe) common.error('no paths given'); + options = common.parseOptions(options, { + 'c': 'clear', + 'q': 'quiet', + }); - var idx = 1; - if (options.numLines === true) { - idx = 2; - options.numLines = Number(arguments[1]); - } else if (options.numLines === false) { - options.numLines = 10; + if (options.clear) { + _dirStack = []; + return _dirStack; } - files = [].slice.call(arguments, idx); - if (pipe) { - files.unshift('-'); - } + var stack = _actualDirStack(); - var shouldAppendNewline = false; - files.forEach(function (file) { - if (file !== '-') { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, { continue: true }); - return; - } else if (common.statFollowLinks(file).isDirectory()) { - common.error("error reading '" + file + "': Is a directory", { - continue: true, - }); - return; - } - } + if (index) { + index = _parseStackIndex(index); - var contents; - if (file === '-') { - contents = pipe; - } else if (options.numLines < 0) { - contents = fs.readFileSync(file, 'utf8'); - } else { - contents = readSomeLines(file, options.numLines); + if (index < 0) { + index = stack.length + index; } - var lines = contents.split('\n'); - var hasTrailingNewline = (lines[lines.length - 1] === ''); - if (hasTrailingNewline) { - lines.pop(); + if (!options.quiet) { + common.log(stack[index]); } - shouldAppendNewline = (hasTrailingNewline || options.numLines < lines.length); - - head = head.concat(lines.slice(0, options.numLines)); - }); + return stack[index]; + } - if (shouldAppendNewline) { - head.push(''); // to add a trailing newline once we join + if (!options.quiet) { + common.log(stack.join(' ')); } - return head.join('\n'); + + return stack; } -module.exports = _head; +exports.dirs = _dirs; /***/ }), -/***/ 5787: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 243: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); -var common = __webpack_require__(3687); +var format = (__nccwpck_require__(3837).format); -common.register('ln', _ln, { - cmdOptions: { - 's': 'symlink', - 'f': 'force', - }, +var common = __nccwpck_require__(3687); + +common.register('echo', _echo, { + allowGlobbing: false, }); //@ -//@ ### ln([options,] source, dest) +//@ ### echo([options,] string [, string ...]) //@ //@ Available options: //@ -//@ + `-s`: symlink -//@ + `-f`: force +//@ + `-e`: interpret backslash escapes (default) +//@ + `-n`: remove trailing newline from output //@ //@ Examples: //@ //@ ```javascript -//@ ln('file', 'newlink'); -//@ ln('-sf', 'file', 'existing'); +//@ echo('hello world'); +//@ var str = echo('hello world'); +//@ echo('-n', 'no newline at end'); //@ ``` //@ -//@ Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. -function _ln(options, source, dest) { - if (!source || !dest) { - common.error('Missing and/or '); - } +//@ Prints `string` to stdout, and returns string with additional utility methods +//@ like `.to()`. +function _echo(opts) { + // allow strings starting with '-', see issue #20 + var messages = [].slice.call(arguments, opts ? 0 : 1); + var options = {}; - source = String(source); - var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), ''); - var isAbsolute = (path.resolve(source) === sourcePath); - dest = path.resolve(process.cwd(), String(dest)); + // If the first argument starts with '-', parse it as options string. + // If parseOptions throws, it wasn't an options string. + try { + options = common.parseOptions(messages[0], { + 'e': 'escapes', + 'n': 'no_newline', + }, { + silent: true, + }); - if (fs.existsSync(dest)) { - if (!options.force) { - common.error('Destination file exists', { continue: true }); + // Allow null to be echoed + if (messages[0]) { + messages.shift(); } + } catch (_) { + // Clear out error if an error occurred + common.state.error = null; + } - fs.unlinkSync(dest); + var output = format.apply(null, messages); + + // Add newline if -n is not passed. + if (!options.no_newline) { + output += '\n'; } - if (options.symlink) { - var isWindows = process.platform === 'win32'; - var linkType = isWindows ? 'file' : null; - var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source); - if (!fs.existsSync(resolvedSourcePath)) { - common.error('Source file does not exist', { continue: true }); - } else if (isWindows && common.statFollowLinks(resolvedSourcePath).isDirectory()) { - linkType = 'junction'; - } + process.stdout.write(output); - try { - fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType); - } catch (err) { - common.error(err.message); - } + return output; +} + +module.exports = _echo; + + +/***/ }), + +/***/ 232: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var common = __nccwpck_require__(3687); + +//@ +//@ ### error() +//@ +//@ Tests if error occurred in the last command. Returns a truthy value if an +//@ error returned, or a falsy value otherwise. +//@ +//@ **Note**: do not rely on the +//@ return value to be an error message. If you need the last error message, use +//@ the `.stderr` attribute from the last command's return value instead. +function error() { + return common.state.error; +} +module.exports = error; + + +/***/ }), + +/***/ 9607: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* module decorator */ module = __nccwpck_require__.nmd(module); +if (require.main !== module) { + throw new Error('This file should not be required'); +} + +var childProcess = __nccwpck_require__(2081); +var fs = __nccwpck_require__(7147); + +var paramFilePath = process.argv[2]; + +var serializedParams = fs.readFileSync(paramFilePath, 'utf8'); +var params = JSON.parse(serializedParams); + +var cmd = params.command; +var execOptions = params.execOptions; +var pipe = params.pipe; +var stdoutFile = params.stdoutFile; +var stderrFile = params.stderrFile; + +var c = childProcess.exec(cmd, execOptions, function (err) { + if (!err) { + process.exitCode = 0; + } else if (err.code === undefined) { + process.exitCode = 1; } else { - if (!fs.existsSync(source)) { - common.error('Source file does not exist', { continue: true }); - } - try { - fs.linkSync(source, dest); - } catch (err) { - common.error(err.message); - } + process.exitCode = err.code; } - return ''; +}); + +var stdoutStream = fs.createWriteStream(stdoutFile); +var stderrStream = fs.createWriteStream(stderrFile); + +c.stdout.pipe(stdoutStream); +c.stderr.pipe(stderrStream); +c.stdout.pipe(process.stdout); +c.stderr.pipe(process.stderr); + +if (pipe) { + c.stdin.end(pipe); } -module.exports = _ln; /***/ }), -/***/ 5561: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 896: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var path = __webpack_require__(5622); -var fs = __webpack_require__(5747); -var common = __webpack_require__(3687); -var glob = __webpack_require__(1957); +var common = __nccwpck_require__(3687); +var _tempDir = (__nccwpck_require__(6150).tempDir); +var _pwd = __nccwpck_require__(8553); +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); +var child = __nccwpck_require__(2081); -var globPatternRecursive = path.sep + '**'; +var DEFAULT_MAXBUFFER_SIZE = 20 * 1024 * 1024; +var DEFAULT_ERROR_CODE = 1; -common.register('ls', _ls, { - cmdOptions: { - 'R': 'recursive', - 'A': 'all', - 'L': 'link', - 'a': 'all_deprecated', - 'd': 'directory', - 'l': 'long', - }, +common.register('exec', _exec, { + unix: false, + canReceivePipe: true, + wrapOutput: false, }); -//@ -//@ ### ls([options,] [path, ...]) -//@ ### ls([options,] path_array) -//@ -//@ Available options: -//@ -//@ + `-R`: recursive -//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) -//@ + `-L`: follow symlinks -//@ + `-d`: list directories themselves, not their contents -//@ + `-l`: list objects representing each file, each with fields containing `ls -//@ -l` output fields. See -//@ [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) -//@ for more info -//@ -//@ Examples: -//@ -//@ ```javascript -//@ ls('projs/*.js'); -//@ ls('-R', '/users/me', '/tmp'); -//@ ls('-R', ['/users/me', '/tmp']); // same as above -//@ ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} -//@ ``` -//@ -//@ Returns array of files in the given `path`, or files in -//@ the current directory if no `path` is provided. -function _ls(options, paths) { - if (options.all_deprecated) { - // We won't support the -a option as it's hard to image why it's useful - // (it includes '.' and '..' in addition to '.*' files) - // For backwards compatibility we'll dump a deprecated message and proceed as before - common.log('ls: Option -a is deprecated. Use -A instead'); - options.all = true; +// We use this function to run `exec` synchronously while also providing realtime +// output. +function execSync(cmd, opts, pipe) { + if (!common.config.execPath) { + common.error('Unable to find a path to the node binary. Please manually set config.execPath'); + } + + var tempDir = _tempDir(); + var paramsFile = path.resolve(tempDir + '/' + common.randomFileName()); + var stderrFile = path.resolve(tempDir + '/' + common.randomFileName()); + var stdoutFile = path.resolve(tempDir + '/' + common.randomFileName()); + + opts = common.extend({ + silent: common.config.silent, + cwd: _pwd().toString(), + env: process.env, + maxBuffer: DEFAULT_MAXBUFFER_SIZE, + encoding: 'utf8', + }, opts); + + if (fs.existsSync(paramsFile)) common.unlinkSync(paramsFile); + if (fs.existsSync(stderrFile)) common.unlinkSync(stderrFile); + if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile); + + opts.cwd = path.resolve(opts.cwd); + + var paramsToSerialize = { + command: cmd, + execOptions: opts, + pipe: pipe, + stdoutFile: stdoutFile, + stderrFile: stderrFile, + }; + + // Create the files and ensure these are locked down (for read and write) to + // the current user. The main concerns here are: + // + // * If we execute a command which prints sensitive output, then + // stdoutFile/stderrFile must not be readable by other users. + // * paramsFile must not be readable by other users, or else they can read it + // to figure out the path for stdoutFile/stderrFile and create these first + // (locked down to their own access), which will crash exec() when it tries + // to write to the files. + function writeFileLockedDown(filePath, data) { + fs.writeFileSync(filePath, data, { + encoding: 'utf8', + mode: parseInt('600', 8), + }); + } + writeFileLockedDown(stdoutFile, ''); + writeFileLockedDown(stderrFile, ''); + writeFileLockedDown(paramsFile, JSON.stringify(paramsToSerialize)); + + var execArgs = [ + __nccwpck_require__.ab + "exec-child.js", + paramsFile, + ]; + + /* istanbul ignore else */ + if (opts.silent) { + opts.stdio = 'ignore'; + } else { + opts.stdio = [0, 1, 2]; + } + + var code = 0; + + // Welcome to the future + try { + // Bad things if we pass in a `shell` option to child_process.execFileSync, + // so we need to explicitly remove it here. + delete opts.shell; + + child.execFileSync(common.config.execPath, execArgs, opts); + } catch (e) { + // Commands with non-zero exit code raise an exception. + code = e.status || DEFAULT_ERROR_CODE; } - if (!paths) { - paths = ['.']; + // fs.readFileSync uses buffer encoding by default, so call + // it without the encoding option if the encoding is 'buffer'. + // Also, if the exec timeout is too short for node to start up, + // the files will not be created, so these calls will throw. + var stdout = ''; + var stderr = ''; + if (opts.encoding === 'buffer') { + stdout = fs.readFileSync(stdoutFile); + stderr = fs.readFileSync(stderrFile); } else { - paths = [].slice.call(arguments, 1); + stdout = fs.readFileSync(stdoutFile, opts.encoding); + stderr = fs.readFileSync(stderrFile, opts.encoding); } - var list = []; + // No biggie if we can't erase the files now -- they're in a temp dir anyway + // and we locked down permissions (see the note above). + try { common.unlinkSync(paramsFile); } catch (e) {} + try { common.unlinkSync(stderrFile); } catch (e) {} + try { common.unlinkSync(stdoutFile); } catch (e) {} - function pushFile(abs, relName, stat) { - if (process.platform === 'win32') { - relName = relName.replace(/\\/g, '/'); - } - if (options.long) { - stat = stat || (options.link ? common.statFollowLinks(abs) : common.statNoFollowLinks(abs)); - list.push(addLsAttributes(relName, stat)); - } else { - // list.push(path.relative(rel || '.', file)); - list.push(relName); - } + if (code !== 0) { + // Note: `silent` should be unconditionally true to avoid double-printing + // the command's stderr, and to avoid printing any stderr when the user has + // set `shell.config.silent`. + common.error(stderr, code, { continue: true, silent: true }); } + var obj = common.ShellString(stdout, stderr, code); + return obj; +} // execSync() - paths.forEach(function (p) { - var stat; +// Wrapper around exec() to enable echoing output to console in real time +function execAsync(cmd, opts, pipe, callback) { + opts = common.extend({ + silent: common.config.silent, + cwd: _pwd().toString(), + env: process.env, + maxBuffer: DEFAULT_MAXBUFFER_SIZE, + encoding: 'utf8', + }, opts); - try { - stat = options.link ? common.statFollowLinks(p) : common.statNoFollowLinks(p); - // follow links to directories by default - if (stat.isSymbolicLink()) { + var c = child.exec(cmd, opts, function (err, stdout, stderr) { + if (callback) { + if (!err) { + callback(0, stdout, stderr); + } else if (err.code === undefined) { + // See issue #536 /* istanbul ignore next */ - // workaround for https://github.com/shelljs/shelljs/issues/795 - // codecov seems to have a bug that miscalculate this block as uncovered. - // but according to nyc report this block does get covered. - try { - var _stat = common.statFollowLinks(p); - if (_stat.isDirectory()) { - stat = _stat; - } - } catch (_) {} // bad symlink, treat it like a file - } - } catch (e) { - common.error('no such file or directory: ' + p, 2, { continue: true }); - return; - } - - // If the stat succeeded - if (stat.isDirectory() && !options.directory) { - if (options.recursive) { - // use glob, because it's simple - glob.sync(p + globPatternRecursive, { dot: options.all, follow: options.link }) - .forEach(function (item) { - // Glob pattern returns the directory itself and needs to be filtered out. - if (path.relative(p, item)) { - pushFile(item, path.relative(p, item)); - } - }); - } else if (options.all) { - // use fs.readdirSync, because it's fast - fs.readdirSync(p).forEach(function (item) { - pushFile(path.join(p, item), item); - }); + callback(1, stdout, stderr); } else { - // use fs.readdirSync and then filter out secret files - fs.readdirSync(p).forEach(function (item) { - if (item[0] !== '.') { - pushFile(path.join(p, item), item); - } - }); + callback(err.code, stdout, stderr); } - } else { - pushFile(p, p, stat); } }); - // Add methods, to make this more compatible with ShellStrings - return list; -} - -function addLsAttributes(pathName, stats) { - // Note: this object will contain more information than .toString() returns - stats.name = pathName; - stats.toString = function () { - // Return a string resembling unix's `ls -l` format - return [this.mode, this.nlink, this.uid, this.gid, this.size, this.mtime, this.name].join(' '); - }; - return stats; -} - -module.exports = _ls; - - -/***/ }), - -/***/ 2695: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); - -common.register('mkdir', _mkdir, { - cmdOptions: { - 'p': 'fullpath', - }, -}); - -// Recursively creates `dir` -function mkdirSyncRecursive(dir) { - var baseDir = path.dirname(dir); - - // Prevents some potential problems arising from malformed UNCs or - // insufficient permissions. - /* istanbul ignore next */ - if (baseDir === dir) { - common.error('dirname() failed: [' + dir + ']'); - } + if (pipe) c.stdin.end(pipe); - // Base dir exists, no recursion necessary - if (fs.existsSync(baseDir)) { - fs.mkdirSync(dir, parseInt('0777', 8)); - return; + if (!opts.silent) { + c.stdout.pipe(process.stdout); + c.stderr.pipe(process.stderr); } - // Base dir does not exist, go recursive - mkdirSyncRecursive(baseDir); - - // Base dir created, can create dir - fs.mkdirSync(dir, parseInt('0777', 8)); + return c; } //@ -//@ ### mkdir([options,] dir [, dir ...]) -//@ ### mkdir([options,] dir_array) +//@ ### exec(command [, options] [, callback]) //@ //@ Available options: //@ -//@ + `-p`: full path (and create intermediate directories, if necessary) +//@ + `async`: Asynchronous execution. If a callback is provided, it will be set to +//@ `true`, regardless of the passed value (default: `false`). +//@ + `silent`: Do not echo program output to console (default: `false`). +//@ + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and +//@ what is written to stdout and stderr when not in silent mode (default: `'utf8'`). +//@ + and any option available to Node.js's +//@ [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) //@ //@ Examples: //@ //@ ```javascript -//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); -//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above +//@ var version = exec('node --version', {silent:true}).stdout; +//@ +//@ var child = exec('some_long_running_process', {async:true}); +//@ child.stdout.on('data', function(data) { +//@ /* ... do something with data ... */ +//@ }); +//@ +//@ exec('some_long_running_process', function(code, stdout, stderr) { +//@ console.log('Exit code:', code); +//@ console.log('Program output:', stdout); +//@ console.log('Program stderr:', stderr); +//@ }); //@ ``` //@ -//@ Creates directories. -function _mkdir(options, dirs) { - if (!dirs) common.error('no paths given'); - - if (typeof dirs === 'string') { - dirs = [].slice.call(arguments, 1); - } - // if it's array leave it as it is +//@ Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous +//@ mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object +//@ of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process +//@ object, and the `callback` receives the arguments `(code, stdout, stderr)`. +//@ +//@ Not seeing the behavior you want? `exec()` runs everything through `sh` +//@ by default (or `cmd.exe` on Windows), which differs from `bash`. If you +//@ need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. +function _exec(command, options, callback) { + options = options || {}; + if (!command) common.error('must specify command'); - dirs.forEach(function (dir) { - try { - var stat = common.statNoFollowLinks(dir); - if (!options.fullpath) { - common.error('path already exists: ' + dir, { continue: true }); - } else if (stat.isFile()) { - common.error('cannot create directory ' + dir + ': File exists', { continue: true }); - } - return; // skip dir - } catch (e) { - // do nothing - } + var pipe = common.readFromPipe(); - // Base dir does not exist, and no -p option given - var baseDir = path.dirname(dir); - if (!fs.existsSync(baseDir) && !options.fullpath) { - common.error('no such file or directory: ' + baseDir, { continue: true }); - return; // skip dir - } + // Callback is defined instead of options. + if (typeof options === 'function') { + callback = options; + options = { async: true }; + } - try { - if (options.fullpath) { - mkdirSyncRecursive(path.resolve(dir)); - } else { - fs.mkdirSync(dir, parseInt('0777', 8)); - } - } catch (e) { - var reason; - if (e.code === 'EACCES') { - reason = 'Permission denied'; - } else if (e.code === 'ENOTDIR' || e.code === 'ENOENT') { - reason = 'Not a directory'; - } else { - /* istanbul ignore next */ - throw e; - } - common.error('cannot create directory ' + dir + ': ' + reason, { continue: true }); - } - }); - return ''; -} // mkdir -module.exports = _mkdir; + // Callback is defined with options. + if (typeof options === 'object' && typeof callback === 'function') { + options.async = true; + } + options = common.extend({ + silent: common.config.silent, + async: false, + }, options); -/***/ }), + if (options.async) { + return execAsync(command, options, pipe, callback); + } else { + return execSync(command, options, pipe); + } +} +module.exports = _exec; -/***/ 9849: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); -var common = __webpack_require__(3687); -var cp = __webpack_require__(4932); -var rm = __webpack_require__(2830); +/***/ }), -common.register('mv', _mv, { - cmdOptions: { - 'f': '!no_force', - 'n': 'no_force', - }, -}); +/***/ 7838: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Checks if cureent file was created recently -function checkRecentCreated(sources, index) { - var lookedSource = sources[index]; - return sources.slice(0, index).some(function (src) { - return path.basename(src) === path.basename(lookedSource); - }); -} +var path = __nccwpck_require__(1017); +var common = __nccwpck_require__(3687); +var _ls = __nccwpck_require__(5561); + +common.register('find', _find, {}); //@ -//@ ### mv([options ,] source [, source ...], dest') -//@ ### mv([options ,] source_array, dest') -//@ -//@ Available options: -//@ -//@ + `-f`: force (default behavior) -//@ + `-n`: no-clobber +//@ ### find(path [, path ...]) +//@ ### find(path_array) //@ //@ Examples: //@ //@ ```javascript -//@ mv('-n', 'file', 'dir/'); -//@ mv('file1', 'file2', 'dir/'); -//@ mv(['file1', 'file2'], 'dir/'); // same as above +//@ find('src', 'lib'); +//@ find(['src', 'lib']); // same as above +//@ find('.').filter(function(file) { return file.match(/\.js$/); }); //@ ``` //@ -//@ Moves `source` file(s) to `dest`. -function _mv(options, sources, dest) { - // Get sources, dest - if (arguments.length < 3) { - common.error('missing and/or '); - } else if (arguments.length > 3) { - sources = [].slice.call(arguments, 1, arguments.length - 1); - dest = arguments[arguments.length - 1]; - } else if (typeof sources === 'string') { - sources = [sources]; - } else { - // TODO(nate): figure out if we actually need this line - common.error('invalid arguments'); - } - - var exists = fs.existsSync(dest); - var stats = exists && common.statFollowLinks(dest); - - // Dest is not existing dir, but multiple sources given - if ((!exists || !stats.isDirectory()) && sources.length > 1) { - common.error('dest is not a directory (too many sources)'); - } - - // Dest is an existing file, but no -f given - if (exists && stats.isFile() && options.no_force) { - common.error('dest file already exists: ' + dest); +//@ Returns array of all files (however deep) in the given paths. +//@ +//@ The main difference from `ls('-R', path)` is that the resulting file names +//@ include the base directories (e.g., `lib/resources/file1` instead of just `file1`). +function _find(options, paths) { + if (!paths) { + common.error('no path specified'); + } else if (typeof paths === 'string') { + paths = [].slice.call(arguments, 1); } - sources.forEach(function (src, srcIndex) { - if (!fs.existsSync(src)) { - common.error('no such file or directory: ' + src, { continue: true }); - return; // skip file - } - - // If here, src exists - - // When copying to '/path/dir': - // thisDest = '/path/dir/file1' - var thisDest = dest; - if (fs.existsSync(dest) && common.statFollowLinks(dest).isDirectory()) { - thisDest = path.normalize(dest + '/' + path.basename(src)); - } - - var thisDestExists = fs.existsSync(thisDest); - - if (thisDestExists && checkRecentCreated(sources, srcIndex)) { - // cannot overwrite file created recently in current execution, but we want to continue copying other files - if (!options.no_force) { - common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true }); - } - return; - } + var list = []; - if (fs.existsSync(thisDest) && options.no_force) { - common.error('dest file already exists: ' + thisDest, { continue: true }); - return; // skip file + function pushFile(file) { + if (process.platform === 'win32') { + file = file.replace(/\\/g, '/'); } + list.push(file); + } - if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { - common.error('cannot move to self: ' + src, { continue: true }); - return; // skip file - } + // why not simply do `ls('-R', paths)`? because the output wouldn't give the base dirs + // to get the base dir in the output, we need instead `ls('-R', 'dir/*')` for every directory + paths.forEach(function (file) { + var stat; try { - fs.renameSync(src, thisDest); + stat = common.statFollowLinks(file); } catch (e) { - /* istanbul ignore next */ - if (e.code === 'EXDEV') { - // If we're trying to `mv` to an external partition, we'll actually need - // to perform a copy and then clean up the original file. If either the - // copy or the rm fails with an exception, we should allow this - // exception to pass up to the top level. - cp('-r', src, thisDest); - rm('-rf', src); - } + common.error('no such file or directory: ' + file); } - }); // forEach(src) - return ''; -} // mv -module.exports = _mv; - - -/***/ }), - -/***/ 227: -/***/ (() => { - -// see dirs.js + pushFile(file); -/***/ }), - -/***/ 4177: -/***/ (() => { + if (stat.isDirectory()) { + _ls({ recursive: true, all: true }, file).forEach(function (subfile) { + pushFile(path.join(file, subfile)); + }); + } + }); -// see dirs.js + return list; +} +module.exports = _find; /***/ }), -/***/ 8553: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 7417: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var path = __webpack_require__(5622); -var common = __webpack_require__(3687); +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); -common.register('pwd', _pwd, { - allowGlobbing: false, +common.register('grep', _grep, { + globStart: 2, // don't glob-expand the regex + canReceivePipe: true, + cmdOptions: { + 'v': 'inverse', + 'l': 'nameOnly', + 'i': 'ignoreCase', + }, }); //@ -//@ ### pwd() +//@ ### grep([options,] regex_filter, file [, file ...]) +//@ ### grep([options,] regex_filter, file_array) //@ -//@ Returns the current directory. -function _pwd() { - var pwd = path.resolve(process.cwd()); - return pwd; -} -module.exports = _pwd; - - -/***/ }), - -/***/ 2830: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +//@ Available options: +//@ +//@ + `-v`: Invert `regex_filter` (only print non-matching lines). +//@ + `-l`: Print only filenames of matching files. +//@ + `-i`: Ignore case. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); +//@ grep('GLOBAL_VARIABLE', '*.js'); +//@ ``` +//@ +//@ Reads input string from given files and returns a string containing all lines of the +//@ file that match the given `regex_filter`. +function _grep(options, regex, files) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); -common.register('rm', _rm, { - cmdOptions: { - 'f': 'force', - 'r': 'recursive', - 'R': 'recursive', - }, -}); + if (!files && !pipe) common.error('no paths given', 2); -// Recursively removes 'dir' -// Adapted from https://github.com/ryanmcgrath/wrench-js -// -// Copyright (c) 2010 Ryan McGrath -// Copyright (c) 2012 Artur Adib -// -// Licensed under the MIT License -// http://www.opensource.org/licenses/mit-license.php -function rmdirSyncRecursive(dir, force, fromSymlink) { - var files; + files = [].slice.call(arguments, 2); - files = fs.readdirSync(dir); + if (pipe) { + files.unshift('-'); + } - // Loop through and delete everything in the sub-tree after checking it - for (var i = 0; i < files.length; i++) { - var file = dir + '/' + files[i]; - var currFile = common.statNoFollowLinks(file); + var grep = []; + if (options.ignoreCase) { + regex = new RegExp(regex, 'i'); + } + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, 2, { continue: true }); + return; + } - if (currFile.isDirectory()) { // Recursive function back to the beginning - rmdirSyncRecursive(file, force); - } else { // Assume it's a file - perhaps a try/catch belongs here? - if (force || isWriteable(file)) { - try { - common.unlinkSync(file); - } catch (e) { - /* istanbul ignore next */ - common.error('could not remove file (code ' + e.code + '): ' + file, { - continue: true, - }); - } + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + if (options.nameOnly) { + if (contents.match(regex)) { + grep.push(file); } + } else { + var lines = contents.split('\n'); + lines.forEach(function (line) { + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) { + grep.push(line); + } + }); } - } + }); - // if was directory was referenced through a symbolic link, - // the contents should be removed, but not the directory itself - if (fromSymlink) return; + return grep.join('\n') + '\n'; +} +module.exports = _grep; - // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. - // Huzzah for the shopkeep. - var result; - try { - // Retry on windows, sometimes it takes a little time before all the files in the directory are gone - var start = Date.now(); +/***/ }), - // TODO: replace this with a finite loop - for (;;) { - try { - result = fs.rmdirSync(dir); - if (fs.existsSync(dir)) throw { code: 'EAGAIN' }; - break; - } catch (er) { - /* istanbul ignore next */ - // In addition to error codes, also check if the directory still exists and loop again if true - if (process.platform === 'win32' && (er.code === 'ENOTEMPTY' || er.code === 'EBUSY' || er.code === 'EPERM' || er.code === 'EAGAIN')) { - if (Date.now() - start > 1000) throw er; - } else if (er.code === 'ENOENT') { - // Directory did not exist, deletion was successful - break; - } else { - throw er; - } - } - } - } catch (e) { - common.error('could not remove directory (code ' + e.code + '): ' + dir, { continue: true }); - } +/***/ 6613: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return result; -} // rmdirSyncRecursive +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); -// Hack to determine if file has write permissions for current user -// Avoids having to check user, group, etc, but it's probably slow -function isWriteable(file) { - var writePermission = true; - try { - var __fd = fs.openSync(file, 'a'); - fs.closeSync(__fd); - } catch (e) { - writePermission = false; - } +common.register('head', _head, { + canReceivePipe: true, + cmdOptions: { + 'n': 'numLines', + }, +}); - return writePermission; -} +// Reads |numLines| lines or the entire file, whichever is less. +function readSomeLines(file, numLines) { + var buf = common.buffer(); + var bufLength = buf.length; + var bytesRead = bufLength; + var pos = 0; -function handleFile(file, options) { - if (options.force || isWriteable(file)) { - // -f was passed, or file is writable, so it can be removed - common.unlinkSync(file); - } else { - common.error('permission denied: ' + file, { continue: true }); + var fdr = fs.openSync(file, 'r'); + var numLinesRead = 0; + var ret = ''; + while (bytesRead === bufLength && numLinesRead < numLines) { + bytesRead = fs.readSync(fdr, buf, 0, bufLength, pos); + var bufStr = buf.toString('utf8', 0, bytesRead); + numLinesRead += bufStr.split('\n').length - 1; + ret += bufStr; + pos += bytesRead; } + + fs.closeSync(fdr); + return ret; } -function handleDirectory(file, options) { - if (options.recursive) { - // -r was passed, so directory can be removed - rmdirSyncRecursive(file, options.force); - } else { - common.error('path is a directory', { continue: true }); +//@ +//@ ### head([{'-n': \},] file [, file ...]) +//@ ### head([{'-n': \},] file_array) +//@ +//@ Available options: +//@ +//@ + `-n `: Show the first `` lines of the files +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = head({'-n': 1}, 'file*.txt'); +//@ var str = head('file1', 'file2'); +//@ var str = head(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Read the start of a file. +function _head(options, files) { + var head = []; + var pipe = common.readFromPipe(); + + if (!files && !pipe) common.error('no paths given'); + + var idx = 1; + if (options.numLines === true) { + idx = 2; + options.numLines = Number(arguments[1]); + } else if (options.numLines === false) { + options.numLines = 10; } -} + files = [].slice.call(arguments, idx); -function handleSymbolicLink(file, options) { - var stats; - try { - stats = common.statFollowLinks(file); - } catch (e) { - // symlink is broken, so remove the symlink itself - common.unlinkSync(file); - return; + if (pipe) { + files.unshift('-'); } - if (stats.isFile()) { - common.unlinkSync(file); - } else if (stats.isDirectory()) { - if (file[file.length - 1] === '/') { - // trailing separator, so remove the contents, not the link - if (options.recursive) { - // -r was passed, so directory can be removed - var fromSymlink = true; - rmdirSyncRecursive(file, options.force, fromSymlink); - } else { - common.error('path is a directory', { continue: true }); + var shouldAppendNewline = false; + files.forEach(function (file) { + if (file !== '-') { + if (!fs.existsSync(file)) { + common.error('no such file or directory: ' + file, { continue: true }); + return; + } else if (common.statFollowLinks(file).isDirectory()) { + common.error("error reading '" + file + "': Is a directory", { + continue: true, + }); + return; } + } + + var contents; + if (file === '-') { + contents = pipe; + } else if (options.numLines < 0) { + contents = fs.readFileSync(file, 'utf8'); } else { - // no trailing separator, so remove the link - common.unlinkSync(file); + contents = readSomeLines(file, options.numLines); + } + + var lines = contents.split('\n'); + var hasTrailingNewline = (lines[lines.length - 1] === ''); + if (hasTrailingNewline) { + lines.pop(); } + shouldAppendNewline = (hasTrailingNewline || options.numLines < lines.length); + + head = head.concat(lines.slice(0, options.numLines)); + }); + + if (shouldAppendNewline) { + head.push(''); // to add a trailing newline once we join } + return head.join('\n'); } +module.exports = _head; -function handleFIFO(file) { - common.unlinkSync(file); -} + +/***/ }), + +/***/ 5787: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var common = __nccwpck_require__(3687); + +common.register('ln', _ln, { + cmdOptions: { + 's': 'symlink', + 'f': 'force', + }, +}); //@ -//@ ### rm([options,] file [, file ...]) -//@ ### rm([options,] file_array) +//@ ### ln([options,] source, dest) //@ //@ Available options: //@ +//@ + `-s`: symlink //@ + `-f`: force -//@ + `-r, -R`: recursive //@ //@ Examples: //@ //@ ```javascript -//@ rm('-rf', '/tmp/*'); -//@ rm('some_file.txt', 'another_file.txt'); -//@ rm(['some_file.txt', 'another_file.txt']); // same as above +//@ ln('file', 'newlink'); +//@ ln('-sf', 'file', 'existing'); //@ ``` //@ -//@ Removes files. -function _rm(options, files) { - if (!files) common.error('no paths given'); +//@ Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. +function _ln(options, source, dest) { + if (!source || !dest) { + common.error('Missing and/or '); + } - // Convert to array - files = [].slice.call(arguments, 1); + source = String(source); + var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), ''); + var isAbsolute = (path.resolve(source) === sourcePath); + dest = path.resolve(process.cwd(), String(dest)); - files.forEach(function (file) { - var lstats; - try { - var filepath = (file[file.length - 1] === '/') - ? file.slice(0, -1) // remove the '/' so lstatSync can detect symlinks - : file; - lstats = common.statNoFollowLinks(filepath); // test for existence - } catch (e) { - // Path does not exist, no force flag given - if (!options.force) { - common.error('no such file or directory: ' + file, { continue: true }); - } - return; // skip file + if (fs.existsSync(dest)) { + if (!options.force) { + common.error('Destination file exists', { continue: true }); + } + + fs.unlinkSync(dest); + } + + if (options.symlink) { + var isWindows = process.platform === 'win32'; + var linkType = isWindows ? 'file' : null; + var resolvedSourcePath = isAbsolute ? sourcePath : path.resolve(process.cwd(), path.dirname(dest), source); + if (!fs.existsSync(resolvedSourcePath)) { + common.error('Source file does not exist', { continue: true }); + } else if (isWindows && common.statFollowLinks(resolvedSourcePath).isDirectory()) { + linkType = 'junction'; } - // If here, path exists - if (lstats.isFile()) { - handleFile(file, options); - } else if (lstats.isDirectory()) { - handleDirectory(file, options); - } else if (lstats.isSymbolicLink()) { - handleSymbolicLink(file, options); - } else if (lstats.isFIFO()) { - handleFIFO(file); + try { + fs.symlinkSync(linkType === 'junction' ? resolvedSourcePath : source, dest, linkType); + } catch (err) { + common.error(err.message); } - }); // forEach(file) + } else { + if (!fs.existsSync(source)) { + common.error('Source file does not exist', { continue: true }); + } + try { + fs.linkSync(source, dest); + } catch (err) { + common.error(err.message); + } + } return ''; -} // rm -module.exports = _rm; +} +module.exports = _ln; /***/ }), -/***/ 5899: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 5561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +var path = __nccwpck_require__(1017); +var fs = __nccwpck_require__(7147); +var common = __nccwpck_require__(3687); +var glob = __nccwpck_require__(1957); -common.register('sed', _sed, { - globStart: 3, // don't glob-expand regexes - canReceivePipe: true, +var globPatternRecursive = path.sep + '**'; + +common.register('ls', _ls, { cmdOptions: { - 'i': 'inplace', + 'R': 'recursive', + 'A': 'all', + 'L': 'link', + 'a': 'all_deprecated', + 'd': 'directory', + 'l': 'long', }, }); //@ -//@ ### sed([options,] search_regex, replacement, file [, file ...]) -//@ ### sed([options,] search_regex, replacement, file_array) +//@ ### ls([options,] [path, ...]) +//@ ### ls([options,] path_array) //@ //@ Available options: //@ -//@ + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ +//@ + `-R`: recursive +//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) +//@ + `-L`: follow symlinks +//@ + `-d`: list directories themselves, not their contents +//@ + `-l`: list objects representing each file, each with fields containing `ls +//@ -l` output fields. See +//@ [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) +//@ for more info //@ //@ Examples: //@ //@ ```javascript -//@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); -//@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); +//@ ls('projs/*.js'); +//@ ls('-R', '/users/me', '/tmp'); +//@ ls('-R', ['/users/me', '/tmp']); // same as above +//@ ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} //@ ``` //@ -//@ Reads an input string from `file`s, and performs a JavaScript `replace()` on the input -//@ using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. -//@ -//@ Note: -//@ -//@ Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified -//@ using the `$n` syntax: -//@ -//@ ```javascript -//@ sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); -//@ ``` -function _sed(options, regex, replacement, files) { - // Check if this is coming from a pipe - var pipe = common.readFromPipe(); - - if (typeof replacement !== 'string' && typeof replacement !== 'function') { - if (typeof replacement === 'number') { - replacement = replacement.toString(); // fallback - } else { - common.error('invalid replacement string'); - } - } - - // Convert all search strings to RegExp - if (typeof regex === 'string') { - regex = RegExp(regex); +//@ Returns array of files in the given `path`, or files in +//@ the current directory if no `path` is provided. +function _ls(options, paths) { + if (options.all_deprecated) { + // We won't support the -a option as it's hard to image why it's useful + // (it includes '.' and '..' in addition to '.*' files) + // For backwards compatibility we'll dump a deprecated message and proceed as before + common.log('ls: Option -a is deprecated. Use -A instead'); + options.all = true; } - if (!files && !pipe) { - common.error('no files given'); + if (!paths) { + paths = ['.']; + } else { + paths = [].slice.call(arguments, 1); } - files = [].slice.call(arguments, 3); + var list = []; - if (pipe) { - files.unshift('-'); + function pushFile(abs, relName, stat) { + if (process.platform === 'win32') { + relName = relName.replace(/\\/g, '/'); + } + if (options.long) { + stat = stat || (options.link ? common.statFollowLinks(abs) : common.statNoFollowLinks(abs)); + list.push(addLsAttributes(relName, stat)); + } else { + // list.push(path.relative(rel || '.', file)); + list.push(relName); + } } - var sed = []; - files.forEach(function (file) { - if (!fs.existsSync(file) && file !== '-') { - common.error('no such file or directory: ' + file, 2, { continue: true }); + paths.forEach(function (p) { + var stat; + + try { + stat = options.link ? common.statFollowLinks(p) : common.statNoFollowLinks(p); + // follow links to directories by default + if (stat.isSymbolicLink()) { + /* istanbul ignore next */ + // workaround for https://github.com/shelljs/shelljs/issues/795 + // codecov seems to have a bug that miscalculate this block as uncovered. + // but according to nyc report this block does get covered. + try { + var _stat = common.statFollowLinks(p); + if (_stat.isDirectory()) { + stat = _stat; + } + } catch (_) {} // bad symlink, treat it like a file + } + } catch (e) { + common.error('no such file or directory: ' + p, 2, { continue: true }); return; } - var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); - var lines = contents.split('\n'); - var result = lines.map(function (line) { - return line.replace(regex, replacement); - }).join('\n'); - - sed.push(result); - - if (options.inplace) { - fs.writeFileSync(file, result, 'utf8'); + // If the stat succeeded + if (stat.isDirectory() && !options.directory) { + if (options.recursive) { + // use glob, because it's simple + glob.sync(p + globPatternRecursive, { dot: options.all, follow: options.link }) + .forEach(function (item) { + // Glob pattern returns the directory itself and needs to be filtered out. + if (path.relative(p, item)) { + pushFile(item, path.relative(p, item)); + } + }); + } else if (options.all) { + // use fs.readdirSync, because it's fast + fs.readdirSync(p).forEach(function (item) { + pushFile(path.join(p, item), item); + }); + } else { + // use fs.readdirSync and then filter out secret files + fs.readdirSync(p).forEach(function (item) { + if (item[0] !== '.') { + pushFile(path.join(p, item), item); + } + }); + } + } else { + pushFile(p, p, stat); } }); - return sed.join('\n'); + // Add methods, to make this more compatible with ShellStrings + return list; +} + +function addLsAttributes(pathName, stats) { + // Note: this object will contain more information than .toString() returns + stats.name = pathName; + stats.toString = function () { + // Return a string resembling unix's `ls -l` format + return [this.mode, this.nlink, this.uid, this.gid, this.size, this.mtime, this.name].join(' '); + }; + return stats; } -module.exports = _sed; + +module.exports = _ls; /***/ }), -/***/ 1411: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 2695: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); -common.register('set', _set, { - allowGlobbing: false, - wrapOutput: false, +common.register('mkdir', _mkdir, { + cmdOptions: { + 'p': 'fullpath', + }, }); +// Recursively creates `dir` +function mkdirSyncRecursive(dir) { + var baseDir = path.dirname(dir); + + // Prevents some potential problems arising from malformed UNCs or + // insufficient permissions. + /* istanbul ignore next */ + if (baseDir === dir) { + common.error('dirname() failed: [' + dir + ']'); + } + + // Base dir exists, no recursion necessary + if (fs.existsSync(baseDir)) { + fs.mkdirSync(dir, parseInt('0777', 8)); + return; + } + + // Base dir does not exist, go recursive + mkdirSyncRecursive(baseDir); + + // Base dir created, can create dir + fs.mkdirSync(dir, parseInt('0777', 8)); +} + //@ -//@ ### set(options) +//@ ### mkdir([options,] dir [, dir ...]) +//@ ### mkdir([options,] dir_array) //@ //@ Available options: //@ -//@ + `+/-e`: exit upon error (`config.fatal`) -//@ + `+/-v`: verbose: show all commands (`config.verbose`) -//@ + `+/-f`: disable filename expansion (globbing) +//@ + `-p`: full path (and create intermediate directories, if necessary) //@ //@ Examples: //@ //@ ```javascript -//@ set('-e'); // exit upon first error -//@ set('+e'); // this undoes a "set('-e')" +//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); +//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above //@ ``` //@ -//@ Sets global configuration variables. -function _set(options) { - if (!options) { - var args = [].slice.call(arguments, 0); - if (args.length < 2) common.error('must provide an argument'); - options = args[1]; - } - var negate = (options[0] === '+'); - if (negate) { - options = '-' + options.slice(1); // parseOptions needs a '-' prefix - } - options = common.parseOptions(options, { - 'e': 'fatal', - 'v': 'verbose', - 'f': 'noglob', - }); +//@ Creates directories. +function _mkdir(options, dirs) { + if (!dirs) common.error('no paths given'); - if (negate) { - Object.keys(options).forEach(function (key) { - options[key] = !options[key]; - }); + if (typeof dirs === 'string') { + dirs = [].slice.call(arguments, 1); } + // if it's array leave it as it is - Object.keys(options).forEach(function (key) { - // Only change the global config if `negate` is false and the option is true - // or if `negate` is true and the option is false (aka negate !== option) - if (negate !== options[key]) { - common.config[key] = options[key]; + dirs.forEach(function (dir) { + try { + var stat = common.statNoFollowLinks(dir); + if (!options.fullpath) { + common.error('path already exists: ' + dir, { continue: true }); + } else if (stat.isFile()) { + common.error('cannot create directory ' + dir + ': File exists', { continue: true }); + } + return; // skip dir + } catch (e) { + // do nothing + } + + // Base dir does not exist, and no -p option given + var baseDir = path.dirname(dir); + if (!fs.existsSync(baseDir) && !options.fullpath) { + common.error('no such file or directory: ' + baseDir, { continue: true }); + return; // skip dir + } + + try { + if (options.fullpath) { + mkdirSyncRecursive(path.resolve(dir)); + } else { + fs.mkdirSync(dir, parseInt('0777', 8)); + } + } catch (e) { + var reason; + if (e.code === 'EACCES') { + reason = 'Permission denied'; + } else if (e.code === 'ENOTDIR' || e.code === 'ENOENT') { + reason = 'Not a directory'; + } else { + /* istanbul ignore next */ + throw e; + } + common.error('cannot create directory ' + dir + ': ' + reason, { continue: true }); } }); - return; -} -module.exports = _set; + return ''; +} // mkdir +module.exports = _mkdir; /***/ }), -/***/ 2116: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 9849: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +var common = __nccwpck_require__(3687); +var cp = __nccwpck_require__(4932); +var rm = __nccwpck_require__(2830); -common.register('sort', _sort, { - canReceivePipe: true, +common.register('mv', _mv, { cmdOptions: { - 'r': 'reverse', - 'n': 'numerical', + 'f': '!no_force', + 'n': 'no_force', }, }); -// parse out the number prefix of a line -function parseNumber(str) { - var match = str.match(/^\s*(\d*)\s*(.*)$/); - return { num: Number(match[1]), value: match[2] }; -} - -// compare two strings case-insensitively, but examine case for strings that are -// case-insensitive equivalent -function unixCmp(a, b) { - var aLower = a.toLowerCase(); - var bLower = b.toLowerCase(); - return (aLower === bLower ? - -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does - aLower.localeCompare(bLower)); -} - -// compare two strings in the fashion that unix sort's -n option works -function numericalCmp(a, b) { - var objA = parseNumber(a); - var objB = parseNumber(b); - if (objA.hasOwnProperty('num') && objB.hasOwnProperty('num')) { - return ((objA.num !== objB.num) ? - (objA.num - objB.num) : - unixCmp(objA.value, objB.value)); - } else { - return unixCmp(objA.value, objB.value); - } +// Checks if cureent file was created recently +function checkRecentCreated(sources, index) { + var lookedSource = sources[index]; + return sources.slice(0, index).some(function (src) { + return path.basename(src) === path.basename(lookedSource); + }); } //@ -//@ ### sort([options,] file [, file ...]) -//@ ### sort([options,] file_array) +//@ ### mv([options ,] source [, source ...], dest') +//@ ### mv([options ,] source_array, dest') //@ //@ Available options: //@ -//@ + `-r`: Reverse the results -//@ + `-n`: Compare according to numerical value +//@ + `-f`: force (default behavior) +//@ + `-n`: no-clobber //@ //@ Examples: //@ //@ ```javascript -//@ sort('foo.txt', 'bar.txt'); -//@ sort('-r', 'foo.txt'); +//@ mv('-n', 'file', 'dir/'); +//@ mv('file1', 'file2', 'dir/'); +//@ mv(['file1', 'file2'], 'dir/'); // same as above //@ ``` //@ -//@ Return the contents of the `file`s, sorted line-by-line. Sorting multiple -//@ files mixes their content (just as unix `sort` does). -function _sort(options, files) { - // Check if this is coming from a pipe - var pipe = common.readFromPipe(); +//@ Moves `source` file(s) to `dest`. +function _mv(options, sources, dest) { + // Get sources, dest + if (arguments.length < 3) { + common.error('missing and/or '); + } else if (arguments.length > 3) { + sources = [].slice.call(arguments, 1, arguments.length - 1); + dest = arguments[arguments.length - 1]; + } else if (typeof sources === 'string') { + sources = [sources]; + } else { + // TODO(nate): figure out if we actually need this line + common.error('invalid arguments'); + } - if (!files && !pipe) common.error('no files given'); + var exists = fs.existsSync(dest); + var stats = exists && common.statFollowLinks(dest); - files = [].slice.call(arguments, 1); + // Dest is not existing dir, but multiple sources given + if ((!exists || !stats.isDirectory()) && sources.length > 1) { + common.error('dest is not a directory (too many sources)'); + } - if (pipe) { - files.unshift('-'); + // Dest is an existing file, but no -f given + if (exists && stats.isFile() && options.no_force) { + common.error('dest file already exists: ' + dest); } - var lines = files.reduce(function (accum, file) { - if (file !== '-') { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, { continue: true }); - return accum; - } else if (common.statFollowLinks(file).isDirectory()) { - common.error('read failed: ' + file + ': Is a directory', { - continue: true, - }); - return accum; + sources.forEach(function (src, srcIndex) { + if (!fs.existsSync(src)) { + common.error('no such file or directory: ' + src, { continue: true }); + return; // skip file + } + + // If here, src exists + + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (fs.existsSync(dest) && common.statFollowLinks(dest).isDirectory()) { + thisDest = path.normalize(dest + '/' + path.basename(src)); + } + + var thisDestExists = fs.existsSync(thisDest); + + if (thisDestExists && checkRecentCreated(sources, srcIndex)) { + // cannot overwrite file created recently in current execution, but we want to continue copying other files + if (!options.no_force) { + common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true }); } + return; } - var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); - return accum.concat(contents.trimRight().split('\n')); - }, []); + if (fs.existsSync(thisDest) && options.no_force) { + common.error('dest file already exists: ' + thisDest, { continue: true }); + return; // skip file + } - var sorted = lines.sort(options.numerical ? numericalCmp : unixCmp); + if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { + common.error('cannot move to self: ' + src, { continue: true }); + return; // skip file + } - if (options.reverse) { - sorted = sorted.reverse(); - } + try { + fs.renameSync(src, thisDest); + } catch (e) { + /* istanbul ignore next */ + if (e.code === 'EXDEV') { + // If we're trying to `mv` to an external partition, we'll actually need + // to perform a copy and then clean up the original file. If either the + // copy or the rm fails with an exception, we should allow this + // exception to pass up to the top level. + cp('-r', src, thisDest); + rm('-rf', src); + } + } + }); // forEach(src) + return ''; +} // mv +module.exports = _mv; - return sorted.join('\n') + '\n'; -} -module.exports = _sort; +/***/ }), + +/***/ 227: +/***/ (() => { + +// see dirs.js /***/ }), -/***/ 2284: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 4177: +/***/ (() => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +// see dirs.js -common.register('tail', _tail, { - canReceivePipe: true, - cmdOptions: { - 'n': 'numLines', - }, + +/***/ }), + +/***/ 8553: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var path = __nccwpck_require__(1017); +var common = __nccwpck_require__(3687); + +common.register('pwd', _pwd, { + allowGlobbing: false, }); //@ -//@ ### tail([{'-n': \},] file [, file ...]) -//@ ### tail([{'-n': \},] file_array) -//@ -//@ Available options: -//@ -//@ + `-n `: Show the last `` lines of `file`s -//@ -//@ Examples: -//@ -//@ ```javascript -//@ var str = tail({'-n': 1}, 'file*.txt'); -//@ var str = tail('file1', 'file2'); -//@ var str = tail(['file1', 'file2']); // same as above -//@ ``` +//@ ### pwd() //@ -//@ Read the end of a `file`. -function _tail(options, files) { - var tail = []; - var pipe = common.readFromPipe(); +//@ Returns the current directory. +function _pwd() { + var pwd = path.resolve(process.cwd()); + return pwd; +} +module.exports = _pwd; - if (!files && !pipe) common.error('no paths given'); - var idx = 1; - if (options.numLines === true) { - idx = 2; - options.numLines = Number(arguments[1]); - } else if (options.numLines === false) { - options.numLines = 10; - } - options.numLines = -1 * Math.abs(options.numLines); - files = [].slice.call(arguments, idx); +/***/ }), - if (pipe) { - files.unshift('-'); - } +/***/ 2830: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var shouldAppendNewline = false; - files.forEach(function (file) { - if (file !== '-') { - if (!fs.existsSync(file)) { - common.error('no such file or directory: ' + file, { continue: true }); - return; - } else if (common.statFollowLinks(file).isDirectory()) { - common.error("error reading '" + file + "': Is a directory", { - continue: true, - }); - return; - } - } +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); - var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); +common.register('rm', _rm, { + cmdOptions: { + 'f': 'force', + 'r': 'recursive', + 'R': 'recursive', + }, +}); - var lines = contents.split('\n'); - if (lines[lines.length - 1] === '') { - lines.pop(); - shouldAppendNewline = true; - } else { - shouldAppendNewline = false; - } +// Recursively removes 'dir' +// Adapted from https://github.com/ryanmcgrath/wrench-js +// +// Copyright (c) 2010 Ryan McGrath +// Copyright (c) 2012 Artur Adib +// +// Licensed under the MIT License +// http://www.opensource.org/licenses/mit-license.php +function rmdirSyncRecursive(dir, force, fromSymlink) { + var files; - tail = tail.concat(lines.slice(options.numLines)); - }); + files = fs.readdirSync(dir); - if (shouldAppendNewline) { - tail.push(''); // to add a trailing newline once we join + // Loop through and delete everything in the sub-tree after checking it + for (var i = 0; i < files.length; i++) { + var file = dir + '/' + files[i]; + var currFile = common.statNoFollowLinks(file); + + if (currFile.isDirectory()) { // Recursive function back to the beginning + rmdirSyncRecursive(file, force); + } else { // Assume it's a file - perhaps a try/catch belongs here? + if (force || isWriteable(file)) { + try { + common.unlinkSync(file); + } catch (e) { + /* istanbul ignore next */ + common.error('could not remove file (code ' + e.code + '): ' + file, { + continue: true, + }); + } + } + } } - return tail.join('\n'); -} -module.exports = _tail; + // if was directory was referenced through a symbolic link, + // the contents should be removed, but not the directory itself + if (fromSymlink) return; -/***/ }), + // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. + // Huzzah for the shopkeep. -/***/ 6150: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + var result; + try { + // Retry on windows, sometimes it takes a little time before all the files in the directory are gone + var start = Date.now(); -var common = __webpack_require__(3687); -var os = __webpack_require__(2087); -var fs = __webpack_require__(5747); + // TODO: replace this with a finite loop + for (;;) { + try { + result = fs.rmdirSync(dir); + if (fs.existsSync(dir)) throw { code: 'EAGAIN' }; + break; + } catch (er) { + /* istanbul ignore next */ + // In addition to error codes, also check if the directory still exists and loop again if true + if (process.platform === 'win32' && (er.code === 'ENOTEMPTY' || er.code === 'EBUSY' || er.code === 'EPERM' || er.code === 'EAGAIN')) { + if (Date.now() - start > 1000) throw er; + } else if (er.code === 'ENOENT') { + // Directory did not exist, deletion was successful + break; + } else { + throw er; + } + } + } + } catch (e) { + common.error('could not remove directory (code ' + e.code + '): ' + dir, { continue: true }); + } -common.register('tempdir', _tempDir, { - allowGlobbing: false, - wrapOutput: false, -}); + return result; +} // rmdirSyncRecursive -// Returns false if 'dir' is not a writeable directory, 'dir' otherwise -function writeableDir(dir) { - if (!dir || !fs.existsSync(dir)) return false; +// Hack to determine if file has write permissions for current user +// Avoids having to check user, group, etc, but it's probably slow +function isWriteable(file) { + var writePermission = true; + try { + var __fd = fs.openSync(file, 'a'); + fs.closeSync(__fd); + } catch (e) { + writePermission = false; + } - if (!common.statFollowLinks(dir).isDirectory()) return false; + return writePermission; +} - var testFile = dir + '/' + common.randomFileName(); +function handleFile(file, options) { + if (options.force || isWriteable(file)) { + // -f was passed, or file is writable, so it can be removed + common.unlinkSync(file); + } else { + common.error('permission denied: ' + file, { continue: true }); + } +} + +function handleDirectory(file, options) { + if (options.recursive) { + // -r was passed, so directory can be removed + rmdirSyncRecursive(file, options.force); + } else { + common.error('path is a directory', { continue: true }); + } +} + +function handleSymbolicLink(file, options) { + var stats; try { - fs.writeFileSync(testFile, ' '); - common.unlinkSync(testFile); - return dir; + stats = common.statFollowLinks(file); } catch (e) { - /* istanbul ignore next */ - return false; + // symlink is broken, so remove the symlink itself + common.unlinkSync(file); + return; + } + + if (stats.isFile()) { + common.unlinkSync(file); + } else if (stats.isDirectory()) { + if (file[file.length - 1] === '/') { + // trailing separator, so remove the contents, not the link + if (options.recursive) { + // -r was passed, so directory can be removed + var fromSymlink = true; + rmdirSyncRecursive(file, options.force, fromSymlink); + } else { + common.error('path is a directory', { continue: true }); + } + } else { + // no trailing separator, so remove the link + common.unlinkSync(file); + } } } -// Variable to cache the tempdir value for successive lookups. -var cachedTempDir; +function handleFIFO(file) { + common.unlinkSync(file); +} //@ -//@ ### tempdir() +//@ ### rm([options,] file [, file ...]) +//@ ### rm([options,] file_array) +//@ +//@ Available options: +//@ +//@ + `-f`: force +//@ + `-r, -R`: recursive //@ //@ Examples: //@ //@ ```javascript -//@ var tmp = tempdir(); // "/tmp" for most *nix platforms +//@ rm('-rf', '/tmp/*'); +//@ rm('some_file.txt', 'another_file.txt'); +//@ rm(['some_file.txt', 'another_file.txt']); // same as above //@ ``` //@ -//@ Searches and returns string containing a writeable, platform-dependent temporary directory. -//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). -function _tempDir() { - if (cachedTempDir) return cachedTempDir; - - cachedTempDir = writeableDir(os.tmpdir()) || - writeableDir(process.env.TMPDIR) || - writeableDir(process.env.TEMP) || - writeableDir(process.env.TMP) || - writeableDir(process.env.Wimp$ScrapDir) || // RiscOS - writeableDir('C:\\TEMP') || // Windows - writeableDir('C:\\TMP') || // Windows - writeableDir('\\TEMP') || // Windows - writeableDir('\\TMP') || // Windows - writeableDir('/tmp') || - writeableDir('/var/tmp') || - writeableDir('/usr/tmp') || - writeableDir('.'); // last resort - - return cachedTempDir; -} +//@ Removes files. +function _rm(options, files) { + if (!files) common.error('no paths given'); -// Indicates if the tempdir value is currently cached. This is exposed for tests -// only. The return value should only be tested for truthiness. -function isCached() { - return cachedTempDir; -} + // Convert to array + files = [].slice.call(arguments, 1); -// Clears the cached tempDir value, if one is cached. This is exposed for tests -// only. -function clearCache() { - cachedTempDir = undefined; -} + files.forEach(function (file) { + var lstats; + try { + var filepath = (file[file.length - 1] === '/') + ? file.slice(0, -1) // remove the '/' so lstatSync can detect symlinks + : file; + lstats = common.statNoFollowLinks(filepath); // test for existence + } catch (e) { + // Path does not exist, no force flag given + if (!options.force) { + common.error('no such file or directory: ' + file, { continue: true }); + } + return; // skip file + } -module.exports.tempDir = _tempDir; -module.exports.isCached = isCached; -module.exports.clearCache = clearCache; + // If here, path exists + if (lstats.isFile()) { + handleFile(file, options); + } else if (lstats.isDirectory()) { + handleDirectory(file, options); + } else if (lstats.isSymbolicLink()) { + handleSymbolicLink(file, options); + } else if (lstats.isFIFO()) { + handleFIFO(file); + } + }); // forEach(file) + return ''; +} // rm +module.exports = _rm; /***/ }), -/***/ 9723: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 5899: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); -common.register('test', _test, { +common.register('sed', _sed, { + globStart: 3, // don't glob-expand regexes + canReceivePipe: true, cmdOptions: { - 'b': 'block', - 'c': 'character', - 'd': 'directory', - 'e': 'exists', - 'f': 'file', - 'L': 'link', - 'p': 'pipe', - 'S': 'socket', + 'i': 'inplace', }, - wrapOutput: false, - allowGlobbing: false, }); - //@ -//@ ### test(expression) +//@ ### sed([options,] search_regex, replacement, file [, file ...]) +//@ ### sed([options,] search_regex, replacement, file_array) //@ -//@ Available expression primaries: +//@ Available options: //@ -//@ + `'-b', 'path'`: true if path is a block device -//@ + `'-c', 'path'`: true if path is a character device -//@ + `'-d', 'path'`: true if path is a directory -//@ + `'-e', 'path'`: true if path exists -//@ + `'-f', 'path'`: true if path is a regular file -//@ + `'-L', 'path'`: true if path is a symbolic link -//@ + `'-p', 'path'`: true if path is a pipe (FIFO) -//@ + `'-S', 'path'`: true if path is a socket +//@ + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ //@ //@ Examples: //@ //@ ```javascript -//@ if (test('-d', path)) { /* do something with dir */ }; -//@ if (!test('-f', path)) continue; // skip if it's a regular file +//@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); +//@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); //@ ``` //@ -//@ Evaluates `expression` using the available primaries and returns corresponding value. -function _test(options, path) { - if (!path) common.error('no path given'); - - var canInterpret = false; - Object.keys(options).forEach(function (key) { - if (options[key] === true) { - canInterpret = true; - } - }); - - if (!canInterpret) common.error('could not interpret expression'); +//@ Reads an input string from `file`s, and performs a JavaScript `replace()` on the input +//@ using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. +//@ +//@ Note: +//@ +//@ Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified +//@ using the `$n` syntax: +//@ +//@ ```javascript +//@ sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); +//@ ``` +function _sed(options, regex, replacement, files) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); - if (options.link) { - try { - return common.statNoFollowLinks(path).isSymbolicLink(); - } catch (e) { - return false; + if (typeof replacement !== 'string' && typeof replacement !== 'function') { + if (typeof replacement === 'number') { + replacement = replacement.toString(); // fallback + } else { + common.error('invalid replacement string'); } } - if (!fs.existsSync(path)) return false; - - if (options.exists) return true; + // Convert all search strings to RegExp + if (typeof regex === 'string') { + regex = RegExp(regex); + } - var stats = common.statFollowLinks(path); + if (!files && !pipe) { + common.error('no files given'); + } - if (options.block) return stats.isBlockDevice(); + files = [].slice.call(arguments, 3); - if (options.character) return stats.isCharacterDevice(); + if (pipe) { + files.unshift('-'); + } - if (options.directory) return stats.isDirectory(); + var sed = []; + files.forEach(function (file) { + if (!fs.existsSync(file) && file !== '-') { + common.error('no such file or directory: ' + file, 2, { continue: true }); + return; + } - if (options.file) return stats.isFile(); + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + var lines = contents.split('\n'); + var result = lines.map(function (line) { + return line.replace(regex, replacement); + }).join('\n'); - /* istanbul ignore next */ - if (options.pipe) return stats.isFIFO(); + sed.push(result); - /* istanbul ignore next */ - if (options.socket) return stats.isSocket(); + if (options.inplace) { + fs.writeFileSync(file, result, 'utf8'); + } + }); - /* istanbul ignore next */ - return false; // fallback -} // test -module.exports = _test; + return sed.join('\n'); +} +module.exports = _sed; /***/ }), -/***/ 1961: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 1411: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); +var common = __nccwpck_require__(3687); -common.register('to', _to, { - pipeOnly: true, +common.register('set', _set, { + allowGlobbing: false, wrapOutput: false, }); //@ -//@ ### ShellString.prototype.to(file) -//@ -//@ Examples: -//@ -//@ ```javascript -//@ cat('input.txt').to('output.txt'); -//@ ``` +//@ ### set(options) //@ -//@ Analogous to the redirection operator `>` in Unix, but works with -//@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix -//@ redirections, `to()` will overwrite any existing file!_ -function _to(options, file) { - if (!file) common.error('wrong arguments'); - - if (!fs.existsSync(path.dirname(file))) { - common.error('no such file or directory: ' + path.dirname(file)); - } - - try { - fs.writeFileSync(file, this.stdout || this.toString(), 'utf8'); - return this; - } catch (e) { - /* istanbul ignore next */ - common.error('could not write to file (code ' + e.code + '): ' + file, { continue: true }); - } -} -module.exports = _to; - - -/***/ }), - -/***/ 3736: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); - -common.register('toEnd', _toEnd, { - pipeOnly: true, - wrapOutput: false, -}); - +//@ Available options: //@ -//@ ### ShellString.prototype.toEnd(file) +//@ + `+/-e`: exit upon error (`config.fatal`) +//@ + `+/-v`: verbose: show all commands (`config.verbose`) +//@ + `+/-f`: disable filename expansion (globbing) //@ //@ Examples: //@ //@ ```javascript -//@ cat('input.txt').toEnd('output.txt'); +//@ set('-e'); // exit upon first error +//@ set('+e'); // this undoes a "set('-e')" //@ ``` //@ -//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with -//@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). -function _toEnd(options, file) { - if (!file) common.error('wrong arguments'); - - if (!fs.existsSync(path.dirname(file))) { - common.error('no such file or directory: ' + path.dirname(file)); +//@ Sets global configuration variables. +function _set(options) { + if (!options) { + var args = [].slice.call(arguments, 0); + if (args.length < 2) common.error('must provide an argument'); + options = args[1]; + } + var negate = (options[0] === '+'); + if (negate) { + options = '-' + options.slice(1); // parseOptions needs a '-' prefix } + options = common.parseOptions(options, { + 'e': 'fatal', + 'v': 'verbose', + 'f': 'noglob', + }); - try { - fs.appendFileSync(file, this.stdout || this.toString(), 'utf8'); - return this; - } catch (e) { - /* istanbul ignore next */ - common.error('could not append to file (code ' + e.code + '): ' + file, { continue: true }); + if (negate) { + Object.keys(options).forEach(function (key) { + options[key] = !options[key]; + }); } + + Object.keys(options).forEach(function (key) { + // Only change the global config if `negate` is false and the option is true + // or if `negate` is true and the option is false (aka negate !== option) + if (negate !== options[key]) { + common.config[key] = options[key]; + } + }); + return; } -module.exports = _toEnd; +module.exports = _set; /***/ }), -/***/ 8358: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 2116: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); -common.register('touch', _touch, { +common.register('sort', _sort, { + canReceivePipe: true, cmdOptions: { - 'a': 'atime_only', - 'c': 'no_create', - 'd': 'date', - 'm': 'mtime_only', - 'r': 'reference', + 'r': 'reverse', + 'n': 'numerical', }, }); +// parse out the number prefix of a line +function parseNumber(str) { + var match = str.match(/^\s*(\d*)\s*(.*)$/); + return { num: Number(match[1]), value: match[2] }; +} + +// compare two strings case-insensitively, but examine case for strings that are +// case-insensitive equivalent +function unixCmp(a, b) { + var aLower = a.toLowerCase(); + var bLower = b.toLowerCase(); + return (aLower === bLower ? + -1 * a.localeCompare(b) : // unix sort treats case opposite how javascript does + aLower.localeCompare(bLower)); +} + +// compare two strings in the fashion that unix sort's -n option works +function numericalCmp(a, b) { + var objA = parseNumber(a); + var objB = parseNumber(b); + if (objA.hasOwnProperty('num') && objB.hasOwnProperty('num')) { + return ((objA.num !== objB.num) ? + (objA.num - objB.num) : + unixCmp(objA.value, objB.value)); + } else { + return unixCmp(objA.value, objB.value); + } +} + //@ -//@ ### touch([options,] file [, file ...]) -//@ ### touch([options,] file_array) +//@ ### sort([options,] file [, file ...]) +//@ ### sort([options,] file_array) //@ //@ Available options: //@ -//@ + `-a`: Change only the access time -//@ + `-c`: Do not create any files -//@ + `-m`: Change only the modification time -//@ + `-d DATE`: Parse `DATE` and use it instead of current time -//@ + `-r FILE`: Use `FILE`'s times instead of current time +//@ + `-r`: Reverse the results +//@ + `-n`: Compare according to numerical value //@ //@ Examples: //@ //@ ```javascript -//@ touch('source.js'); -//@ touch('-c', '/path/to/some/dir/source.js'); -//@ touch({ '-r': FILE }, '/path/to/some/dir/source.js'); +//@ sort('foo.txt', 'bar.txt'); +//@ sort('-r', 'foo.txt'); //@ ``` //@ -//@ Update the access and modification times of each `FILE` to the current time. -//@ A `FILE` argument that does not exist is created empty, unless `-c` is supplied. -//@ This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). -function _touch(opts, files) { - if (!files) { - common.error('no files given'); - } else if (typeof files === 'string') { - files = [].slice.call(arguments, 1); - } else { - common.error('file arg should be a string file path or an Array of string file paths'); - } - - files.forEach(function (f) { - touchFile(opts, f); - }); - return ''; -} +//@ Return the contents of the `file`s, sorted line-by-line. Sorting multiple +//@ files mixes their content (just as unix `sort` does). +function _sort(options, files) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); -function touchFile(opts, file) { - var stat = tryStatFile(file); + if (!files && !pipe) common.error('no files given'); - if (stat && stat.isDirectory()) { - // don't error just exit - return; - } + files = [].slice.call(arguments, 1); - // if the file doesn't already exist and the user has specified --no-create then - // this script is finished - if (!stat && opts.no_create) { - return; + if (pipe) { + files.unshift('-'); } - // open the file and then close it. this will create it if it doesn't exist but will - // not truncate the file - fs.closeSync(fs.openSync(file, 'a')); - - // - // Set timestamps - // + var lines = files.reduce(function (accum, file) { + if (file !== '-') { + if (!fs.existsSync(file)) { + common.error('no such file or directory: ' + file, { continue: true }); + return accum; + } else if (common.statFollowLinks(file).isDirectory()) { + common.error('read failed: ' + file + ': Is a directory', { + continue: true, + }); + return accum; + } + } - // setup some defaults - var now = new Date(); - var mtime = opts.date || now; - var atime = opts.date || now; + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + return accum.concat(contents.trimRight().split('\n')); + }, []); - // use reference file - if (opts.reference) { - var refStat = tryStatFile(opts.reference); - if (!refStat) { - common.error('failed to get attributess of ' + opts.reference); - } - mtime = refStat.mtime; - atime = refStat.atime; - } else if (opts.date) { - mtime = opts.date; - atime = opts.date; - } + var sorted = lines.sort(options.numerical ? numericalCmp : unixCmp); - if (opts.atime_only && opts.mtime_only) { - // keep the new values of mtime and atime like GNU - } else if (opts.atime_only) { - mtime = stat.mtime; - } else if (opts.mtime_only) { - atime = stat.atime; + if (options.reverse) { + sorted = sorted.reverse(); } - fs.utimesSync(file, atime, mtime); + return sorted.join('\n') + '\n'; } -module.exports = _touch; - -function tryStatFile(filePath) { - try { - return common.statFollowLinks(filePath); - } catch (e) { - return null; - } -} +module.exports = _sort; /***/ }), -/***/ 7286: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); +/***/ 2284: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// add c spaces to the left of str -function lpad(c, str) { - var res = '' + str; - if (res.length < c) { - res = Array((c - res.length) + 1).join(' ') + res; - } - return res; -} +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); -common.register('uniq', _uniq, { +common.register('tail', _tail, { canReceivePipe: true, cmdOptions: { - 'i': 'ignoreCase', - 'c': 'count', - 'd': 'duplicates', + 'n': 'numLines', }, }); //@ -//@ ### uniq([options,] [input, [output]]) +//@ ### tail([{'-n': \},] file [, file ...]) +//@ ### tail([{'-n': \},] file_array) //@ //@ Available options: //@ -//@ + `-i`: Ignore case while comparing -//@ + `-c`: Prefix lines by the number of occurrences -//@ + `-d`: Only print duplicate lines, one for each group of identical lines +//@ + `-n `: Show the last `` lines of `file`s //@ //@ Examples: //@ //@ ```javascript -//@ uniq('foo.txt'); -//@ uniq('-i', 'foo.txt'); -//@ uniq('-cd', 'foo.txt', 'bar.txt'); +//@ var str = tail({'-n': 1}, 'file*.txt'); +//@ var str = tail('file1', 'file2'); +//@ var str = tail(['file1', 'file2']); // same as above //@ ``` //@ -//@ Filter adjacent matching lines from `input`. -function _uniq(options, input, output) { - // Check if this is coming from a pipe +//@ Read the end of a `file`. +function _tail(options, files) { + var tail = []; var pipe = common.readFromPipe(); - if (!pipe) { - if (!input) common.error('no input given'); + if (!files && !pipe) common.error('no paths given'); - if (!fs.existsSync(input)) { - common.error(input + ': No such file or directory'); - } else if (common.statFollowLinks(input).isDirectory()) { - common.error("error reading '" + input + "'"); - } + var idx = 1; + if (options.numLines === true) { + idx = 2; + options.numLines = Number(arguments[1]); + } else if (options.numLines === false) { + options.numLines = 10; } - if (output && fs.existsSync(output) && common.statFollowLinks(output).isDirectory()) { - common.error(output + ': Is a directory'); + options.numLines = -1 * Math.abs(options.numLines); + files = [].slice.call(arguments, idx); + + if (pipe) { + files.unshift('-'); } - var lines = (input ? fs.readFileSync(input, 'utf8') : pipe). - trimRight(). - split('\n'); + var shouldAppendNewline = false; + files.forEach(function (file) { + if (file !== '-') { + if (!fs.existsSync(file)) { + common.error('no such file or directory: ' + file, { continue: true }); + return; + } else if (common.statFollowLinks(file).isDirectory()) { + common.error("error reading '" + file + "': Is a directory", { + continue: true, + }); + return; + } + } - var compare = function (a, b) { - return options.ignoreCase ? - a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()) : - a.localeCompare(b); - }; - var uniqed = lines.reduceRight(function (res, e) { - // Perform uniq -c on the input - if (res.length === 0) { - return [{ count: 1, ln: e }]; - } else if (compare(res[0].ln, e) === 0) { - return [{ count: res[0].count + 1, ln: e }].concat(res.slice(1)); + var contents = file === '-' ? pipe : fs.readFileSync(file, 'utf8'); + + var lines = contents.split('\n'); + if (lines[lines.length - 1] === '') { + lines.pop(); + shouldAppendNewline = true; } else { - return [{ count: 1, ln: e }].concat(res); + shouldAppendNewline = false; } - }, []).filter(function (obj) { - // Do we want only duplicated objects? - return options.duplicates ? obj.count > 1 : true; - }).map(function (obj) { - // Are we tracking the counts of each line? - return (options.count ? (lpad(7, obj.count) + ' ') : '') + obj.ln; - }).join('\n') + '\n'; - if (output) { - (new common.ShellString(uniqed)).to(output); - // if uniq writes to output, nothing is passed to the next command in the pipeline (if any) - return ''; - } else { - return uniqed; + tail = tail.concat(lines.slice(options.numLines)); + }); + + if (shouldAppendNewline) { + tail.push(''); // to add a trailing newline once we join } + return tail.join('\n'); } - -module.exports = _uniq; +module.exports = _tail; /***/ }), -/***/ 4766: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 6150: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var common = __webpack_require__(3687); -var fs = __webpack_require__(5747); -var path = __webpack_require__(5622); +var common = __nccwpck_require__(3687); +var os = __nccwpck_require__(2037); +var fs = __nccwpck_require__(7147); -common.register('which', _which, { +common.register('tempdir', _tempDir, { allowGlobbing: false, - cmdOptions: { - 'a': 'all', - }, + wrapOutput: false, }); -// XP's system default value for `PATHEXT` system variable, just in case it's not -// set on Windows. -var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh'; - -// For earlier versions of NodeJS that doesn't have a list of constants (< v6) -var FILE_EXECUTABLE_MODE = 1; - -function isWindowsPlatform() { - return process.platform === 'win32'; -} +// Returns false if 'dir' is not a writeable directory, 'dir' otherwise +function writeableDir(dir) { + if (!dir || !fs.existsSync(dir)) return false; -// Cross-platform method for splitting environment `PATH` variables -function splitPath(p) { - return p ? p.split(path.delimiter) : []; -} + if (!common.statFollowLinks(dir).isDirectory()) return false; -// Tests are running all cases for this func but it stays uncovered by codecov due to unknown reason -/* istanbul ignore next */ -function isExecutable(pathName) { + var testFile = dir + '/' + common.randomFileName(); try { - // TODO(node-support): replace with fs.constants.X_OK once remove support for node < v6 - fs.accessSync(pathName, FILE_EXECUTABLE_MODE); - } catch (err) { + fs.writeFileSync(testFile, ' '); + common.unlinkSync(testFile); + return dir; + } catch (e) { + /* istanbul ignore next */ return false; } - return true; } -function checkPath(pathName) { - return fs.existsSync(pathName) && !common.statFollowLinks(pathName).isDirectory() - && (isWindowsPlatform() || isExecutable(pathName)); -} +// Variable to cache the tempdir value for successive lookups. +var cachedTempDir; //@ -//@ ### which(command) +//@ ### tempdir() //@ //@ Examples: //@ //@ ```javascript -//@ var nodeExec = which('node'); +//@ var tmp = tempdir(); // "/tmp" for most *nix platforms //@ ``` //@ -//@ Searches for `command` in the system's `PATH`. On Windows, this uses the -//@ `PATHEXT` variable to append the extension if it's not already executable. -//@ Returns string containing the absolute path to `command`. -function _which(options, cmd) { - if (!cmd) common.error('must specify command'); - - var isWindows = isWindowsPlatform(); - var pathArray = splitPath(process.env.PATH); - - var queryMatches = []; - - // No relative/absolute paths provided? - if (cmd.indexOf('/') === -1) { - // Assume that there are no extensions to append to queries (this is the - // case for unix) - var pathExtArray = ['']; - if (isWindows) { - // In case the PATHEXT variable is somehow not set (e.g. - // child_process.spawn with an empty environment), use the XP default. - var pathExtEnv = process.env.PATHEXT || XP_DEFAULT_PATHEXT; - pathExtArray = splitPath(pathExtEnv.toUpperCase()); - } - - // Search for command in PATH - for (var k = 0; k < pathArray.length; k++) { - // already found it - if (queryMatches.length > 0 && !options.all) break; +//@ Searches and returns string containing a writeable, platform-dependent temporary directory. +//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). +function _tempDir() { + if (cachedTempDir) return cachedTempDir; - var attempt = path.resolve(pathArray[k], cmd); + cachedTempDir = writeableDir(os.tmpdir()) || + writeableDir(process.env.TMPDIR) || + writeableDir(process.env.TEMP) || + writeableDir(process.env.TMP) || + writeableDir(process.env.Wimp$ScrapDir) || // RiscOS + writeableDir('C:\\TEMP') || // Windows + writeableDir('C:\\TMP') || // Windows + writeableDir('\\TEMP') || // Windows + writeableDir('\\TMP') || // Windows + writeableDir('/tmp') || + writeableDir('/var/tmp') || + writeableDir('/usr/tmp') || + writeableDir('.'); // last resort - if (isWindows) { - attempt = attempt.toUpperCase(); - } + return cachedTempDir; +} - var match = attempt.match(/\.[^<>:"/\|?*.]+$/); - if (match && pathExtArray.indexOf(match[0]) >= 0) { // this is Windows-only - // The user typed a query with the file extension, like - // `which('node.exe')` - if (checkPath(attempt)) { - queryMatches.push(attempt); - break; - } - } else { // All-platforms - // Cycle through the PATHEXT array, and check each extension - // Note: the array is always [''] on Unix - for (var i = 0; i < pathExtArray.length; i++) { - var ext = pathExtArray[i]; - var newAttempt = attempt + ext; - if (checkPath(newAttempt)) { - queryMatches.push(newAttempt); - break; - } - } - } - } - } else if (checkPath(cmd)) { // a valid absolute or relative path - queryMatches.push(path.resolve(cmd)); - } +// Indicates if the tempdir value is currently cached. This is exposed for tests +// only. The return value should only be tested for truthiness. +function isCached() { + return cachedTempDir; +} - if (queryMatches.length > 0) { - return options.all ? queryMatches : queryMatches[0]; - } - return options.all ? [] : null; +// Clears the cached tempDir value, if one is cached. This is exposed for tests +// only. +function clearCache() { + cachedTempDir = undefined; } -module.exports = _which; + +module.exports.tempDir = _tempDir; +module.exports.isCached = isCached; +module.exports.clearCache = clearCache; /***/ }), -/***/ 2940: -/***/ ((module) => { +/***/ 9723: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') +common.register('test', _test, { + cmdOptions: { + 'b': 'block', + 'c': 'character', + 'd': 'directory', + 'e': 'exists', + 'f': 'file', + 'L': 'link', + 'p': 'pipe', + 'S': 'socket', + }, + wrapOutput: false, + allowGlobbing: false, +}); - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - return wrapper +//@ +//@ ### test(expression) +//@ +//@ Available expression primaries: +//@ +//@ + `'-b', 'path'`: true if path is a block device +//@ + `'-c', 'path'`: true if path is a character device +//@ + `'-d', 'path'`: true if path is a directory +//@ + `'-e', 'path'`: true if path exists +//@ + `'-f', 'path'`: true if path is a regular file +//@ + `'-L', 'path'`: true if path is a symbolic link +//@ + `'-p', 'path'`: true if path is a pipe (FIFO) +//@ + `'-S', 'path'`: true if path is a socket +//@ +//@ Examples: +//@ +//@ ```javascript +//@ if (test('-d', path)) { /* do something with dir */ }; +//@ if (!test('-f', path)) continue; // skip if it's a regular file +//@ ``` +//@ +//@ Evaluates `expression` using the available primaries and returns corresponding value. +function _test(options, path) { + if (!path) common.error('no path given'); - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] + var canInterpret = false; + Object.keys(options).forEach(function (key) { + if (options[key] === true) { + canInterpret = true; } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) + }); + + if (!canInterpret) common.error('could not interpret expression'); + + if (options.link) { + try { + return common.statNoFollowLinks(path).isSymbolicLink(); + } catch (e) { + return false; } - return ret } -} + if (!fs.existsSync(path)) return false; -/***/ }), + if (options.exists) return true; -/***/ 1983: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + var stats = common.statFollowLinks(path); -"use strict"; + if (options.block) return stats.isBlockDevice(); + if (options.character) return stats.isCharacterDevice(); -var PlainValue = __webpack_require__(5215); -var resolveSeq = __webpack_require__(6140); -var Schema = __webpack_require__(3656); - -const defaultOptions = { - anchorPrefix: 'a', - customTags: null, - indent: 2, - indentSeq: true, - keepCstNodes: false, - keepNodeTypes: true, - keepBlobsInJSON: true, - mapAsMap: false, - maxAliasCount: 100, - prettyErrors: false, - // TODO Set true in v2 - simpleKeys: false, - version: '1.2' -}; -const scalarOptions = { - get binary() { - return resolveSeq.binaryOptions; - }, + if (options.directory) return stats.isDirectory(); - set binary(opt) { - Object.assign(resolveSeq.binaryOptions, opt); - }, + if (options.file) return stats.isFile(); - get bool() { - return resolveSeq.boolOptions; - }, + /* istanbul ignore next */ + if (options.pipe) return stats.isFIFO(); - set bool(opt) { - Object.assign(resolveSeq.boolOptions, opt); - }, + /* istanbul ignore next */ + if (options.socket) return stats.isSocket(); - get int() { - return resolveSeq.intOptions; - }, + /* istanbul ignore next */ + return false; // fallback +} // test +module.exports = _test; - set int(opt) { - Object.assign(resolveSeq.intOptions, opt); - }, - get null() { - return resolveSeq.nullOptions; - }, +/***/ }), - set null(opt) { - Object.assign(resolveSeq.nullOptions, opt); - }, +/***/ 1961: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get str() { - return resolveSeq.strOptions; - }, +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); - set str(opt) { - Object.assign(resolveSeq.strOptions, opt); - } +common.register('to', _to, { + pipeOnly: true, + wrapOutput: false, +}); -}; -const documentOptions = { - '1.0': { - schema: 'yaml-1.1', - merge: true, - tagPrefixes: [{ - handle: '!', - prefix: PlainValue.defaultTagPrefix - }, { - handle: '!!', - prefix: 'tag:private.yaml.org,2002:' - }] - }, - '1.1': { - schema: 'yaml-1.1', - merge: true, - tagPrefixes: [{ - handle: '!', - prefix: '!' - }, { - handle: '!!', - prefix: PlainValue.defaultTagPrefix - }] - }, - '1.2': { - schema: 'core', - merge: false, - tagPrefixes: [{ - handle: '!', - prefix: '!' - }, { - handle: '!!', - prefix: PlainValue.defaultTagPrefix - }] - } -}; +//@ +//@ ### ShellString.prototype.to(file) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ cat('input.txt').to('output.txt'); +//@ ``` +//@ +//@ Analogous to the redirection operator `>` in Unix, but works with +//@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix +//@ redirections, `to()` will overwrite any existing file!_ +function _to(options, file) { + if (!file) common.error('wrong arguments'); -function stringifyTag(doc, tag) { - if ((doc.version || doc.options.version) === '1.0') { - const priv = tag.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/); - if (priv) return '!' + priv[1]; - const vocab = tag.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/); - return vocab ? `!${vocab[1]}/${vocab[2]}` : `!${tag.replace(/^tag:/, '')}`; + if (!fs.existsSync(path.dirname(file))) { + common.error('no such file or directory: ' + path.dirname(file)); } - let p = doc.tagPrefixes.find(p => tag.indexOf(p.prefix) === 0); - - if (!p) { - const dtp = doc.getDefaults().tagPrefixes; - p = dtp && dtp.find(p => tag.indexOf(p.prefix) === 0); + try { + fs.writeFileSync(file, this.stdout || this.toString(), 'utf8'); + return this; + } catch (e) { + /* istanbul ignore next */ + common.error('could not write to file (code ' + e.code + '): ' + file, { continue: true }); } - - if (!p) return tag[0] === '!' ? tag : `!<${tag}>`; - const suffix = tag.substr(p.prefix.length).replace(/[!,[\]{}]/g, ch => ({ - '!': '%21', - ',': '%2C', - '[': '%5B', - ']': '%5D', - '{': '%7B', - '}': '%7D' - })[ch]); - return p.handle + suffix; } +module.exports = _to; -function getTagObject(tags, item) { - if (item instanceof resolveSeq.Alias) return resolveSeq.Alias; - - 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, obj; - - if (item instanceof resolveSeq.Scalar) { - obj = item.value; // TODO: deprecate/remove class check - const match = tags.filter(t => t.identify && t.identify(obj) || t.class && obj instanceof t.class); - 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 && obj.constructor ? obj.constructor.name : typeof obj; - throw new Error(`Tag not resolved for ${name} value`); - } +/***/ 3736: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return tagObj; -} // needs to be called before value stringifier to allow for circular anchor refs +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); +common.register('toEnd', _toEnd, { + pipeOnly: true, + wrapOutput: false, +}); -function stringifyProps(node, tagObj, { - anchors, - doc -}) { - const props = []; - const anchor = doc.anchors.getName(node); +//@ +//@ ### ShellString.prototype.toEnd(file) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ cat('input.txt').toEnd('output.txt'); +//@ ``` +//@ +//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with +//@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). +function _toEnd(options, file) { + if (!file) common.error('wrong arguments'); - if (anchor) { - anchors[anchor] = node; - props.push(`&${anchor}`); + if (!fs.existsSync(path.dirname(file))) { + common.error('no such file or directory: ' + path.dirname(file)); } - if (node.tag) { - props.push(stringifyTag(doc, node.tag)); - } else if (!tagObj.default) { - props.push(stringifyTag(doc, tagObj.tag)); + try { + fs.appendFileSync(file, this.stdout || this.toString(), 'utf8'); + return this; + } catch (e) { + /* istanbul ignore next */ + common.error('could not append to file (code ' + e.code + '): ' + file, { continue: true }); } - - return props.join(' '); } +module.exports = _toEnd; -function stringify(item, ctx, onComment, onChompKeep) { - const { - anchors, - schema - } = ctx.doc; - let tagObj; - - if (!(item instanceof resolveSeq.Node)) { - const createCtx = { - aliasNodes: [], - onTagObj: o => tagObj = o, - prevObjects: new Map() - }; - item = schema.createNode(item, true, null, createCtx); - - for (const alias of createCtx.aliasNodes) { - alias.source = alias.source.node; - let name = anchors.getName(alias.source); - if (!name) { - name = anchors.newName(); - anchors.map[name] = alias.source; - } - } - } +/***/ }), - if (item instanceof resolveSeq.Pair) return item.toString(ctx, onComment, onChompKeep); - if (!tagObj) tagObj = getTagObject(schema.tags, item); - const props = stringifyProps(item, tagObj, ctx); - if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1; - const str = typeof tagObj.stringify === 'function' ? tagObj.stringify(item, ctx, onComment, onChompKeep) : item instanceof resolveSeq.Scalar ? resolveSeq.stringifyString(item, ctx, onComment, onChompKeep) : item.toString(ctx, onComment, onChompKeep); - if (!props) return str; - return item instanceof resolveSeq.Scalar || str[0] === '{' || str[0] === '[' ? `${props} ${str}` : `${props}\n${ctx.indent}${str}`; -} +/***/ 8358: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -class Anchors { - static validAnchorNode(node) { - return node instanceof resolveSeq.Scalar || node instanceof resolveSeq.YAMLSeq || node instanceof resolveSeq.YAMLMap; - } +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); - constructor(prefix) { - PlainValue._defineProperty(this, "map", {}); +common.register('touch', _touch, { + cmdOptions: { + 'a': 'atime_only', + 'c': 'no_create', + 'd': 'date', + 'm': 'mtime_only', + 'r': 'reference', + }, +}); - this.prefix = prefix; +//@ +//@ ### touch([options,] file [, file ...]) +//@ ### touch([options,] file_array) +//@ +//@ Available options: +//@ +//@ + `-a`: Change only the access time +//@ + `-c`: Do not create any files +//@ + `-m`: Change only the modification time +//@ + `-d DATE`: Parse `DATE` and use it instead of current time +//@ + `-r FILE`: Use `FILE`'s times instead of current time +//@ +//@ Examples: +//@ +//@ ```javascript +//@ touch('source.js'); +//@ touch('-c', '/path/to/some/dir/source.js'); +//@ touch({ '-r': FILE }, '/path/to/some/dir/source.js'); +//@ ``` +//@ +//@ Update the access and modification times of each `FILE` to the current time. +//@ A `FILE` argument that does not exist is created empty, unless `-c` is supplied. +//@ This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). +function _touch(opts, files) { + if (!files) { + common.error('no files given'); + } else if (typeof files === 'string') { + files = [].slice.call(arguments, 1); + } else { + common.error('file arg should be a string file path or an Array of string file paths'); } - createAlias(node, name) { - this.setAnchor(node, name); - return new resolveSeq.Alias(node); - } + files.forEach(function (f) { + touchFile(opts, f); + }); + return ''; +} - createMergePair(...sources) { - const merge = new resolveSeq.Merge(); - merge.value.items = sources.map(s => { - if (s instanceof resolveSeq.Alias) { - if (s.source instanceof resolveSeq.YAMLMap) return s; - } else if (s instanceof resolveSeq.YAMLMap) { - return this.createAlias(s); - } +function touchFile(opts, file) { + var stat = tryStatFile(file); - throw new Error('Merge sources must be Map nodes or their Aliases'); - }); - return merge; + if (stat && stat.isDirectory()) { + // don't error just exit + return; } - getName(node) { - const { - map - } = this; - return Object.keys(map).find(a => map[a] === node); + // if the file doesn't already exist and the user has specified --no-create then + // this script is finished + if (!stat && opts.no_create) { + return; } - getNames() { - return Object.keys(this.map); - } + // open the file and then close it. this will create it if it doesn't exist but will + // not truncate the file + fs.closeSync(fs.openSync(file, 'a')); - getNode(name) { - return this.map[name]; - } + // + // Set timestamps + // - newName(prefix) { - if (!prefix) prefix = this.prefix; - const names = Object.keys(this.map); + // setup some defaults + var now = new Date(); + var mtime = opts.date || now; + var atime = opts.date || now; - for (let i = 1; true; ++i) { - const name = `${prefix}${i}`; - if (!names.includes(name)) return name; + // use reference file + if (opts.reference) { + var refStat = tryStatFile(opts.reference); + if (!refStat) { + common.error('failed to get attributess of ' + opts.reference); } - } // During parsing, map & aliases contain CST nodes + mtime = refStat.mtime; + atime = refStat.atime; + } else if (opts.date) { + mtime = opts.date; + atime = opts.date; + } + if (opts.atime_only && opts.mtime_only) { + // keep the new values of mtime and atime like GNU + } else if (opts.atime_only) { + mtime = stat.mtime; + } else if (opts.mtime_only) { + atime = stat.atime; + } - resolveNodes() { - const { - map, - _cstAliases - } = this; - Object.keys(map).forEach(a => { - map[a] = map[a].resolved; - }); + fs.utimesSync(file, atime, mtime); +} - _cstAliases.forEach(a => { - a.source = a.source.resolved; - }); +module.exports = _touch; - delete this._cstAliases; +function tryStatFile(filePath) { + try { + return common.statFollowLinks(filePath); + } catch (e) { + return null; } +} - setAnchor(node, name) { - if (node != null && !Anchors.validAnchorNode(node)) { - throw new Error('Anchors may only be set for Scalar, Seq and Map nodes'); - } - - if (name && /[\x00-\x19\s,[\]{}]/.test(name)) { - throw new Error('Anchor names must not contain whitespace or control characters'); - } - const { - map - } = this; - const prev = node && Object.keys(map).find(a => map[a] === node); +/***/ }), - if (prev) { - if (!name) { - return prev; - } else if (prev !== name) { - delete map[prev]; - map[name] = node; - } - } else { - if (!name) { - if (!node) return null; - name = this.newName(); - } +/***/ 7286: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - map[name] = node; - } +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); - return name; +// add c spaces to the left of str +function lpad(c, str) { + var res = '' + str; + if (res.length < c) { + res = Array((c - res.length) + 1).join(' ') + res; } - + return res; } -const visit = (node, tags) => { - if (node && typeof node === 'object') { - const { - tag - } = node; +common.register('uniq', _uniq, { + canReceivePipe: true, + cmdOptions: { + 'i': 'ignoreCase', + 'c': 'count', + 'd': 'duplicates', + }, +}); + +//@ +//@ ### uniq([options,] [input, [output]]) +//@ +//@ Available options: +//@ +//@ + `-i`: Ignore case while comparing +//@ + `-c`: Prefix lines by the number of occurrences +//@ + `-d`: Only print duplicate lines, one for each group of identical lines +//@ +//@ Examples: +//@ +//@ ```javascript +//@ uniq('foo.txt'); +//@ uniq('-i', 'foo.txt'); +//@ uniq('-cd', 'foo.txt', 'bar.txt'); +//@ ``` +//@ +//@ Filter adjacent matching lines from `input`. +function _uniq(options, input, output) { + // Check if this is coming from a pipe + var pipe = common.readFromPipe(); + + if (!pipe) { + if (!input) common.error('no input given'); - if (node instanceof resolveSeq.Collection) { - if (tag) tags[tag] = true; - node.items.forEach(n => visit(n, tags)); - } else if (node instanceof resolveSeq.Pair) { - visit(node.key, tags); - visit(node.value, tags); - } else if (node instanceof resolveSeq.Scalar) { - if (tag) tags[tag] = true; + if (!fs.existsSync(input)) { + common.error(input + ': No such file or directory'); + } else if (common.statFollowLinks(input).isDirectory()) { + common.error("error reading '" + input + "'"); } } + if (output && fs.existsSync(output) && common.statFollowLinks(output).isDirectory()) { + common.error(output + ': Is a directory'); + } - return tags; -}; - -const listTagNames = node => Object.keys(visit(node, {})); + var lines = (input ? fs.readFileSync(input, 'utf8') : pipe). + trimRight(). + split('\n'); -function parseContents(doc, contents) { - const comments = { - before: [], - after: [] + var compare = function (a, b) { + return options.ignoreCase ? + a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()) : + a.localeCompare(b); }; - let body = undefined; - let spaceBefore = false; - - for (const node of contents) { - if (node.valueRange) { - if (body !== undefined) { - const msg = 'Document contains trailing content not separated by a ... or --- line'; - doc.errors.push(new PlainValue.YAMLSyntaxError(node, msg)); - break; - } - - const res = resolveSeq.resolveNode(doc, node); - - if (spaceBefore) { - res.spaceBefore = true; - spaceBefore = false; - } - - body = res; - } else if (node.comment !== null) { - const cc = body === undefined ? comments.before : comments.after; - cc.push(node.comment); - } else if (node.type === PlainValue.Type.BLANK_LINE) { - spaceBefore = true; - - if (body === undefined && comments.before.length > 0 && !doc.commentBefore) { - // space-separated comments at start are parsed as document comments - doc.commentBefore = comments.before.join('\n'); - comments.before = []; - } + var uniqed = lines.reduceRight(function (res, e) { + // Perform uniq -c on the input + if (res.length === 0) { + return [{ count: 1, ln: e }]; + } else if (compare(res[0].ln, e) === 0) { + return [{ count: res[0].count + 1, ln: e }].concat(res.slice(1)); + } else { + return [{ count: 1, ln: e }].concat(res); } + }, []).filter(function (obj) { + // Do we want only duplicated objects? + return options.duplicates ? obj.count > 1 : true; + }).map(function (obj) { + // Are we tracking the counts of each line? + return (options.count ? (lpad(7, obj.count) + ' ') : '') + obj.ln; + }).join('\n') + '\n'; + + if (output) { + (new common.ShellString(uniqed)).to(output); + // if uniq writes to output, nothing is passed to the next command in the pipeline (if any) + return ''; + } else { + return uniqed; } +} - doc.contents = body || null; +module.exports = _uniq; - if (!body) { - doc.comment = comments.before.concat(comments.after).join('\n') || null; - } else { - const cb = comments.before.join('\n'); - if (cb) { - const cbNode = body instanceof resolveSeq.Collection && body.items[0] ? body.items[0] : body; - cbNode.commentBefore = cbNode.commentBefore ? `${cb}\n${cbNode.commentBefore}` : cb; - } +/***/ }), - doc.comment = comments.after.join('\n') || null; - } -} +/***/ 6478: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function resolveTagDirective({ - tagPrefixes -}, directive) { - const [handle, prefix] = directive.parameters; +var common = __nccwpck_require__(3687); +var fs = __nccwpck_require__(7147); +var path = __nccwpck_require__(1017); - if (!handle || !prefix) { - const msg = 'Insufficient parameters given for %TAG directive'; - throw new PlainValue.YAMLSemanticError(directive, msg); - } +common.register('which', _which, { + allowGlobbing: false, + cmdOptions: { + 'a': 'all', + }, +}); - if (tagPrefixes.some(p => p.handle === handle)) { - const msg = 'The %TAG directive must only be given at most once per handle in the same document.'; - throw new PlainValue.YAMLSemanticError(directive, msg); - } +// XP's system default value for `PATHEXT` system variable, just in case it's not +// set on Windows. +var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh'; - return { - handle, - prefix - }; -} +// For earlier versions of NodeJS that doesn't have a list of constants (< v6) +var FILE_EXECUTABLE_MODE = 1; -function resolveYamlDirective(doc, directive) { - let [version] = directive.parameters; - if (directive.name === 'YAML:1.0') version = '1.0'; +function isWindowsPlatform() { + return process.platform === 'win32'; +} - if (!version) { - const msg = 'Insufficient parameters given for %YAML directive'; - throw new PlainValue.YAMLSemanticError(directive, msg); - } +// Cross-platform method for splitting environment `PATH` variables +function splitPath(p) { + return p ? p.split(path.delimiter) : []; +} - if (!documentOptions[version]) { - const v0 = doc.version || doc.options.version; - const msg = `Document will be parsed as YAML ${v0} rather than YAML ${version}`; - doc.warnings.push(new PlainValue.YAMLWarning(directive, msg)); +// Tests are running all cases for this func but it stays uncovered by codecov due to unknown reason +/* istanbul ignore next */ +function isExecutable(pathName) { + try { + // TODO(node-support): replace with fs.constants.X_OK once remove support for node < v6 + fs.accessSync(pathName, FILE_EXECUTABLE_MODE); + } catch (err) { + return false; } + return true; +} - return version; +function checkPath(pathName) { + return fs.existsSync(pathName) && !common.statFollowLinks(pathName).isDirectory() + && (isWindowsPlatform() || isExecutable(pathName)); } -function parseDirectives(doc, directives, prevDoc) { - const directiveComments = []; - let hasDirectives = false; +//@ +//@ ### which(command) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var nodeExec = which('node'); +//@ ``` +//@ +//@ Searches for `command` in the system's `PATH`. On Windows, this uses the +//@ `PATHEXT` variable to append the extension if it's not already executable. +//@ Returns string containing the absolute path to `command`. +function _which(options, cmd) { + if (!cmd) common.error('must specify command'); - for (const directive of directives) { - const { - comment, - name - } = directive; + var isWindows = isWindowsPlatform(); + var pathArray = splitPath(process.env.PATH); - switch (name) { - case 'TAG': - try { - doc.tagPrefixes.push(resolveTagDirective(doc, directive)); - } catch (error) { - doc.errors.push(error); - } + var queryMatches = []; - hasDirectives = true; - break; + // No relative/absolute paths provided? + if (cmd.indexOf('/') === -1) { + // Assume that there are no extensions to append to queries (this is the + // case for unix) + var pathExtArray = ['']; + if (isWindows) { + // In case the PATHEXT variable is somehow not set (e.g. + // child_process.spawn with an empty environment), use the XP default. + var pathExtEnv = process.env.PATHEXT || XP_DEFAULT_PATHEXT; + pathExtArray = splitPath(pathExtEnv.toUpperCase()); + } - case 'YAML': - case 'YAML:1.0': - if (doc.version) { - const msg = 'The %YAML directive must only be given at most once per document.'; - doc.errors.push(new PlainValue.YAMLSemanticError(directive, msg)); - } + // Search for command in PATH + for (var k = 0; k < pathArray.length; k++) { + // already found it + if (queryMatches.length > 0 && !options.all) break; - try { - doc.version = resolveYamlDirective(doc, directive); - } catch (error) { - doc.errors.push(error); - } + var attempt = path.resolve(pathArray[k], cmd); - hasDirectives = true; - break; + if (isWindows) { + attempt = attempt.toUpperCase(); + } - default: - if (name) { - const msg = `YAML only supports %TAG and %YAML directives, and not %${name}`; - doc.warnings.push(new PlainValue.YAMLWarning(directive, msg)); + var match = attempt.match(/\.[^<>:"/\|?*.]+$/); + if (match && pathExtArray.indexOf(match[0]) >= 0) { // this is Windows-only + // The user typed a query with the file extension, like + // `which('node.exe')` + if (checkPath(attempt)) { + queryMatches.push(attempt); + break; } - + } else { // All-platforms + // Cycle through the PATHEXT array, and check each extension + // Note: the array is always [''] on Unix + for (var i = 0; i < pathExtArray.length; i++) { + var ext = pathExtArray[i]; + var newAttempt = attempt + ext; + if (checkPath(newAttempt)) { + queryMatches.push(newAttempt); + break; + } + } + } } - - if (comment) directiveComments.push(comment); + } else if (checkPath(cmd)) { // a valid absolute or relative path + queryMatches.push(path.resolve(cmd)); } - if (prevDoc && !hasDirectives && '1.1' === (doc.version || prevDoc.version || doc.options.version)) { - const copyTagPrefix = ({ - handle, - prefix - }) => ({ - handle, - prefix - }); - - doc.tagPrefixes = prevDoc.tagPrefixes.map(copyTagPrefix); - doc.version = prevDoc.version; + if (queryMatches.length > 0) { + return options.all ? queryMatches : queryMatches[0]; } - - doc.commentBefore = directiveComments.join('\n') || null; -} - -function assertCollection(contents) { - if (contents instanceof resolveSeq.Collection) return true; - throw new Error('Expected a YAML collection as document contents'); + return options.all ? [] : null; } +module.exports = _which; -class Document { - constructor(options) { - this.anchors = new Anchors(options.anchorPrefix); - this.commentBefore = null; - this.comment = null; - this.contents = null; - this.directivesEndMarker = null; - this.errors = []; - this.options = options; - this.schema = null; - this.tagPrefixes = []; - this.version = null; - this.warnings = []; - } - - add(value) { - assertCollection(this.contents); - return this.contents.add(value); - } - - addIn(path, value) { - assertCollection(this.contents); - this.contents.addIn(path, value); - } - - delete(key) { - assertCollection(this.contents); - return this.contents.delete(key); - } - - deleteIn(path) { - if (resolveSeq.isEmptyPath(path)) { - if (this.contents == null) return false; - this.contents = null; - return true; - } - - assertCollection(this.contents); - return this.contents.deleteIn(path); - } - getDefaults() { - return Document.defaults[this.version] || Document.defaults[this.options.version] || {}; - } +/***/ }), - get(key, keepScalar) { - return this.contents instanceof resolveSeq.Collection ? this.contents.get(key, keepScalar) : undefined; - } +/***/ 4294: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - getIn(path, keepScalar) { - if (resolveSeq.isEmptyPath(path)) return !keepScalar && this.contents instanceof resolveSeq.Scalar ? this.contents.value : this.contents; - return this.contents instanceof resolveSeq.Collection ? this.contents.getIn(path, keepScalar) : undefined; - } +module.exports = __nccwpck_require__(4219); - has(key) { - return this.contents instanceof resolveSeq.Collection ? this.contents.has(key) : false; - } - hasIn(path) { - if (resolveSeq.isEmptyPath(path)) return this.contents !== undefined; - return this.contents instanceof resolveSeq.Collection ? this.contents.hasIn(path) : false; - } +/***/ }), - set(key, value) { - assertCollection(this.contents); - this.contents.set(key, value); - } +/***/ 4219: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - setIn(path, value) { - if (resolveSeq.isEmptyPath(path)) this.contents = value;else { - assertCollection(this.contents); - this.contents.setIn(path, value); - } - } +"use strict"; - setSchema(id, customTags) { - if (!id && !customTags && this.schema) return; - if (typeof id === 'number') id = id.toFixed(1); - if (id === '1.0' || id === '1.1' || id === '1.2') { - if (this.version) this.version = id;else this.options.version = id; - delete this.options.schema; - } else if (id && typeof id === 'string') { - this.options.schema = id; - } +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); - if (Array.isArray(customTags)) this.options.customTags = customTags; - const opt = Object.assign({}, this.getDefaults(), this.options); - this.schema = new Schema.Schema(opt); - } - parse(node, prevDoc) { - if (this.options.keepCstNodes) this.cstNode = node; - if (this.options.keepNodeTypes) this.type = 'DOCUMENT'; - const { - directives = [], - contents = [], - directivesEndMarker, - error, - valueRange - } = node; +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; - if (error) { - if (!error.source) error.source = this; - this.errors.push(error); - } - parseDirectives(this, directives, prevDoc); - if (directivesEndMarker) this.directivesEndMarker = true; - this.range = valueRange ? [valueRange.start, valueRange.end] : null; - this.setSchema(); - this.anchors._cstAliases = []; - parseContents(this, contents); - this.anchors.resolveNodes(); +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} - if (this.options.prettyErrors) { - for (const error of this.errors) if (error instanceof PlainValue.YAMLError) error.makePretty(); +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - for (const warn of this.warnings) if (warn instanceof PlainValue.YAMLError) warn.makePretty(); - } +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} - return this; - } +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} - listNonDefaultTags() { - return listTagNames(this.contents).filter(t => t.indexOf(Schema.Schema.defaultPrefix) !== 0); - } - setTagPrefix(handle, prefix) { - if (handle[0] !== '!' || handle[handle.length - 1] !== '!') throw new Error('Handle must start and end with !'); +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 = []; - if (prefix) { - const prev = this.tagPrefixes.find(p => p.handle === handle); - if (prev) prev.prefix = prefix;else this.tagPrefixes.push({ - handle, - prefix - }); - } else { - this.tagPrefixes = this.tagPrefixes.filter(p => p.handle !== handle); + 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); - toJSON(arg, onAnchor) { - const { - keepBlobsInJSON, - mapAsMap, - maxAliasCount - } = this.options; - const keep = keepBlobsInJSON && (typeof arg !== 'string' || !(this.contents instanceof resolveSeq.Scalar)); - const ctx = { - doc: this, - indentStep: ' ', - keep, - mapAsMap: keep && !!mapAsMap, - maxAliasCount, - stringify // Requiring directly in Pair would create circular dependencies +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - }; - const anchorNames = Object.keys(this.anchors.map); - if (anchorNames.length > 0) ctx.anchors = new Map(anchorNames.map(name => [this.anchors.map[name], { - alias: [], - aliasCount: 0, - count: 1 - }])); - const res = resolveSeq.toJSON(this.contents, arg, ctx); - if (typeof onAnchor === 'function' && ctx.anchors) for (const { - count, - res - } of ctx.anchors.values()) onAnchor(res, count); - return res; + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; } - toString() { - if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); - const indentSize = this.options.indent; + // 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); - if (!Number.isInteger(indentSize) || indentSize <= 0) { - const s = JSON.stringify(indentSize); - throw new Error(`"indent" option must be a positive integer, not ${s}`); + function onFree() { + self.emit('free', socket, options); } - this.setSchema(); - const lines = []; - let hasDirectives = false; - - if (this.version) { - let vd = '%YAML 1.2'; - - if (this.schema.name === 'yaml-1.1') { - if (this.version === '1.0') vd = '%YAML:1.0';else if (this.version === '1.1') vd = '%YAML 1.1'; - } - - lines.push(vd); - hasDirectives = true; + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); } + }); +}; - const tagNames = this.listNonDefaultTags(); - this.tagPrefixes.forEach(({ - handle, - prefix - }) => { - if (tagNames.some(t => t.indexOf(prefix) === 0)) { - lines.push(`%TAG ${handle} ${prefix}`); - hasDirectives = true; - } - }); - if (hasDirectives || this.directivesEndMarker) lines.push('---'); +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); - if (this.commentBefore) { - if (hasDirectives || !this.directivesEndMarker) lines.unshift(''); - lines.unshift(this.commentBefore.replace(/^/gm, '#')); + 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'); + } - const ctx = { - anchors: {}, - doc: this, - indent: '', - indentStep: ' '.repeat(indentSize), - stringify // Requiring directly in nodes would create circular dependencies + 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(); - }; - let chompKeep = false; - let contentComment = null; + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } - if (this.contents) { - if (this.contents instanceof resolveSeq.Node) { - if (this.contents.spaceBefore && (hasDirectives || this.directivesEndMarker)) lines.push(''); - if (this.contents.commentBefore) lines.push(this.contents.commentBefore.replace(/^/gm, '#')); // top-level block scalars need to be indented if followed by a comment + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } - ctx.forceBlockIndent = !!this.comment; - contentComment = this.contents.comment; - } + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); - const onChompKeep = contentComment ? null : () => chompKeep = true; - const body = stringify(this.contents, ctx, () => contentComment = null, onChompKeep); - lines.push(resolveSeq.addComment(body, '', contentComment)); - } else if (this.contents !== undefined) { - lines.push(stringify(this.contents, ctx)); + 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 (this.comment) { - if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '') lines.push(''); - lines.push(this.comment.replace(/^/gm, '#')); + 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; } - - return lines.join('\n') + '\n'; + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); } -} - -PlainValue._defineProperty(Document, "defaults", documentOptions); - -exports.Document = Document; -exports.defaultOptions = defaultOptions; -exports.scalarOptions = scalarOptions; - - -/***/ }), - -/***/ 5215: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - + function onError(cause) { + connectReq.removeAllListeners(); -const Char = { - ANCHOR: '&', - COMMENT: '#', - TAG: '!', - DIRECTIVES_END: '-', - DOCUMENT_END: '.' -}; -const Type = { - ALIAS: 'ALIAS', - BLANK_LINE: 'BLANK_LINE', - BLOCK_FOLDED: 'BLOCK_FOLDED', - BLOCK_LITERAL: 'BLOCK_LITERAL', - COMMENT: 'COMMENT', - DIRECTIVE: 'DIRECTIVE', - DOCUMENT: 'DOCUMENT', - FLOW_MAP: 'FLOW_MAP', - FLOW_SEQ: 'FLOW_SEQ', - MAP: 'MAP', - MAP_KEY: 'MAP_KEY', - MAP_VALUE: 'MAP_VALUE', - PLAIN: 'PLAIN', - QUOTE_DOUBLE: 'QUOTE_DOUBLE', - QUOTE_SINGLE: 'QUOTE_SINGLE', - SEQ: 'SEQ', - SEQ_ITEM: 'SEQ_ITEM' -}; -const defaultTagPrefix = 'tag:yaml.org,2002:'; -const defaultTags = { - MAP: 'tag:yaml.org,2002:map', - SEQ: 'tag:yaml.org,2002:seq', - STR: 'tag:yaml.org,2002:str' + 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); + } }; -function findLineStarts(src) { - const ls = [0]; - let offset = src.indexOf('\n'); - - while (offset !== -1) { - offset += 1; - ls.push(offset); - offset = src.indexOf('\n', offset); +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; } + this.sockets.splice(pos, 1); - return ls; -} - -function getSrcInfo(cst) { - let lineStarts, src; - - if (typeof cst === 'string') { - lineStarts = findLineStarts(cst); - src = cst; - } else { - if (Array.isArray(cst)) cst = cst[0]; - - if (cst && cst.context) { - if (!cst.lineStarts) cst.lineStarts = findLineStarts(cst.context.src); - lineStarts = cst.lineStarts; - src = cst.context.src; - } + 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); + }); } +}; - return { - lineStarts, - src - }; -} -/** - * @typedef {Object} LinePos - One-indexed position in the source - * @property {number} line - * @property {number} col - */ - -/** - * Determine the line/col position matching a character offset. - * - * Accepts a source string or a CST document as the second parameter. With - * the latter, starting indices for lines are cached in the document as - * `lineStarts: number[]`. - * - * Returns a one-indexed `{ line, col }` location if found, or - * `undefined` otherwise. - * - * @param {number} offset - * @param {string|Document|Document[]} cst - * @returns {?LinePos} - */ - - -function getLinePos(offset, cst) { - if (typeof offset !== 'number' || offset < 0) return null; - const { - lineStarts, - src - } = getSrcInfo(cst); - if (!lineStarts || !src || offset > src.length) return null; +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 + }); - for (let i = 0; i < lineStarts.length; ++i) { - const start = lineStarts[i]; + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} - if (offset < start) { - return { - line: i, - col: offset - lineStarts[i - 1] + 1 - }; - } - if (offset === start) return { - line: i + 1, - col: 1 +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 +} - const line = lineStarts.length; - return { - line, - col: offset - lineStarts[line - 1] + 1 - }; -} -/** - * Get a specified line from the source. - * - * Accepts a source string or a CST document as the second parameter. With - * the latter, starting indices for lines are cached in the document as - * `lineStarts: number[]`. - * - * Returns the line as a string if found, or `null` otherwise. - * - * @param {number} line One-indexed line number - * @param {string|Document|Document[]} cst - * @returns {?string} - */ - -function getLine(line, cst) { - const { - lineStarts, - src - } = getSrcInfo(cst); - if (!lineStarts || !(line >= 1) || line > lineStarts.length) return null; - const start = lineStarts[line - 1]; - let end = lineStarts[line]; // undefined for last line; that's ok for slice() - - while (end && end > start && src[end - 1] === '\n') --end; - - return src.slice(start, end); -} -/** - * Pretty-print the starting line from the source indicated by the range `pos` - * - * Trims output to `maxWidth` chars while keeping the starting column visible, - * using `…` at either end to indicate dropped characters. - * - * Returns a two-line string (or `null`) with `\n` as separator; the second line - * will hold appropriately indented `^` marks indicating the column range. - * - * @param {Object} pos - * @param {LinePos} pos.start - * @param {LinePos} [pos.end] - * @param {string|Document|Document[]*} cst - * @param {number} [maxWidth=80] - * @returns {?string} - */ - -function getPrettyContext({ - start, - end -}, cst, maxWidth = 80) { - let src = getLine(start.line, cst); - if (!src) return null; - let { - col - } = start; - - if (src.length > maxWidth) { - if (col <= maxWidth - 10) { - src = src.substr(0, maxWidth - 1) + '…'; - } else { - const halfWidth = Math.round(maxWidth / 2); - if (src.length > col + halfWidth) src = src.substr(0, col + halfWidth - 1) + '…'; - col -= src.length - maxWidth; - src = '…' + src.substr(1 - maxWidth); +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; +} - let errLen = 1; - let errEnd = ''; - if (end) { - if (end.line === start.line && col + (end.col - start.col) <= maxWidth + 1) { - errLen = end.col - start.col; +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 { - errLen = Math.min(src.length + 1, maxWidth) - col; - errEnd = '…'; + args.unshift('TUNNEL:'); } + console.error.apply(console, args); } - - const offset = col > 1 ? ' '.repeat(col - 1) : ''; - const err = '^'.repeat(errLen); - return `${src}\n${offset}${err}${errEnd}`; +} else { + debug = function() {}; } +exports.debug = debug; // for test -class Range { - static copy(orig) { - return new Range(orig.start, orig.end); - } - constructor(start, end) { - this.start = start; - this.end = end || start; - } +/***/ }), + +/***/ 5840: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + - isEmpty() { - return typeof this.start !== 'number' || !this.end || this.end <= this.start; +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; } - /** - * Set `origStart` and `origEnd` to point to the original source range for - * this node, which may differ due to dropped CR characters. - * - * @param {number[]} cr - Positions of dropped CR characters - * @param {number} offset - Starting index of `cr` from the last call - * @returns {number} - The next offset, matching the one found for `origStart` - */ +})); +var _v = _interopRequireDefault(__nccwpck_require__(8628)); - setOrigRange(cr, offset) { - const { - start, - end - } = this; +var _v2 = _interopRequireDefault(__nccwpck_require__(6409)); - if (cr.length === 0 || end <= cr[0]) { - this.origStart = start; - this.origEnd = end; - return offset; - } +var _v3 = _interopRequireDefault(__nccwpck_require__(5122)); - let i = offset; +var _v4 = _interopRequireDefault(__nccwpck_require__(9120)); - while (i < cr.length) { - if (cr[i] > start) break;else ++i; - } +var _nil = _interopRequireDefault(__nccwpck_require__(5332)); - this.origStart = start + i; - const nextOffset = i; +var _version = _interopRequireDefault(__nccwpck_require__(1595)); - while (i < cr.length) { - // if end was at \n, it should now be at \r - if (cr[i] >= end) break;else ++i; - } +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - this.origEnd = end + i; - return nextOffset; - } +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); -} +var _parse = _interopRequireDefault(__nccwpck_require__(2746)); -/** Root class of all nodes */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class Node { - static addStringTerminator(src, offset, str) { - if (str[str.length - 1] === '\n') return str; - const next = Node.endOfWhiteSpace(src, offset); - return next >= src.length || src[next] === '\n' ? str + '\n' : str; - } // ^(---|...) +/***/ }), +/***/ 4569: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - static atDocumentBoundary(src, offset, sep) { - const ch0 = src[offset]; - if (!ch0) return true; - const prev = src[offset - 1]; - if (prev && prev !== '\n') return false; +"use strict"; - if (sep) { - if (ch0 !== sep) return false; - } else { - if (ch0 !== Char.DIRECTIVES_END && ch0 !== Char.DOCUMENT_END) return false; - } - const ch1 = src[offset + 1]; - const ch2 = src[offset + 2]; - if (ch1 !== ch0 || ch2 !== ch0) return false; - const ch3 = src[offset + 3]; - return !ch3 || ch3 === '\n' || ch3 === '\t' || ch3 === ' '; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - static endOfIdentifier(src, offset) { - let ch = src[offset]; - const isVerbatim = ch === '<'; - const notOk = isVerbatim ? ['\n', '\t', ' ', '>'] : ['\n', '\t', ' ', '[', ']', '{', '}', ',']; +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - while (ch && notOk.indexOf(ch) === -1) ch = src[offset += 1]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (isVerbatim && ch === '>') offset += 1; - return offset; +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); } - static endOfIndent(src, offset) { - let ch = src[offset]; + return _crypto.default.createHash('md5').update(bytes).digest(); +} - while (ch === ' ') ch = src[offset += 1]; +var _default = md5; +exports["default"] = _default; - return offset; - } +/***/ }), - static endOfLine(src, offset) { - let ch = src[offset]; +/***/ 5332: +/***/ ((__unused_webpack_module, exports) => { - while (ch && ch !== '\n') ch = src[offset += 1]; +"use strict"; - return offset; - } - static endOfWhiteSpace(src, offset) { - let ch = src[offset]; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports["default"] = _default; - while (ch === '\t' || ch === ' ') ch = src[offset += 1]; +/***/ }), - return offset; - } +/***/ 2746: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - static startOfLine(src, offset) { - let ch = src[offset - 1]; - if (ch === '\n') return offset; +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - while (ch && ch !== '\n') ch = src[offset -= 1]; +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - return offset + 1; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); } - /** - * End of indentation, or null if the line's indent level is not more - * than `indent` - * - * @param {string} src - * @param {number} indent - * @param {number} lineStart - * @returns {?number} - */ + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - static endOfBlockIndent(src, indent, lineStart) { - const inEnd = Node.endOfIndent(src, lineStart); + 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 ........-####-....-....-............ - if (inEnd > lineStart + indent) { - return inEnd; - } else { - const wsEnd = Node.endOfWhiteSpace(src, inEnd); - const ch = src[wsEnd]; - if (!ch || ch === '\n') return wsEnd; - } + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ - return null; - } + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ - static atBlank(src, offset, endAsBlank) { - const ch = src[offset]; - return ch === '\n' || ch === '\t' || ch === ' ' || endAsBlank && !ch; - } + 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) - static nextNodeIsIndented(ch, indentDiff, indicatorAsIndent) { - if (!ch || indentDiff < 0) return false; - if (indentDiff > 0) return true; - return indicatorAsIndent && ch === '-'; - } // should be at line or string end, or at next non-whitespace char + 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; - static normalizeOffset(src, offset) { - const ch = src[offset]; - return !ch ? offset : ch !== '\n' && src[offset - 1] === '\n' ? offset - 1 : Node.endOfWhiteSpace(src, offset); - } // fold single newline into space, multiple newlines to N - 1 newlines - // presumes src[offset] === '\n' +/***/ }), +/***/ 814: +/***/ ((__unused_webpack_module, exports) => { - static foldNewline(src, offset, indent) { - let inCount = 0; - let error = false; - let fold = ''; - let ch = src[offset + 1]; +"use strict"; - while (ch === ' ' || ch === '\t' || ch === '\n') { - switch (ch) { - case '\n': - inCount = 0; - offset += 1; - fold += '\n'; - break; - case '\t': - if (inCount <= indent) error = true; - offset = Node.endOfWhiteSpace(src, offset + 2) - 1; - break; +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; - case ' ': - inCount += 1; - offset += 1; - break; - } +/***/ }), - ch = src[offset + 1]; - } +/***/ 807: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!fold) fold = ' '; - if (ch && inCount <= indent) error = true; - return { - fold, - offset, - error - }; - } +"use strict"; - constructor(type, props, context) { - Object.defineProperty(this, 'context', { - value: context || null, - writable: true - }); - this.error = null; - this.range = null; - this.valueRange = null; - this.props = props || []; - this.type = type; - this.value = null; - } - getPropValue(idx, key, skipKey) { - if (!this.context) return null; - const { - src - } = this.context; - const prop = this.props[idx]; - return prop && src[prop.start] === key ? src.slice(prop.start + (skipKey ? 1 : 0), prop.end) : null; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; - get anchor() { - for (let i = 0; i < this.props.length; ++i) { - const anchor = this.getPropValue(i, Char.ANCHOR, true); - if (anchor != null) return anchor; - } +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - return null; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - get comment() { - const comments = []; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - for (let i = 0; i < this.props.length; ++i) { - const comment = this.getPropValue(i, Char.COMMENT, true); - if (comment != null) comments.push(comment); - } +let poolPtr = rnds8Pool.length; - return comments.length > 0 ? comments.join('\n') : null; - } +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); - commentHasRequiredWhitespace(start) { - const { - src - } = this.context; - if (this.header && start === this.header.end) return false; - if (!this.valueRange) return false; - const { - end - } = this.valueRange; - return start !== end || Node.atBlank(src, end - 1); + poolPtr = 0; } - get hasComment() { - if (this.context) { - const { - src - } = this.context; + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} - for (let i = 0; i < this.props.length; ++i) { - if (src[this.props[i].start] === Char.COMMENT) return true; - } - } +/***/ }), - return false; - } +/***/ 5274: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get hasProps() { - if (this.context) { - const { - src - } = this.context; +"use strict"; - for (let i = 0; i < this.props.length; ++i) { - if (src[this.props[i].start] !== Char.COMMENT) return true; - } - } - return false; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - get includesTrailingLines() { - return false; - } +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - get jsonLike() { - const jsonLikeTypes = [Type.FLOW_MAP, Type.FLOW_SEQ, Type.QUOTE_DOUBLE, Type.QUOTE_SINGLE]; - return jsonLikeTypes.indexOf(this.type) !== -1; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - get rangeAsLinePos() { - if (!this.range || !this.context) return undefined; - const start = getLinePos(this.range.start, this.context.root); - if (!start) return undefined; - const end = getLinePos(this.range.end, this.context.root); - return { - start, - end - }; +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); } - get rawValue() { - if (!this.valueRange || !this.context) return null; - const { - start, - end - } = this.valueRange; - return this.context.src.slice(start, end); - } + return _crypto.default.createHash('sha1').update(bytes).digest(); +} - get tag() { - for (let i = 0; i < this.props.length; ++i) { - const tag = this.getPropValue(i, Char.TAG, false); +var _default = sha1; +exports["default"] = _default; - if (tag != null) { - if (tag[1] === '<') { - return { - verbatim: tag.slice(2, -1) - }; - } else { - // eslint-disable-next-line no-unused-vars - const [_, handle, suffix] = tag.match(/^(.*!)([^!]*)$/); - return { - handle, - suffix - }; - } - } - } +/***/ }), - return null; - } +/***/ 8950: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get valueRangeContainsNewline() { - if (!this.valueRange || !this.context) return false; - const { - start, - end - } = this.valueRange; - const { - src - } = this.context; +"use strict"; - for (let i = start; i < end; ++i) { - if (src[i] === '\n') return true; - } - return false; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - parseComment(start) { - const { - src - } = this.context; +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - if (src[start] === Char.COMMENT) { - const end = Node.endOfLine(src, start + 1); - const commentRange = new Range(start, end); - this.props.push(commentRange); - return end; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return start; - } - /** - * Populates the `origStart` and `origEnd` values of all ranges for this - * node. Extended by child classes to handle descendant nodes. - * - * @param {number[]} cr - Positions of dropped CR characters - * @param {number} offset - Starting index of `cr` from the last call - * @returns {number} - The next offset, matching the one found for `origStart` - */ +/** + * 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)); +} - setOrigRanges(cr, offset) { - if (this.range) offset = this.range.setOrigRange(cr, offset); - if (this.valueRange) this.valueRange.setOrigRange(cr, offset); - this.props.forEach(prop => prop.setOrigRange(cr, offset)); - return offset; - } +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 - toString() { - const { - context: { - src - }, - range, - value - } = this; - if (value != null) return value; - const str = src.slice(range.start, range.end); - return Node.addStringTerminator(src, range.end, str); + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); } + return uuid; } -class YAMLError extends Error { - constructor(name, source, message) { - if (!message || !(source instanceof Node)) throw new Error(`Invalid arguments for new ${name}`); - super(); - this.name = name; - this.message = message; - this.source = source; - } - - makePretty() { - if (!this.source) return; - this.nodeType = this.source.type; - const cst = this.source.context && this.source.context.root; - - if (typeof this.offset === 'number') { - this.range = new Range(this.offset, this.offset + 1); - const start = cst && getLinePos(this.offset, cst); - - if (start) { - const end = { - line: start.line, - col: start.col + 1 - }; - this.linePos = { - start, - end - }; - } +var _default = stringify; +exports["default"] = _default; - delete this.offset; - } else { - this.range = this.source.range; - this.linePos = this.source.rangeAsLinePos; - } +/***/ }), - if (this.linePos) { - const { - line, - col - } = this.linePos.start; - this.message += ` at line ${line}, column ${col}`; - const ctx = cst && getPrettyContext(this.linePos, cst); - if (ctx) this.message += `:\n\n${ctx}\n`; - } +/***/ 8628: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - delete this.source; - } +"use strict"; -} -class YAMLReferenceError extends YAMLError { - constructor(source, message) { - super('YAMLReferenceError', source, message); - } -} -class YAMLSemanticError extends YAMLError { - constructor(source, message) { - super('YAMLSemanticError', source, message); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -} -class YAMLSyntaxError extends YAMLError { - constructor(source, message) { - super('YAMLSyntaxError', source, message); - } +var _rng = _interopRequireDefault(__nccwpck_require__(807)); -} -class YAMLWarning extends YAMLError { - constructor(source, message) { - super('YAMLWarning', source, message); - } +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; - return obj; -} +let _clockseq; // Previous uuid creation time -class PlainValue extends Node { - static endOfLine(src, start, inFlow) { - let ch = src[start]; - let offset = start; - while (ch && ch !== '\n') { - if (inFlow && (ch === '[' || ch === ']' || ch === '{' || ch === '}' || ch === ',')) break; - const next = src[offset + 1]; - if (ch === ':' && (!next || next === '\n' || next === '\t' || next === ' ' || inFlow && next === ',')) break; - if ((ch === ' ' || ch === '\t') && next === '#') break; - offset += 1; - ch = next; - } +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - return offset; - } +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 - get strValue() { - if (!this.valueRange || !this.context) return null; - let { - start, - end - } = this.valueRange; - const { - src - } = this.context; - let ch = src[end - 1]; + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); - while (start < end && (ch === '\n' || ch === '\t' || ch === ' ')) ch = src[--end - 1]; + 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]]; + } - let str = ''; + 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. - for (let i = start; i < end; ++i) { - const ch = src[i]; - if (ch === '\n') { - const { - fold, - offset - } = Node.foldNewline(src, i, -1); - str += fold; - i = offset; - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - const wsStart = i; - let next = src[i + 1]; + 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 - while (i < end && (next === ' ' || next === '\t')) { - i += 1; - next = src[i + 1]; - } + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - const ch0 = src[start]; + 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 - switch (ch0) { - case '\t': - { - const msg = 'Plain value cannot start with a tab character'; - const errors = [new YAMLSemanticError(this, msg)]; - return { - errors, - str - }; - } - case '@': - case '`': - { - const msg = `Plain value cannot start with reserved character ${ch0}`; - const errors = [new YAMLSemanticError(this, msg)]; - return { - errors, - str - }; - } + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested - default: - return str; - } + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } - parseBlockValue(start) { - const { - indent, - inFlow, - src - } = this.context; - let offset = start; - let valueEnd = start; + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { - if (Node.atDocumentBoundary(src, offset + 1)) break; - const end = Node.endOfBlockIndent(src, indent, offset + 1); - if (end === null || src[end] === '#') break; + msecs += 12219292800000; // `time_low` - if (src[end] === '\n') { - offset = end; - } else { - valueEnd = PlainValue.endOfLine(src, end, inFlow); - offset = valueEnd; - } - } + 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` - if (this.valueRange.isEmpty()) this.valueRange.start = start; - this.valueRange.end = valueEnd; - return valueEnd; - } - /** - * Parses a plain value from the source - * - * Accepted forms are: - * ``` - * #comment - * - * first line - * - * first line #comment - * - * first line - * block - * lines - * - * #comment - * block - * lines - * ``` - * where block lines are empty or have an indent level greater than `indent`. - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar, may be `\n` - */ - - - parse(context, start) { - this.context = context; - const { - inFlow, - src - } = context; - let offset = start; - const ch = src[offset]; - - if (ch && ch !== '#' && ch !== '\n') { - offset = PlainValue.endOfLine(src, start, inFlow); - } - - this.valueRange = new Range(start, offset); - offset = Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - - if (!this.hasComment || this.valueRange.isEmpty()) { - offset = this.parseBlockValue(offset); - } + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` - return offset; + 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); } -exports.Char = Char; -exports.Node = Node; -exports.PlainValue = PlainValue; -exports.Range = Range; -exports.Type = Type; -exports.YAMLError = YAMLError; -exports.YAMLReferenceError = YAMLReferenceError; -exports.YAMLSemanticError = YAMLSemanticError; -exports.YAMLSyntaxError = YAMLSyntaxError; -exports.YAMLWarning = YAMLWarning; -exports._defineProperty = _defineProperty; -exports.defaultTagPrefix = defaultTagPrefix; -exports.defaultTags = defaultTags; - +var _default = v1; +exports["default"] = _default; /***/ }), -/***/ 3656: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 6409: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var PlainValue = __webpack_require__(5215); -var resolveSeq = __webpack_require__(6140); -var warnings = __webpack_require__(7383); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -function createMap(schema, obj, ctx) { - const map = new resolveSeq.YAMLMap(schema); +var _v = _interopRequireDefault(__nccwpck_require__(5998)); - if (obj instanceof Map) { - for (const [key, value] of obj) map.items.push(schema.createPair(key, value, ctx)); - } else if (obj && typeof obj === 'object') { - for (const key of Object.keys(obj)) map.items.push(schema.createPair(key, obj[key], ctx)); - } +var _md = _interopRequireDefault(__nccwpck_require__(4569)); - if (typeof schema.sortMapEntries === 'function') { - map.items.sort(schema.sortMapEntries); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return map; -} +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports["default"] = _default; -const map = { - createNode: createMap, - default: true, - nodeClass: resolveSeq.YAMLMap, - tag: 'tag:yaml.org,2002:map', - resolve: resolveSeq.resolveMap -}; +/***/ }), -function createSeq(schema, obj, ctx) { - const seq = new resolveSeq.YAMLSeq(schema); +/***/ 5998: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (obj && obj[Symbol.iterator]) { - for (const it of obj) { - const v = schema.createNode(it, ctx.wrapScalars, null, ctx); - seq.items.push(v); - } - } +"use strict"; - return seq; -} -const seq = { - createNode: createSeq, - default: true, - nodeClass: resolveSeq.YAMLSeq, - tag: 'tag:yaml.org,2002:seq', - resolve: resolveSeq.resolveSeq -}; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = _default; +exports.URL = exports.DNS = void 0; -const string = { - identify: value => typeof value === 'string', - default: true, - tag: 'tag:yaml.org,2002:str', - resolve: resolveSeq.resolveString, - - stringify(item, ctx, onComment, onChompKeep) { - ctx = Object.assign({ - actualString: true - }, ctx); - return resolveSeq.stringifyString(item, ctx, onComment, onChompKeep); - }, +var _stringify = _interopRequireDefault(__nccwpck_require__(8950)); - options: resolveSeq.strOptions -}; +var _parse = _interopRequireDefault(__nccwpck_require__(2746)); -const failsafe = [map, seq, string]; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/* global BigInt */ +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape -const intIdentify = value => typeof value === 'bigint' || Number.isInteger(value); + const bytes = []; -const intResolve = (src, part, radix) => resolveSeq.intOptions.asBigInt ? BigInt(src) : parseInt(part, radix); + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } -function intStringify(node, radix, prefix) { - const { - value - } = node; - if (intIdentify(value) && value >= 0) return prefix + value.toString(radix); - return resolveSeq.stringifyNumber(node); -} - -const nullObj = { - identify: value => value == null, - createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: () => null, - options: resolveSeq.nullOptions, - stringify: () => resolveSeq.nullOptions.nullStr -}; -const boolObj = { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, - resolve: str => str[0] === 't' || str[0] === 'T', - options: resolveSeq.boolOptions, - stringify: ({ - value - }) => value ? resolveSeq.boolOptions.trueStr : resolveSeq.boolOptions.falseStr -}; -const octObj = { - identify: value => intIdentify(value) && value >= 0, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'OCT', - test: /^0o([0-7]+)$/, - resolve: (str, oct) => intResolve(str, oct, 8), - options: resolveSeq.intOptions, - stringify: node => intStringify(node, 8, '0o') -}; -const intObj = { - identify: intIdentify, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^[-+]?[0-9]+$/, - resolve: str => intResolve(str, str, 10), - options: resolveSeq.intOptions, - stringify: resolveSeq.stringifyNumber -}; -const hexObj = { - identify: value => intIdentify(value) && value >= 0, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'HEX', - test: /^0x([0-9a-fA-F]+)$/, - resolve: (str, hex) => intResolve(str, hex, 16), - options: resolveSeq.intOptions, - stringify: node => intStringify(node, 16, '0x') -}; -const nanObj = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^(?:[-+]?\.inf|(\.nan))$/i, - resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - stringify: resolveSeq.stringifyNumber -}; -const expObj = { - 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: ({ - value - }) => Number(value).toExponential() -}; -const floatObj = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/, - - resolve(str, frac1, frac2) { - const frac = frac1 || frac2; - const node = new resolveSeq.Scalar(parseFloat(str)); - if (frac && frac[frac.length - 1] === '0') node.minFractionDigits = frac.length; - return node; - }, + return bytes; +} - stringify: resolveSeq.stringifyNumber -}; -const core = failsafe.concat([nullObj, boolObj, octObj, intObj, hexObj, nanObj, expObj, floatObj]); - -/* global BigInt */ - -const intIdentify$1 = value => typeof value === 'bigint' || Number.isInteger(value); - -const stringifyJSON = ({ - value -}) => JSON.stringify(value); - -const json = [map, seq, { - identify: value => typeof value === 'string', - default: true, - tag: 'tag:yaml.org,2002:str', - resolve: resolveSeq.resolveString, - stringify: stringifyJSON -}, { - identify: value => value == null, - createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : 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$1, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^-?(?:0|[1-9][0-9]*)$/, - resolve: str => resolveSeq.intOptions.asBigInt ? BigInt(str) : parseInt(str, 10), - stringify: ({ - value - }) => intIdentify$1(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 -}]; - -json.scalarFallback = str => { - throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(str)}`); -}; +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); + } -/* global BigInt */ + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } -const boolStringify = ({ - value -}) => value ? resolveSeq.boolOptions.trueStr : resolveSeq.boolOptions.falseStr; + 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])` -const intIdentify$2 = value => typeof value === 'bigint' || Number.isInteger(value); -function intResolve$1(sign, src, radix) { - let str = src.replace(/_/g, ''); + 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 (resolveSeq.intOptions.asBigInt) { - switch (radix) { - case 2: - str = `0b${str}`; - break; + if (buf) { + offset = offset || 0; - case 8: - str = `0o${str}`; - break; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } - case 16: - str = `0x${str}`; - break; + return buf; } - const n = BigInt(str); - return sign === '-' ? BigInt(-1) * n : n; - } - - const n = parseInt(str, radix); - return sign === '-' ? -1 * n : n; -} - -function intStringify$1(node, radix, prefix) { - const { - value - } = node; - - if (intIdentify$2(value)) { - const str = value.toString(radix); - return value < 0 ? '-' + prefix + str.substr(1) : prefix + str; - } - - return resolveSeq.stringifyNumber(node); -} - -const yaml11 = failsafe.concat([{ - identify: value => value == null, - createNode: (schema, value, ctx) => ctx.wrapScalars ? new resolveSeq.Scalar(null) : null, - default: true, - tag: 'tag:yaml.org,2002:null', - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: () => null, - options: resolveSeq.nullOptions, - stringify: () => resolveSeq.nullOptions.nullStr -}, { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, - resolve: () => true, - options: resolveSeq.boolOptions, - stringify: boolStringify -}, { - identify: value => typeof value === 'boolean', - default: true, - tag: 'tag:yaml.org,2002:bool', - test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i, - resolve: () => false, - options: resolveSeq.boolOptions, - stringify: boolStringify -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'BIN', - test: /^([-+]?)0b([0-1_]+)$/, - resolve: (str, sign, bin) => intResolve$1(sign, bin, 2), - stringify: node => intStringify$1(node, 2, '0b') -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'OCT', - test: /^([-+]?)0([0-7_]+)$/, - resolve: (str, sign, oct) => intResolve$1(sign, oct, 8), - stringify: node => intStringify$1(node, 8, '0') -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - test: /^([-+]?)([0-9][0-9_]*)$/, - resolve: (str, sign, abs) => intResolve$1(sign, abs, 10), - stringify: resolveSeq.stringifyNumber -}, { - identify: intIdentify$2, - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'HEX', - test: /^([-+]?)0x([0-9a-fA-F_]+)$/, - resolve: (str, sign, hex) => intResolve$1(sign, hex, 16), - stringify: node => intStringify$1(node, 16, '0x') -}, { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^(?:[-+]?\.inf|(\.nan))$/i, - resolve: (str, nan) => nan ? NaN : str[0] === '-' ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - stringify: resolveSeq.stringifyNumber -}, { - 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: ({ - value - }) => Number(value).toExponential() -}, { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:float', - test: /^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/, - - resolve(str, frac) { - const node = new resolveSeq.Scalar(parseFloat(str.replace(/_/g, ''))); - - if (frac) { - const f = frac.replace(/_/g, ''); - if (f[f.length - 1] === '0') node.minFractionDigits = f.length; - } + return (0, _stringify.default)(bytes); + } // Function#name is not settable on some platforms (#270) - return node; - }, - stringify: resolveSeq.stringifyNumber -}], warnings.binary, warnings.omap, warnings.pairs, warnings.set, warnings.intTime, warnings.floatTime, warnings.timestamp); + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support -const schemas = { - core, - failsafe, - json, - yaml11 -}; -const tags = { - binary: warnings.binary, - bool: boolObj, - float: floatObj, - floatExp: expObj, - floatNaN: nanObj, - floatTime: warnings.floatTime, - int: intObj, - intHex: hexObj, - intOct: octObj, - intTime: warnings.intTime, - map, - null: nullObj, - omap: warnings.omap, - pairs: warnings.pairs, - seq, - set: warnings.set, - timestamp: warnings.timestamp -}; -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; - } // TODO: deprecate/remove class check + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} +/***/ }), - return tags.find(t => (t.identify && t.identify(value) || t.class && value instanceof t.class) && !t.format); -} +/***/ 5122: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function createNode(value, tagName, ctx) { - if (value instanceof resolveSeq.Node) return value; - const { - defaultPrefix, - onTagObj, - prevObjects, - schema, - wrapScalars - } = ctx; - if (tagName && tagName.startsWith('!!')) tagName = defaultPrefix + tagName.slice(2); - let tagObj = findTagObject(value, tagName, schema.tags); +"use strict"; - if (!tagObj) { - if (typeof value.toJSON === 'function') value = value.toJSON(); - if (typeof value !== 'object') return wrapScalars ? new resolveSeq.Scalar(value) : value; - tagObj = value instanceof Map ? map : value[Symbol.iterator] ? seq : map; - } - if (onTagObj) { - onTagObj(tagObj); - delete ctx.onTagObj; - } // Detect duplicate references to the same object & use Alias nodes for all - // after first. The `obj` wrapper allows for circular references to resolve. +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 obj = {}; + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - if (value && typeof value === 'object' && prevObjects) { - const prev = prevObjects.get(value); - if (prev) { - const alias = new resolveSeq.Alias(prev); // leaves source dirty; must be cleaned by caller + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - ctx.aliasNodes.push(alias); // defined along with prevObjects + if (buf) { + offset = offset || 0; - return alias; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; } - obj.value = value; - prevObjects.set(value, obj); + return buf; } - obj.node = tagObj.createNode ? tagObj.createNode(ctx.schema, value, ctx) : wrapScalars ? new resolveSeq.Scalar(value) : value; - if (tagName && obj.node instanceof resolveSeq.Node) obj.node.tag = tagName; - return obj.node; + return (0, _stringify.default)(rnds); } -function getSchemaTags(schemas, knownTags, customTags, schemaId) { - let tags = schemas[schemaId.replace(/\W/g, '')]; // 'yaml-1.1' -> 'yaml11' +var _default = v4; +exports["default"] = _default; - if (!tags) { - const keys = Object.keys(schemas).map(key => JSON.stringify(key)).join(', '); - throw new Error(`Unknown schema "${schemaId}"; use one of ${keys}`); - } +/***/ }), - if (Array.isArray(customTags)) { - for (const tag of customTags) tags = tags.concat(tag); - } else if (typeof customTags === 'function') { - tags = customTags(tags.slice()); - } +/***/ 9120: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - for (let i = 0; i < tags.length; ++i) { - const tag = tags[i]; +var _v = _interopRequireDefault(__nccwpck_require__(5998)); - if (typeof tag === 'string') { - const tagObj = knownTags[tag]; +var _sha = _interopRequireDefault(__nccwpck_require__(5274)); - if (!tagObj) { - const keys = Object.keys(knownTags).map(key => JSON.stringify(key)).join(', '); - throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - tags[i] = tagObj; - } - } +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports["default"] = _default; - return tags; -} +/***/ }), -const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +/***/ 6900: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -class Schema { - // TODO: remove in v2 - // TODO: remove in v2 - constructor({ - customTags, - merge, - schema, - sortMapEntries, - tags: deprecatedCustomTags - }) { - this.merge = !!merge; - this.name = schema; - this.sortMapEntries = sortMapEntries === true ? sortMapEntriesByKey : sortMapEntries || null; - if (!customTags && deprecatedCustomTags) warnings.warnOptionDeprecation('tags', 'customTags'); - this.tags = getSchemaTags(schemas, tags, customTags || deprecatedCustomTags, schema); - } - - createNode(value, wrapScalars, tagName, ctx) { - const baseCtx = { - defaultPrefix: Schema.defaultPrefix, - schema: this, - wrapScalars - }; - const createCtx = ctx ? Object.assign(ctx, baseCtx) : baseCtx; - return createNode(value, tagName, createCtx); - } +"use strict"; - createPair(key, value, ctx) { - if (!ctx) ctx = { - wrapScalars: true - }; - const k = this.createNode(key, ctx.wrapScalars, null, ctx); - const v = this.createNode(value, ctx.wrapScalars, null, ctx); - return new resolveSeq.Pair(k, v); - } -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -PlainValue._defineProperty(Schema, "defaultPrefix", PlainValue.defaultTagPrefix); +var _regex = _interopRequireDefault(__nccwpck_require__(814)); -PlainValue._defineProperty(Schema, "defaultTags", PlainValue.defaultTags); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -exports.Schema = Schema; +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} +var _default = validate; +exports["default"] = _default; /***/ }), -/***/ 5065: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 1595: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var PlainValue = __webpack_require__(5215); -var parseCst = __webpack_require__(445); -__webpack_require__(6140); -var Document$1 = __webpack_require__(1983); -var Schema = __webpack_require__(3656); -var warnings = __webpack_require__(7383); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -function createNode(value, wrapScalars = true, tag) { - if (tag === undefined && typeof wrapScalars === 'string') { - tag = wrapScalars; - wrapScalars = true; - } +var _validate = _interopRequireDefault(__nccwpck_require__(6900)); - const options = Object.assign({}, Document$1.Document.defaults[Document$1.defaultOptions.version], Document$1.defaultOptions); - const schema = new Schema.Schema(options); - return schema.createNode(value, wrapScalars, tag); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class Document extends Document$1.Document { - constructor(options) { - super(Object.assign({}, Document$1.defaultOptions, options)); +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); } + return parseInt(uuid.substr(14, 1), 16); } -function parseAllDocuments(src, options) { - const stream = []; - let prev; +var _default = version; +exports["default"] = _default; - for (const cstDoc of parseCst.parse(src)) { - const doc = new Document(options); - doc.parse(cstDoc, prev); - stream.push(doc); - prev = doc; - } +/***/ }), - return stream; -} +/***/ 2940: +/***/ ((module) => { -function parseDocument(src, options) { - const cst = parseCst.parse(src); - const doc = new Document(options).parse(cst[0]); +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) - if (cst.length > 1) { - const errMsg = 'Source contains multiple documents; please use YAML.parseAllDocuments()'; - doc.errors.unshift(new PlainValue.YAMLSemanticError(cst[1], errMsg)); - } + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') - return doc; -} + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) -function parse(src, options) { - const doc = parseDocument(src, options); - doc.warnings.forEach(warning => warnings.warn(warning)); - if (doc.errors.length > 0) throw doc.errors[0]; - return doc.toJSON(); -} + return wrapper -function stringify(value, options) { - const doc = new Document(options); - doc.contents = value; - return String(doc); + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } } -const YAML = { - createNode, - defaultOptions: Document$1.defaultOptions, - Document, - parse, - parseAllDocuments, - parseCST: parseCst.parse, - parseDocument, - scalarOptions: Document$1.scalarOptions, - stringify -}; - -exports.YAML = YAML; - /***/ }), -/***/ 445: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 9491: +/***/ ((module) => { "use strict"; +module.exports = require("assert"); +/***/ }), -var PlainValue = __webpack_require__(5215); +/***/ 2081: +/***/ ((module) => { -class BlankLine extends PlainValue.Node { - constructor() { - super(PlainValue.Type.BLANK_LINE); - } - /* istanbul ignore next */ +"use strict"; +module.exports = require("child_process"); +/***/ }), - get includesTrailingLines() { - // This is never called from anywhere, but if it were, - // this is the value it should return. - return true; - } - /** - * Parses a blank line from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first \n character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - this.range = new PlainValue.Range(start, start + 1); - return start + 1; - } - -} - -class CollectionItem extends PlainValue.Node { - constructor(type, props) { - super(type, props); - this.node = null; - } - - get includesTrailingLines() { - return !!this.node && this.node.includesTrailingLines; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - const { - parseNode, - src - } = context; - let { - atLineStart, - lineStart - } = context; - if (!atLineStart && this.type === PlainValue.Type.SEQ_ITEM) this.error = new PlainValue.YAMLSemanticError(this, 'Sequence items must not have preceding content on the same line'); - const indent = atLineStart ? start - lineStart : context.indent; - let offset = PlainValue.Node.endOfWhiteSpace(src, start + 1); - let ch = src[offset]; - const inlineComment = ch === '#'; - const comments = []; - let blankLine = null; - - while (ch === '\n' || ch === '#') { - if (ch === '#') { - const end = PlainValue.Node.endOfLine(src, offset + 1); - comments.push(new PlainValue.Range(offset, end)); - offset = end; - } else { - atLineStart = true; - lineStart = offset + 1; - const wsEnd = PlainValue.Node.endOfWhiteSpace(src, lineStart); +/***/ 6113: +/***/ ((module) => { - if (src[wsEnd] === '\n' && comments.length === 0) { - blankLine = new BlankLine(); - lineStart = blankLine.parse({ - src - }, lineStart); - } +"use strict"; +module.exports = require("crypto"); - offset = PlainValue.Node.endOfIndent(src, lineStart); - } +/***/ }), - ch = src[offset]; - } +/***/ 2361: +/***/ ((module) => { - if (PlainValue.Node.nextNodeIsIndented(ch, offset - (lineStart + indent), this.type !== PlainValue.Type.SEQ_ITEM)) { - this.node = parseNode({ - atLineStart, - inCollection: false, - indent, - lineStart, - parent: this - }, offset); - } else if (ch && lineStart > start + 1) { - offset = lineStart - 1; - } +"use strict"; +module.exports = require("events"); - if (this.node) { - if (blankLine) { - // Only blank lines preceding non-empty nodes are captured. Note that - // this means that collection item range start indices do not always - // increase monotonically. -- eemeli/yaml#126 - const items = context.parent.items || context.parent.contents; - if (items) items.push(blankLine); - } +/***/ }), - if (comments.length) Array.prototype.push.apply(this.props, comments); - offset = this.node.range.end; - } else { - if (inlineComment) { - const c = comments[0]; - this.props.push(c); - offset = c.end; - } else { - offset = PlainValue.Node.endOfLine(src, start + 1); - } - } +/***/ 7147: +/***/ ((module) => { - const end = this.node ? this.node.valueRange.end : offset; - this.valueRange = new PlainValue.Range(start, end); - return offset; - } +"use strict"; +module.exports = require("fs"); - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - return this.node ? this.node.setOrigRanges(cr, offset) : offset; - } +/***/ }), - toString() { - const { - context: { - src - }, - node, - range, - value - } = this; - if (value != null) return value; - const str = node ? src.slice(range.start, node.range.start) + String(node) : src.slice(range.start, range.end); - return PlainValue.Node.addStringTerminator(src, range.end, str); - } +/***/ 3685: +/***/ ((module) => { -} +"use strict"; +module.exports = require("http"); -class Comment extends PlainValue.Node { - constructor() { - super(PlainValue.Type.COMMENT); - } - /** - * Parses a comment line from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ +/***/ }), +/***/ 5687: +/***/ ((module) => { - parse(context, start) { - this.context = context; - const offset = this.parseComment(start); - this.range = new PlainValue.Range(start, offset); - return offset; - } +"use strict"; +module.exports = require("https"); -} +/***/ }), -function grabCollectionEndComments(node) { - let cnode = node; +/***/ 1808: +/***/ ((module) => { - while (cnode instanceof CollectionItem) cnode = cnode.node; +"use strict"; +module.exports = require("net"); - if (!(cnode instanceof Collection)) return null; - const len = cnode.items.length; - let ci = -1; +/***/ }), - for (let i = len - 1; i >= 0; --i) { - const n = cnode.items[i]; +/***/ 2037: +/***/ ((module) => { - if (n.type === PlainValue.Type.COMMENT) { - // Keep sufficiently indented comments with preceding node - const { - indent, - lineStart - } = n.context; - if (indent > 0 && n.range.start >= lineStart + indent) break; - ci = i; - } else if (n.type === PlainValue.Type.BLANK_LINE) ci = i;else break; - } +"use strict"; +module.exports = require("os"); - if (ci === -1) return null; - const ca = cnode.items.splice(ci, len - ci); - const prevEnd = ca[0].range.start; +/***/ }), - while (true) { - cnode.range.end = prevEnd; - if (cnode.valueRange && cnode.valueRange.end > prevEnd) cnode.valueRange.end = prevEnd; - if (cnode === node) break; - cnode = cnode.context.parent; - } +/***/ 1017: +/***/ ((module) => { - return ca; -} -class Collection extends PlainValue.Node { - static nextContentHasIndent(src, offset, indent) { - const lineStart = PlainValue.Node.endOfLine(src, offset) + 1; - offset = PlainValue.Node.endOfWhiteSpace(src, lineStart); - const ch = src[offset]; - if (!ch) return false; - if (offset >= lineStart + indent) return true; - if (ch !== '#' && ch !== '\n') return false; - return Collection.nextContentHasIndent(src, offset, indent); - } +"use strict"; +module.exports = require("path"); - constructor(firstItem) { - super(firstItem.type === PlainValue.Type.SEQ_ITEM ? PlainValue.Type.SEQ : PlainValue.Type.MAP); +/***/ }), - for (let i = firstItem.props.length - 1; i >= 0; --i) { - if (firstItem.props[i].start < firstItem.context.lineStart) { - // props on previous line are assumed by the collection - this.props = firstItem.props.slice(0, i + 1); - firstItem.props = firstItem.props.slice(i + 1); - const itemRange = firstItem.props[0] || firstItem.valueRange; - firstItem.range.start = itemRange.start; - break; - } - } +/***/ 4404: +/***/ ((module) => { - this.items = [firstItem]; - const ec = grabCollectionEndComments(firstItem); - if (ec) Array.prototype.push.apply(this.items, ec); - } - - get includesTrailingLines() { - return this.items.length > 0; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - this.context = context; - const { - parseNode, - src - } = context; // It's easier to recalculate lineStart here rather than tracking down the - // last context from which to read it -- eemeli/yaml#2 - - let lineStart = PlainValue.Node.startOfLine(src, start); - const firstItem = this.items[0]; // First-item context needs to be correct for later comment handling - // -- eemeli/yaml#17 - - firstItem.context.parent = this; - this.valueRange = PlainValue.Range.copy(firstItem.valueRange); - const indent = firstItem.range.start - firstItem.context.lineStart; - let offset = start; - offset = PlainValue.Node.normalizeOffset(src, offset); - let ch = src[offset]; - let atLineStart = PlainValue.Node.endOfWhiteSpace(src, lineStart) === offset; - let prevIncludesTrailingLines = false; - - while (ch) { - while (ch === '\n' || ch === '#') { - if (atLineStart && ch === '\n' && !prevIncludesTrailingLines) { - const blankLine = new BlankLine(); - offset = blankLine.parse({ - src - }, offset); - this.valueRange.end = offset; - - if (offset >= src.length) { - ch = null; - break; - } +"use strict"; +module.exports = require("tls"); - this.items.push(blankLine); - offset -= 1; // blankLine.parse() consumes terminal newline - } else if (ch === '#') { - if (offset < lineStart + indent && !Collection.nextContentHasIndent(src, offset, indent)) { - return offset; - } +/***/ }), - const comment = new Comment(); - offset = comment.parse({ - indent, - lineStart, - src - }, offset); - this.items.push(comment); - this.valueRange.end = offset; - - if (offset >= src.length) { - ch = null; - break; - } - } +/***/ 3837: +/***/ ((module) => { - lineStart = offset + 1; - offset = PlainValue.Node.endOfIndent(src, lineStart); +"use strict"; +module.exports = require("util"); - if (PlainValue.Node.atBlank(src, offset)) { - const wsEnd = PlainValue.Node.endOfWhiteSpace(src, offset); - const next = src[wsEnd]; +/***/ }), - if (!next || next === '\n' || next === '#') { - offset = wsEnd; - } - } +/***/ 8109: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ch = src[offset]; - atLineStart = true; - } +"use strict"; - if (!ch) { - break; - } - if (offset !== lineStart + indent && (atLineStart || ch !== ':')) { - if (offset < lineStart + indent) { - if (lineStart > start) offset = lineStart; - break; - } else if (!this.error) { - const msg = 'All collection items must start at the same column'; - this.error = new PlainValue.YAMLSyntaxError(this, msg); - } - } +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); - if (firstItem.type === PlainValue.Type.SEQ_ITEM) { - if (ch !== '-') { - if (lineStart > start) offset = lineStart; - break; +function composeCollection(CN, ctx, token, tagToken, onError) { + let coll; + switch (token.type) { + case 'block-map': { + coll = resolveBlockMap.resolveBlockMap(CN, ctx, token, onError); + break; } - } else if (ch === '-' && !this.error) { - // map key may start with -, as long as it's followed by a non-whitespace char - const next = src[offset + 1]; - - if (!next || next === '\n' || next === '\t' || next === ' ') { - const msg = 'A collection cannot be both a mapping and a sequence'; - this.error = new PlainValue.YAMLSyntaxError(this, msg); + case 'block-seq': { + coll = resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError); + break; } - } - - const node = parseNode({ - atLineStart, - inCollection: true, - indent, - lineStart, - parent: this - }, offset); - if (!node) return offset; // at next document start - - this.items.push(node); - this.valueRange.end = node.valueRange.end; - offset = PlainValue.Node.normalizeOffset(src, node.range.end); - ch = src[offset]; - atLineStart = false; - prevIncludesTrailingLines = node.includesTrailingLines; // Need to reset lineStart and atLineStart here if preceding node's range - // has advanced to check the current line's indentation level - // -- eemeli/yaml#10 & eemeli/yaml#38 - - if (ch) { - let ls = offset - 1; - let prev = src[ls]; - - while (prev === ' ' || prev === '\t') prev = src[--ls]; - - if (prev === '\n') { - lineStart = ls + 1; - atLineStart = true; + 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 ec = grabCollectionEndComments(node); - if (ec) Array.prototype.push.apply(this.items, ec); } + 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; +} - return offset; - } +exports.composeCollection = composeCollection; - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - this.items.forEach(node => { - offset = node.setOrigRanges(cr, offset); - }); - return offset; - } - toString() { - const { - context: { - src - }, - items, - range, - value - } = this; - if (value != null) return value; - let str = src.slice(range.start, items[0].range.start) + String(items[0]); +/***/ }), - for (let i = 1; i < items.length; ++i) { - const item = items[i]; - const { - atLineStart, - indent - } = item.context; - if (atLineStart) for (let i = 0; i < indent; ++i) str += ' '; - str += String(item); - } +/***/ 5050: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; - return PlainValue.Node.addStringTerminator(src, range.end, str); - } +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; } -class Directive extends PlainValue.Node { - constructor() { - super(PlainValue.Type.DIRECTIVE); - this.name = null; - } +exports.composeDoc = composeDoc; - get parameters() { - const raw = this.rawValue; - return raw ? raw.trim().split(/[ \t]+/) : []; - } - parseName(start) { - const { - src - } = this.context; - let offset = start; - let ch = src[offset]; +/***/ }), - while (ch && ch !== '\n' && ch !== '\t' && ch !== ' ') ch = src[offset += 1]; +/***/ 8676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.name = src.slice(start, offset); - return offset; - } +"use strict"; - parseParameters(start) { - const { - src - } = this.context; - let offset = start; - let ch = src[offset]; - while (ch && ch !== '\n' && ch !== '#') ch = src[offset += 1]; +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; +} - this.valueRange = new PlainValue.Range(start, offset); - return offset; - } +exports.composeEmptyNode = composeEmptyNode; +exports.composeNode = composeNode; - parse(context, start) { - this.context = context; - let offset = this.parseName(start + 1); - offset = this.parseParameters(offset); - offset = this.parseComment(offset); - this.range = new PlainValue.Range(start, offset); - return offset; - } -} +/***/ }), -class Document extends PlainValue.Node { - static startCommentOrEndBlankLine(src, start) { - const offset = PlainValue.Node.endOfWhiteSpace(src, start); - const ch = src[offset]; - return ch === '#' || ch === '\n' ? offset : start; - } +/***/ 4766: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - constructor() { - super(PlainValue.Type.DOCUMENT); - this.directives = null; - this.contents = null; - this.directivesEndMarker = null; - this.documentEndMarker = null; - } +"use strict"; - parseDirectives(start) { - const { - src - } = this.context; - this.directives = []; - let atLineStart = true; - let hasDirectives = false; - let offset = start; - while (!PlainValue.Node.atDocumentBoundary(src, offset, PlainValue.Char.DIRECTIVES_END)) { - offset = Document.startCommentOrEndBlankLine(src, offset); +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; +} - switch (src[offset]) { - case '\n': - if (atLineStart) { - const blankLine = new BlankLine(); - offset = blankLine.parse({ - src - }, offset); +exports.composeScalar = composeScalar; - if (offset < src.length) { - this.directives.push(blankLine); - } - } else { - offset += 1; - atLineStart = true; - } - break; +/***/ }), - case '#': - { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.directives.push(comment); - atLineStart = false; - } - break; +/***/ 9493: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case '%': - { - const directive = new Directive(); - offset = directive.parse({ - parent: this, - src - }, offset); - this.directives.push(directive); - hasDirectives = true; - atLineStart = false; - } - break; +"use strict"; - default: - if (hasDirectives) { - this.error = new PlainValue.YAMLSemanticError(this, 'Missing directives-end indicator line'); - } else if (this.directives.length > 0) { - this.contents = this.directives; - this.directives = []; - } - return offset; - } +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}`)); + } } - - if (src[offset]) { - this.directivesEndMarker = new PlainValue.Range(offset, offset + 3); - return offset + 3; + /** + * 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; + } } +} - if (hasDirectives) { - this.error = new PlainValue.YAMLSemanticError(this, 'Missing directives-end indicator line'); - } else if (this.directives.length > 0) { - this.contents = this.directives; - this.directives = []; - } +exports.Composer = Composer; - return offset; - } - parseContents(start) { - const { - parseNode, - src - } = this.context; - if (!this.contents) this.contents = []; - let lineStart = start; +/***/ }), - while (src[lineStart - 1] === '-') lineStart -= 1; +/***/ 2986: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let offset = PlainValue.Node.endOfWhiteSpace(src, start); - let atLineStart = lineStart === start; - this.valueRange = new PlainValue.Range(offset); +"use strict"; - while (!PlainValue.Node.atDocumentBoundary(src, offset, PlainValue.Char.DOCUMENT_END)) { - switch (src[offset]) { - case '\n': - if (atLineStart) { - const blankLine = new BlankLine(); - offset = blankLine.parse({ - src - }, offset); - if (offset < src.length) { - this.contents.push(blankLine); +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); } - } else { - offset += 1; - atLineStart = true; - } - - lineStart = offset; - break; + 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; +} - case '#': - { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.contents.push(comment); - atLineStart = false; - } - break; +exports.resolveBlockMap = resolveBlockMap; - default: - { - const iEnd = PlainValue.Node.endOfIndent(src, offset); - const context = { - atLineStart, - indent: -1, - inFlow: false, - inCollection: false, - lineStart, - parent: this - }; - const node = parseNode(context, iEnd); - if (!node) return this.valueRange.end = iEnd; // at next document start - - this.contents.push(node); - offset = node.range.end; - atLineStart = false; - const ec = grabCollectionEndComments(node); - if (ec) Array.prototype.push.apply(this.contents, ec); - } - } - offset = Document.startCommentOrEndBlankLine(src, offset); - } +/***/ }), - this.valueRange.end = offset; +/***/ 9485: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (src[offset]) { - this.documentEndMarker = new PlainValue.Range(offset, offset + 3); - offset += 3; +"use strict"; - if (src[offset]) { - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - if (src[offset] === '#') { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.contents.push(comment); +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; } - - switch (src[offset]) { - case '\n': - offset += 1; + 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; - - case undefined: + } + 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; - - default: - this.error = new PlainValue.YAMLSyntaxError(this, 'Document end marker line cannot have a non-comment suffix'); + 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; +} - return offset; - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ - - - parse(context, start) { - context.root = this; - this.context = context; - const { - src - } = context; - let offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM +exports.resolveBlockScalar = resolveBlockScalar; - offset = this.parseDirectives(offset); - offset = this.parseContents(offset); - return offset; - } - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - this.directives.forEach(node => { - offset = node.setOrigRanges(cr, offset); - }); - if (this.directivesEndMarker) offset = this.directivesEndMarker.setOrigRange(cr, offset); - this.contents.forEach(node => { - offset = node.setOrigRanges(cr, offset); - }); - if (this.documentEndMarker) offset = this.documentEndMarker.setOrigRange(cr, offset); - return offset; - } +/***/ }), - toString() { - const { - contents, - directives, - value - } = this; - if (value != null) return value; - let str = directives.join(''); +/***/ 2289: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (contents.length > 0) { - if (directives.length > 0 || contents[0].type === PlainValue.Type.COMMENT) str += '---\n'; - str += contents.join(''); - } +"use strict"; - if (str[str.length - 1] !== '\n') str += '\n'; - return str; - } +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; } -class Alias extends PlainValue.Node { - /** - * Parses an *alias from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = PlainValue.Node.endOfIdentifier(src, start + 1); - this.valueRange = new PlainValue.Range(start + 1, offset); - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } +exports.resolveBlockSeq = resolveBlockSeq; -} -const Chomp = { - CLIP: 'CLIP', - KEEP: 'KEEP', - STRIP: 'STRIP' -}; -class BlockValue extends PlainValue.Node { - constructor(type, props) { - super(type, props); - this.blockIndent = null; - this.chomping = Chomp.CLIP; - this.header = null; - } - - get includesTrailingLines() { - return this.chomping === Chomp.KEEP; - } - - get strValue() { - if (!this.valueRange || !this.context) return null; - let { - start, - end - } = this.valueRange; - const { - indent, - src - } = this.context; - if (this.valueRange.isEmpty()) return ''; - let lastNewLine = null; - let ch = src[end - 1]; - - while (ch === '\n' || ch === '\t' || ch === ' ') { - end -= 1; - - if (end <= start) { - if (this.chomping === Chomp.KEEP) break;else return ''; // probably never happens - } +/***/ }), - if (ch === '\n') lastNewLine = end; - ch = src[end - 1]; - } +/***/ 1250: +/***/ ((__unused_webpack_module, exports) => { - let keepStart = end + 1; +"use strict"; - if (lastNewLine) { - if (this.chomping === Chomp.KEEP) { - keepStart = lastNewLine; - end = this.valueRange.end; - } else { - end = lastNewLine; - } + +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 }; +} - const bi = indent + this.blockIndent; - const folded = this.type === PlainValue.Type.BLOCK_FOLDED; - let atStart = true; - let str = ''; - let sep = ''; - let prevMoreIndented = false; +exports.resolveEnd = resolveEnd; - for (let i = start; i < end; ++i) { - for (let j = 0; j < bi; ++j) { - if (src[i] !== ' ') break; - i += 1; - } - const ch = src[i]; +/***/ }), - if (ch === '\n') { - if (sep === '\n') str += '\n';else sep = '\n'; - } else { - const lineEnd = PlainValue.Node.endOfLine(src, i); - const line = src.slice(i, lineEnd); - i = lineEnd; +/***/ 45: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (folded && (ch === ' ' || ch === '\t') && i < keepStart) { - if (sep === ' ') sep = '\n';else if (!prevMoreIndented && !atStart && sep === '\n') sep = '\n\n'; - str += sep + line; //+ ((lineEnd < end && src[lineEnd]) || '') +"use strict"; - sep = lineEnd < end && src[lineEnd] || ''; - prevMoreIndented = true; - } else { - str += sep + line; - sep = folded && i < keepStart ? ' ' : '\n'; - prevMoreIndented = false; - } - if (atStart && line !== '') atStart = false; - } +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; +} - return this.chomping === Chomp.STRIP ? str : str + '\n'; - } +exports.resolveFlowCollection = resolveFlowCollection; - parseBlockHeader(start) { - const { - src - } = this.context; - let offset = start + 1; - let bi = ''; - while (true) { - const ch = src[offset]; +/***/ }), - switch (ch) { - case '-': - this.chomping = Chomp.STRIP; - break; +/***/ 7578: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case '+': - this.chomping = Chomp.KEEP; - break; +"use strict"; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - bi += ch; - break; - default: - this.blockIndent = Number(bi) || null; - this.header = new PlainValue.Range(start, offset); - return offset; - } +var Scalar = __nccwpck_require__(9338); +var resolveEnd = __nccwpck_require__(1250); - offset += 1; +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] + }; } - } - - parseBlockValue(start) { - const { - indent, - src - } = this.context; - const explicit = !!this.blockIndent; - let offset = start; - let valueEnd = start; - let minBlockIndent = 1; - - for (let ch = src[offset]; ch === '\n'; ch = src[offset]) { - offset += 1; - if (PlainValue.Node.atDocumentBoundary(src, offset)) break; - const end = PlainValue.Node.endOfBlockIndent(src, indent, offset); // should not include tab? - - if (end === null) break; - const ch = src[end]; - const lineIndent = end - (offset + indent); - - if (!this.blockIndent) { - // no explicit block indent, none yet detected - if (src[end] !== '\n') { - // first line with non-whitespace content - if (lineIndent < minBlockIndent) { - const msg = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator'; - this.error = new PlainValue.YAMLSemanticError(this, msg); - } - - this.blockIndent = lineIndent; - } else if (lineIndent > minBlockIndent) { - // empty line with more whitespace - minBlockIndent = lineIndent; + 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; } - } else if (ch && ch !== '\n' && lineIndent < this.blockIndent) { - if (src[end] === '#') break; - - if (!this.error) { - const src = explicit ? 'explicit indentation indicator' : 'first line'; - const msg = `Block scalars must not be less indented than their ${src}`; - this.error = new PlainValue.YAMLSemanticError(this, msg); + case '@': + case '`': { + badChar = `reserved character ${source[0]}`; + break; } - } - - if (src[end] === '\n') { - offset = end; - } else { - offset = valueEnd = PlainValue.Node.endOfLine(src, end); - } } - - if (this.chomping !== Chomp.KEEP) { - offset = src[valueEnd] ? valueEnd + 1 : valueEnd; + 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('(.*?)(? 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); +} - this.valueRange = new PlainValue.Range(start + 1, offset); - return offset; - } - /** - * Parses a block value from the source - * - * Accepted forms are: - * ``` - * BS - * block - * lines - * - * BS #comment - * block - * lines - * ``` - * where the block style BS matches the regexp `[|>][-+1-9]*` and block lines - * are empty or have an indent level greater than `indent`. - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this block - */ - - - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = this.parseBlockHeader(start); - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - offset = this.parseBlockValue(offset); - return offset; - } +exports.resolveFlowScalar = resolveFlowScalar; - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - return this.header ? this.header.setOrigRange(cr, offset) : offset; - } -} +/***/ }), -class FlowCollection extends PlainValue.Node { - constructor(type, props) { - super(type, props); - this.items = null; - } +/***/ 6985: +/***/ ((__unused_webpack_module, exports) => { - prevNodeIsJsonLike(idx = this.items.length) { - const node = this.items[idx - 1]; - return !!node && (node.jsonLike || node.type === PlainValue.Type.COMMENT && this.prevNodeIsJsonLike(idx - 1)); - } - /** - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this - */ +"use strict"; - parse(context, start) { - this.context = context; - const { - parseNode, - src - } = context; - let { - indent, - lineStart - } = context; - let char = src[start]; // { or [ +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; - this.items = [{ - char, - offset: start - }]; - let offset = PlainValue.Node.endOfWhiteSpace(src, start + 1); - char = src[offset]; - while (char && char !== ']' && char !== '}') { - switch (char) { - case '\n': - { - lineStart = offset + 1; - const wsEnd = PlainValue.Node.endOfWhiteSpace(src, lineStart); +/***/ }), - if (src[wsEnd] === '\n') { - const blankLine = new BlankLine(); - lineStart = blankLine.parse({ - src - }, lineStart); - this.items.push(blankLine); - } +/***/ 976: +/***/ ((__unused_webpack_module, exports) => { - offset = PlainValue.Node.endOfIndent(src, lineStart); +"use strict"; - if (offset <= lineStart + indent) { - char = src[offset]; - if (offset < lineStart + indent || char !== ']' && char !== '}') { - const msg = 'Insufficient indentation in flow collection'; - this.error = new PlainValue.YAMLSemanticError(this, msg); - } +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; } - } - break; + return false; + default: + return true; + } +} - case ',': - { - this.items.push({ - char, - offset - }); - offset += 1; - } - break; +exports.containsNewline = containsNewline; - case '#': - { - const comment = new Comment(); - offset = comment.parse({ - src - }, offset); - this.items.push(comment); - } - break; - case '?': - case ':': - { - const next = src[offset + 1]; - - if (next === '\n' || next === '\t' || next === ' ' || next === ',' || // in-flow : after JSON-like key does not need to be followed by whitespace - char === ':' && this.prevNodeIsJsonLike()) { - this.items.push({ - char, - offset - }); - offset += 1; - break; - } - } - // fallthrough +/***/ }), - default: - { - const node = parseNode({ - atLineStart: false, - inCollection: false, - inFlow: true, - indent: -1, - lineStart, - parent: this - }, offset); - - if (!node) { - // at next document start - this.valueRange = new PlainValue.Range(start, offset); - return offset; - } - - this.items.push(node); - offset = PlainValue.Node.normalizeOffset(src, node.range.end); - } - } +/***/ 8781: +/***/ ((__unused_webpack_module, exports) => { - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - char = src[offset]; - } +"use strict"; - this.valueRange = new PlainValue.Range(start, offset + 1); - if (char) { - this.items.push({ - char, - offset - }); - offset = PlainValue.Node.endOfWhiteSpace(src, offset + 1); - offset = this.parseComment(offset); +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; - } +} - setOrigRanges(cr, offset) { - offset = super.setOrigRanges(cr, offset); - this.items.forEach(node => { - if (node instanceof PlainValue.Node) { - offset = node.setOrigRanges(cr, offset); - } else if (cr.length === 0) { - node.origOffset = node.offset; - } else { - let i = offset; +exports.emptyScalarPosition = emptyScalarPosition; - while (i < cr.length) { - if (cr[i] > node.offset) break;else ++i; - } - node.origOffset = node.offset + i; - offset = i; - } - }); - return offset; - } +/***/ }), - toString() { - const { - context: { - src - }, - items, - range, - value - } = this; - if (value != null) return value; - const nodes = items.filter(item => item instanceof PlainValue.Node); - let str = ''; - let prevEnd = range.start; - nodes.forEach(node => { - const prefix = src.slice(prevEnd, node.range.start); - prevEnd = node.range.end; - str += prefix + String(node); - - if (str[str.length - 1] === '\n' && src[prevEnd - 1] !== '\n' && src[prevEnd] === '\n') { - // Comment range does not include the terminal newline, but its - // stringified value does. Without this fix, newlines at comment ends - // get duplicated. - prevEnd += 1; - } - }); - str += src.slice(prevEnd, range.end); - return PlainValue.Node.addStringTerminator(src, range.end, str); - } +/***/ 3669: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -} +"use strict"; -class QuoteDouble extends PlainValue.Node { - static endOfQuote(src, offset) { - let ch = src[offset]; - while (ch && ch !== '"') { - offset += ch === '\\' ? 2 : 1; - ch = src[offset]; +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); + } } +} - return offset + 1; - } - /** - * @returns {string | { str: string, errors: YAMLSyntaxError[] }} - */ +exports.flowIndentCheck = flowIndentCheck; - get strValue() { - if (!this.valueRange || !this.context) return null; - const errors = []; - const { - start, - end - } = this.valueRange; - const { - indent, - src - } = this.context; - if (src[end - 1] !== '"') errors.push(new PlainValue.YAMLSyntaxError(this, 'Missing closing "quote')); // Using String#replace is too painful with escaped newlines preceded by - // escaped backslashes; also, this should be faster. +/***/ }), - let str = ''; +/***/ 6899: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (let i = start + 1; i < end - 1; ++i) { - const ch = src[i]; - - if (ch === '\n') { - if (PlainValue.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); - const { - fold, - offset, - error - } = PlainValue.Node.foldNewline(src, i, indent); - str += fold; - i = offset; - if (error) errors.push(new PlainValue.YAMLSemanticError(this, 'Multi-line double-quoted string needs to be sufficiently indented')); - } else if (ch === '\\') { - i += 1; - - switch (src[i]) { - case '0': - str += '\0'; - break; - // null character +"use strict"; - case 'a': - str += '\x07'; - break; - // bell character - case 'b': - str += '\b'; - break; - // backspace +var Node = __nccwpck_require__(1399); - case 'e': - str += '\x1b'; - break; - // escape character +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)); +} - case 'f': - str += '\f'; - break; - // form feed +exports.mapIncludes = mapIncludes; - case 'n': - str += '\n'; - break; - // line feed - case 'r': - str += '\r'; - break; - // carriage return +/***/ }), - case 't': - str += '\t'; - break; - // horizontal tab +/***/ 42: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case 'v': - str += '\v'; - break; - // vertical tab +"use strict"; - case 'N': - str += '\u0085'; - break; - // Unicode next line - case '_': - str += '\u00a0'; - break; - // Unicode non-breaking space +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); - case 'L': - str += '\u2028'; - break; - // Unicode line separator +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'); +} - case 'P': - str += '\u2029'; - break; - // Unicode paragraph separator +exports.Document = Document; - case ' ': - str += ' '; - break; - case '"': - str += '"'; - break; +/***/ }), - case '/': - str += '/'; - break; +/***/ 8459: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case '\\': - str += '\\'; - break; +"use strict"; - case '\t': - str += '\t'; - break; - case 'x': - str += this.parseCharCode(i + 1, 2, errors); - i += 2; - break; +var Node = __nccwpck_require__(1399); +var visit = __nccwpck_require__(6796); - case 'u': - str += this.parseCharCode(i + 1, 4, errors); - i += 4; - break; +/** + * 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 + }; +} - case 'U': - str += this.parseCharCode(i + 1, 8, errors); - i += 8; - break; +exports.anchorIsValid = anchorIsValid; +exports.anchorNames = anchorNames; +exports.createNodeAnchors = createNodeAnchors; +exports.findNewAnchor = findNewAnchor; - case '\n': - // skip escaped newlines, but still trim the following line - while (src[i + 1] === ' ' || src[i + 1] === '\t') i += 1; - break; +/***/ }), - default: - errors.push(new PlainValue.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(i - 1, 2)}`)); - str += '\\' + src[i]; - } - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - const wsStart = i; - let next = src[i + 1]; +/***/ 3412: +/***/ ((__unused_webpack_module, exports) => { - while (next === ' ' || next === '\t') { - i += 1; - next = src[i + 1]; - } +"use strict"; - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } + +/** + * 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); +} - return errors.length > 0 ? { - errors, - str - } : str; - } +exports.applyReviver = applyReviver; - parseCharCode(offset, length, errors) { - const { - src - } = this.context; - const cc = src.substr(offset, length); - const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); - const code = ok ? parseInt(cc, 16) : NaN; - if (isNaN(code)) { - errors.push(new PlainValue.YAMLSyntaxError(this, `Invalid escape sequence ${src.substr(offset - 2, length + 2)}`)); - return src.substr(offset - 2, length + 2); - } +/***/ }), - return String.fromCodePoint(code); - } - /** - * Parses a "double quoted" value from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = QuoteDouble.endOfQuote(src, start + 1); - this.valueRange = new PlainValue.Range(start, offset); - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } +/***/ 9652: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -} +"use strict"; -class QuoteSingle extends PlainValue.Node { - static endOfQuote(src, offset) { - let ch = src[offset]; - while (ch) { - if (ch === "'") { - if (src[offset + 1] !== "'") break; - ch = src[offset += 2]; - } else { - ch = src[offset += 1]; - } +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; +} - return offset + 1; - } - /** - * @returns {string | { str: string, errors: YAMLSyntaxError[] }} - */ +exports.createNode = createNode; - get strValue() { - if (!this.valueRange || !this.context) return null; - const errors = []; - const { - start, - end - } = this.valueRange; - const { - indent, - src - } = this.context; - if (src[end - 1] !== "'") errors.push(new PlainValue.YAMLSyntaxError(this, "Missing closing 'quote")); - let str = ''; +/***/ }), - for (let i = start + 1; i < end - 1; ++i) { - const ch = src[i]; - - if (ch === '\n') { - if (PlainValue.Node.atDocumentBoundary(src, i + 1)) errors.push(new PlainValue.YAMLSemanticError(this, 'Document boundary indicators are not allowed within string values')); - const { - fold, - offset, - error - } = PlainValue.Node.foldNewline(src, i, indent); - str += fold; - i = offset; - if (error) errors.push(new PlainValue.YAMLSemanticError(this, 'Multi-line single-quoted string needs to be sufficiently indented')); - } else if (ch === "'") { - str += ch; - i += 1; - if (src[i] !== "'") errors.push(new PlainValue.YAMLSyntaxError(this, 'Unescaped single quote? This should not happen.')); - } else if (ch === ' ' || ch === '\t') { - // trim trailing whitespace - const wsStart = i; - let next = src[i + 1]; - - while (next === ' ' || next === '\t') { - i += 1; - next = src[i + 1]; - } - - if (next !== '\n') str += i > wsStart ? src.slice(wsStart, i + 1) : ch; - } else { - str += ch; - } - } +/***/ 5400: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; - return errors.length > 0 ? { - errors, - str - } : str; - } - /** - * Parses a 'single quoted' value from the source - * - * @param {ParseContext} context - * @param {number} start - Index of first character - * @returns {number} - Index of the character after this scalar - */ - - - parse(context, start) { - this.context = context; - const { - src - } = context; - let offset = QuoteSingle.endOfQuote(src, start + 1); - this.valueRange = new PlainValue.Range(start, offset); - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - offset = this.parseComment(offset); - return offset; - } +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:' }; -function createNewNode(type, props) { - switch (type) { - case PlainValue.Type.ALIAS: - return new Alias(type, props); - - case PlainValue.Type.BLOCK_FOLDED: - case PlainValue.Type.BLOCK_LITERAL: - return new BlockValue(type, props); +exports.Directives = Directives; - case PlainValue.Type.FLOW_MAP: - case PlainValue.Type.FLOW_SEQ: - return new FlowCollection(type, props); - case PlainValue.Type.MAP_KEY: - case PlainValue.Type.MAP_VALUE: - case PlainValue.Type.SEQ_ITEM: - return new CollectionItem(type, props); - - case PlainValue.Type.COMMENT: - case PlainValue.Type.PLAIN: - return new PlainValue.PlainValue(type, props); +/***/ }), - case PlainValue.Type.QUOTE_DOUBLE: - return new QuoteDouble(type, props); +/***/ 4236: +/***/ ((__unused_webpack_module, exports) => { - case PlainValue.Type.QUOTE_SINGLE: - return new QuoteSingle(type, props); +"use strict"; - /* istanbul ignore next */ - default: - return null; - // should never happen - } +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } } -/** - * @param {boolean} atLineStart - Node starts at beginning of line - * @param {boolean} inFlow - true if currently in a flow context - * @param {boolean} inCollection - true if currently in a collection context - * @param {number} indent - Current level of indentation - * @param {number} lineStart - Start of the current line - * @param {Node} parent - The parent of the node - * @param {string} src - Source of the YAML document - */ +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.max(1, 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; -class ParseContext { - static parseType(src, offset, inFlow) { - switch (src[offset]) { - case '*': - return PlainValue.Type.ALIAS; - case '>': - return PlainValue.Type.BLOCK_FOLDED; +/***/ }), - case '|': - return PlainValue.Type.BLOCK_LITERAL; +/***/ 4083: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case '{': - return PlainValue.Type.FLOW_MAP; +"use strict"; - case '[': - return PlainValue.Type.FLOW_SEQ; - case '?': - return !inFlow && PlainValue.Node.atBlank(src, offset + 1, true) ? PlainValue.Type.MAP_KEY : PlainValue.Type.PLAIN; +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; - case ':': - return !inFlow && PlainValue.Node.atBlank(src, offset + 1, true) ? PlainValue.Type.MAP_VALUE : PlainValue.Type.PLAIN; - case '-': - return !inFlow && PlainValue.Node.atBlank(src, offset + 1, true) ? PlainValue.Type.SEQ_ITEM : PlainValue.Type.PLAIN; +/***/ }), - case '"': - return PlainValue.Type.QUOTE_DOUBLE; +/***/ 6909: +/***/ ((__unused_webpack_module, exports) => { - case "'": - return PlainValue.Type.QUOTE_SINGLE; +"use strict"; - default: - return PlainValue.Type.PLAIN; - } - } - - constructor(orig = {}, { - atLineStart, - inCollection, - inFlow, - indent, - lineStart, - parent - } = {}) { - PlainValue._defineProperty(this, "parseNode", (overlay, start) => { - if (PlainValue.Node.atDocumentBoundary(this.src, start)) return null; - const context = new ParseContext(this, overlay); - const { - props, - type, - valueStart - } = context.parseProps(start); - const node = createNewNode(type, props); - let offset = node.parse(context, valueStart); - node.range = new PlainValue.Range(start, offset); - /* istanbul ignore if */ - if (offset <= start) { - // This should never happen, but if it does, let's make sure to at least - // step one character forward to avoid a busy loop. - node.error = new Error(`Node#parse consumed no characters`); - node.error.parseEnd = offset; - node.error.source = node; - node.range.end = start + 1; - } +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); + } +} - if (context.nodeStartsCollection(node)) { - if (!node.error && !context.atLineStart && context.parent.type === PlainValue.Type.DOCUMENT) { - node.error = new PlainValue.YAMLSyntaxError(node, 'Block collection must not have preceding content here (e.g. directives-end indicator)'); - } +exports.debug = debug; +exports.warn = warn; - const collection = new Collection(node); - offset = collection.parse(new ParseContext(context), offset); - collection.range = new PlainValue.Range(start, offset); - return collection; - } - return node; - }); +/***/ }), - this.atLineStart = atLineStart != null ? atLineStart : orig.atLineStart || false; - this.inCollection = inCollection != null ? inCollection : orig.inCollection || false; - this.inFlow = inFlow != null ? inFlow : orig.inFlow || false; - this.indent = indent != null ? indent : orig.indent; - this.lineStart = lineStart != null ? lineStart : orig.lineStart; - this.parent = parent != null ? parent : orig.parent || {}; - this.root = orig.root; - this.src = orig.src; - } - - nodeStartsCollection(node) { - const { - inCollection, - inFlow, - src - } = this; - if (inCollection || inFlow) return false; - if (node instanceof CollectionItem) return true; // check for implicit key - - let offset = node.range.end; - if (src[offset] === '\n' || src[offset - 1] === '\n') return false; - offset = PlainValue.Node.endOfWhiteSpace(src, offset); - return src[offset] === ':'; - } // Anchor and tag are before type, which determines the node implementation - // class; hence this intermediate step. - - - parseProps(offset) { - const { - inFlow, - parent, - src - } = this; - const props = []; - let lineHasProps = false; - offset = this.atLineStart ? PlainValue.Node.endOfIndent(src, offset) : PlainValue.Node.endOfWhiteSpace(src, offset); - let ch = src[offset]; - - while (ch === PlainValue.Char.ANCHOR || ch === PlainValue.Char.COMMENT || ch === PlainValue.Char.TAG || ch === '\n') { - if (ch === '\n') { - const lineStart = offset + 1; - const inEnd = PlainValue.Node.endOfIndent(src, lineStart); - const indentDiff = inEnd - (lineStart + this.indent); - const noIndicatorAsIndent = parent.type === PlainValue.Type.SEQ_ITEM && parent.context.atLineStart; - if (!PlainValue.Node.nextNodeIsIndented(src[inEnd], indentDiff, !noIndicatorAsIndent)) break; - this.atLineStart = true; - this.lineStart = lineStart; - lineHasProps = false; - offset = inEnd; - } else if (ch === PlainValue.Char.COMMENT) { - const end = PlainValue.Node.endOfLine(src, offset + 1); - props.push(new PlainValue.Range(offset, end)); - offset = end; - } else { - let end = PlainValue.Node.endOfIdentifier(src, offset + 1); +/***/ 5639: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (ch === PlainValue.Char.TAG && src[end] === ',' && /^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(src.slice(offset + 1, end + 13))) { - // Let's presume we're dealing with a YAML 1.0 domain tag here, rather - // than an empty but 'foo.bar' private-tagged node in a flow collection - // followed without whitespace by a plain string starting with a year - // or date divided by something. - end = PlainValue.Node.endOfIdentifier(src, end + 5); - } +"use strict"; - props.push(new PlainValue.Range(offset, end)); - lineHasProps = true; - offset = PlainValue.Node.endOfWhiteSpace(src, end); - } - ch = src[offset]; - } // '- &a : b' has an anchor on an empty node +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; - if (lineHasProps && ch === ':' && PlainValue.Node.atBlank(src, offset + 1, true)) offset -= 1; - const type = ParseContext.parseType(src, offset, inFlow); - return { - props, - type, - valueStart: offset - }; - } - /** - * Parses a node from the source - * @param {ParseContext} overlay - * @param {number} start - Index of first non-whitespace character for the node - * @returns {?Node} - null if at a document boundary - */ +/***/ }), -} +/***/ 3466: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Published as 'yaml/parse-cst' -function parse(src) { - const cr = []; +"use strict"; - if (src.indexOf('\r') !== -1) { - src = src.replace(/\r\n?/g, (match, offset) => { - if (match.length > 1) cr.push(offset); - return '\n'; - }); - } - const documents = []; - let offset = 0; +var createNode = __nccwpck_require__(9652); +var Node = __nccwpck_require__(1399); - do { - const doc = new Document(); - const context = new ParseContext({ - src +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() }); - offset = doc.parse(context, offset); - documents.push(doc); - } while (offset < src.length); +} +// 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; - documents.setOrigRanges = () => { - if (cr.length === 0) return false; +exports.Collection = Collection; +exports.collectionFromPath = collectionFromPath; +exports.isEmptyPath = isEmptyPath; - for (let i = 1; i < cr.length; ++i) cr[i] -= i; - let crOffset = 0; +/***/ }), - for (let i = 0; i < documents.length; ++i) { - crOffset = documents[i].setOrigRanges(cr, crOffset); - } +/***/ 1399: +/***/ ((__unused_webpack_module, exports) => { - cr.splice(0, cr.length); - return true; - }; +"use strict"; - documents.toString = () => documents.join('...\n'); - return documents; +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; } - -exports.parse = parse; +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; /***/ }), -/***/ 6140: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 246: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var PlainValue = __webpack_require__(5215); +var createNode = __nccwpck_require__(9652); +var stringifyPair = __nccwpck_require__(4875); +var addPairToJSMap = __nccwpck_require__(4676); +var Node = __nccwpck_require__(1399); -function addCommentBefore(str, indent, comment) { - if (!comment) return str; - const cc = comment.replace(/[\s\S]^/gm, `$&${indent}#`); - return `#${cc}\n${indent}${str}`; +function createPair(key, value, ctx) { + const k = createNode.createNode(key, undefined, ctx); + const v = createNode.createNode(value, undefined, ctx); + return new Pair(k, v); } -function addComment(str, indent, comment) { - return !comment ? str : comment.indexOf('\n') === -1 ? `${str} #${comment}` : `${str}\n` + comment.replace(/^/gm, `${indent || ''}#`); +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); + } } -class Node {} +exports.Pair = Pair; +exports.createPair = createPair; -function toJSON(value, arg, ctx) { - if (Array.isArray(value)) return value.map((v, i) => toJSON(v, String(i), ctx)); - if (value && typeof value.toJSON === 'function') { - const anchor = ctx && ctx.anchors && ctx.anchors.get(value); - if (anchor) ctx.onCreate = res => { - anchor.res = res; - delete ctx.onCreate; - }; - const res = value.toJSON(arg, ctx); - if (anchor && ctx.onCreate) ctx.onCreate(res); - return res; - } +/***/ }), - if ((!ctx || !ctx.keep) && typeof value === 'bigint') return Number(value); - return value; -} +/***/ 9338: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -class Scalar extends Node { - constructor(value) { - super(); - this.value = value; - } +"use strict"; - toJSON(arg, ctx) { - return ctx && ctx.keep ? this.value : toJSON(this.value, arg, ctx); - } - toString() { - return String(this.value); - } +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'; -function collectionFromPath(schema, path, value) { - let v = value; +exports.Scalar = Scalar; +exports.isScalarValue = isScalarValue; - for (let i = path.length - 1; i >= 0; --i) { - const k = path[i]; - const o = Number.isInteger(k) && k >= 0 ? [] : {}; - o[k] = v; - v = o; - } - return schema.createNode(v, false); -} // null, undefined, or an empty non-string iterable (e.g. []) +/***/ }), +/***/ 6011: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const isEmptyPath = path => path == null || typeof path === 'object' && path[Symbol.iterator]().next().done; -class Collection extends Node { - constructor(schema) { - super(); +"use strict"; - PlainValue._defineProperty(this, "items", []); - this.schema = schema; - } +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); - addIn(path, value) { - if (isEmptyPath(path)) this.add(value);else { - const [key, ...rest] = path; - const node = this.get(key, true); - if (node instanceof Collection) 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}`); +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; + } } - } - - deleteIn([key, ...rest]) { - if (rest.length === 0) return this.delete(key); - const node = this.get(key, true); - if (node instanceof Collection) return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); - } + 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 + }); + } +} - getIn([key, ...rest], keepScalar) { - const node = this.get(key, true); - if (rest.length === 0) return !keepScalar && node instanceof Scalar ? node.value : node;else return node instanceof Collection ? node.getIn(rest, keepScalar) : undefined; - } +exports.YAMLMap = YAMLMap; +exports.findPair = findPair; - hasAllNullValues() { - return this.items.every(node => { - if (!node || node.type !== 'PAIR') return false; - const n = node.value; - return n == null || n instanceof Scalar && n.value == null && !n.commentBefore && !n.comment && !n.tag; - }); - } - hasIn([key, ...rest]) { - if (rest.length === 0) return this.has(key); - const node = this.get(key, true); - return node instanceof Collection ? node.hasIn(rest) : false; - } +/***/ }), - setIn([key, ...rest], value) { - if (rest.length === 0) { - this.set(key, value); - } else { - const node = this.get(key, true); - if (node instanceof Collection) 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}`); - } - } // overridden in implementations +/***/ 5161: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - /* istanbul ignore next */ +"use strict"; - toJSON() { - return null; - } +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); - toString(ctx, { - blockItem, - flowChars, - isMap, - itemIndent - }, onComment, onChompKeep) { - const { - indent, - indentStep, - stringify - } = ctx; - const inFlow = this.type === PlainValue.Type.FLOW_MAP || this.type === PlainValue.Type.FLOW_SEQ || ctx.inFlow; - if (inFlow) itemIndent += indentStep; - const allNullValues = isMap && this.hasAllNullValues(); - ctx = Object.assign({}, ctx, { - allNullValues, - indent: itemIndent, - inFlow, - type: null - }); - let chompKeep = false; - let hasItemWithNewLine = false; - const nodes = this.items.reduce((nodes, item, i) => { - let comment; - - if (item) { - if (!chompKeep && item.spaceBefore) nodes.push({ - type: 'comment', - str: '' - }); - if (item.commentBefore) item.commentBefore.match(/^.*$/gm).forEach(line => { - nodes.push({ - type: 'comment', - str: `#${line}` - }); +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 }); - if (item.comment) comment = item.comment; - if (inFlow && (!chompKeep && item.spaceBefore || item.commentBefore || item.comment || item.key && (item.key.commentBefore || item.key.comment) || item.value && (item.value.commentBefore || item.value.comment))) hasItemWithNewLine = true; - } - - chompKeep = false; - let str = stringify(item, ctx, () => comment = null, () => chompKeep = true); - if (inFlow && !hasItemWithNewLine && str.includes('\n')) hasItemWithNewLine = true; - if (inFlow && i < this.items.length - 1) str += ','; - str = addComment(str, itemIndent, comment); - if (chompKeep && (comment || inFlow)) chompKeep = false; - nodes.push({ - type: 'item', - str - }); - return nodes; - }, []); - let str; + } +} +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; +} - if (nodes.length === 0) { - str = flowChars.start + flowChars.end; - } else if (inFlow) { - const { - start, - end - } = flowChars; - const strings = nodes.map(n => n.str); +exports.YAMLSeq = YAMLSeq; - if (hasItemWithNewLine || strings.reduce((sum, str) => sum + str.length + 2, 2) > Collection.maxFlowStringSingleLineLength) { - str = start; - for (const s of strings) { - str += s ? `\n${indentStep}${indent}${s}` : '\n'; - } +/***/ }), - str += `\n${indent}${end}`; - } else { - str = `${start} ${strings.join(' ')} ${end}`; - } - } else { - const strings = nodes.map(blockItem); - str = strings.shift(); +/***/ 4676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (const s of strings) str += s ? `\n${indent}${s}` : '\n'; - } +"use strict"; - if (this.comment) { - str += '\n' + this.comment.replace(/^/gm, `${indent}#`); - if (onComment) onComment(); - } else if (chompKeep && onChompKeep) onChompKeep(); - return str; - } +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); } -PlainValue._defineProperty(Collection, "maxFlowStringSingleLineLength", 60); +exports.addPairToJSMap = addPairToJSMap; -function asItemIndex(key) { - let idx = key instanceof Scalar ? key.value : key; - if (idx && typeof idx === 'string') idx = Number(idx); - return Number.isInteger(idx) && idx >= 0 ? idx : null; -} -class YAMLSeq extends Collection { - add(value) { - this.items.push(value); - } +/***/ }), - delete(key) { - const idx = asItemIndex(key); - if (typeof idx !== 'number') return false; - const del = this.items.splice(idx, 1); - return del.length > 0; - } +/***/ 2463: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get(key, keepScalar) { - const idx = asItemIndex(key); - if (typeof idx !== 'number') return undefined; - const it = this.items[idx]; - return !keepScalar && it instanceof Scalar ? it.value : it; - } +"use strict"; - has(key) { - const idx = asItemIndex(key); - return typeof idx === 'number' && idx < this.items.length; - } - set(key, value) { - const idx = asItemIndex(key); - if (typeof idx !== 'number') throw new Error(`Expected a valid index, not ${key}.`); - this.items[idx] = value; - } +var Node = __nccwpck_require__(1399); - toJSON(_, ctx) { - const seq = []; - if (ctx && ctx.onCreate) ctx.onCreate(seq); - let i = 0; +/** + * 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; +} - for (const item of this.items) seq.push(toJSON(item, String(i++), ctx)); +exports.toJS = toJS; - return seq; - } - toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - return super.toString(ctx, { - blockItem: n => n.type === 'comment' ? n.str : `- ${n.str}`, - flowChars: { - start: '[', - end: ']' - }, - isMap: false, - itemIndent: (ctx.indent || '') + ' ' - }, onComment, onChompKeep); - } - -} - -const stringifyKey = (key, jsKey, ctx) => { - if (jsKey === null) return ''; - if (typeof jsKey !== 'object') return String(jsKey); - if (key instanceof Node && ctx && ctx.doc) return key.toString({ - anchors: {}, - doc: ctx.doc, - indent: '', - indentStep: ctx.indentStep, - inFlow: true, - inStringifyKey: true, - stringify: ctx.stringify - }); - return JSON.stringify(jsKey); -}; +/***/ }), -class Pair extends Node { - constructor(key, value = null) { - super(); - this.key = key; - this.value = value; - this.type = Pair.Type.PAIR; - } +/***/ 9027: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - get commentBefore() { - return this.key instanceof Node ? this.key.commentBefore : undefined; - } +"use strict"; - set commentBefore(cb) { - if (this.key == null) this.key = new Scalar(null); - if (this.key instanceof Node) this.key.commentBefore = cb;else { - const msg = 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.'; - throw new Error(msg); - } - } - addToJSMap(ctx, map) { - const key = toJSON(this.key, '', ctx); +var resolveBlockScalar = __nccwpck_require__(9485); +var resolveFlowScalar = __nccwpck_require__(7578); +var errors = __nccwpck_require__(4236); +var stringifyString = __nccwpck_require__(6226); - if (map instanceof Map) { - const value = toJSON(this.value, key, ctx); - map.set(key, value); - } else if (map instanceof Set) { - map.add(key); - } else { - const stringKey = stringifyKey(this.key, key, ctx); - map[stringKey] = toJSON(this.value, stringKey, ctx); +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 map; - } - - toJSON(_, ctx) { - const pair = ctx && ctx.mapAsMap ? new Map() : {}; - return this.addToJSMap(ctx, pair); - } - - toString(ctx, onComment, onChompKeep) { - if (!ctx || !ctx.doc) return JSON.stringify(this); - const { - indent: indentSize, - indentSeq, - simpleKeys - } = ctx.doc.options; - let { - key, - value - } = this; - let keyComment = key instanceof Node && key.comment; - - if (simpleKeys) { - if (keyComment) { - throw new Error('With simple keys, key nodes cannot have comments'); - } - - if (key instanceof Collection) { - const msg = 'With simple keys, collection cannot be used as a key value'; - throw new Error(msg); - } + 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 }; } - - const explicitKey = !simpleKeys && (!key || keyComment || key instanceof Collection || key.type === PlainValue.Type.BLOCK_FOLDED || key.type === PlainValue.Type.BLOCK_LITERAL); - const { - doc, - indent, - indentStep, - stringify - } = ctx; - ctx = Object.assign({}, ctx, { - implicitKey: !explicitKey, - indent: indent + indentStep +} +/** + * 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 } }); - let chompKeep = false; - let str = stringify(key, ctx, () => keyComment = null, () => chompKeep = true); - str = addComment(str, ctx.indent, keyComment); - - if (ctx.allNullValues && !simpleKeys) { - if (this.comment) { - str = addComment(str, ctx.indent, this.comment); - if (onComment) onComment(); - } else if (chompKeep && !keyComment && onChompKeep) onChompKeep(); - - return ctx.inFlow ? str : `? ${str}`; + 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'); } - - str = explicitKey ? `? ${str}\n${indent}:` : `${str}:`; - - if (this.comment) { - // expected (but not strictly required) to be a single-line comment - str = addComment(str, ctx.indent, this.comment); - if (onComment) onComment(); +} +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 }); + } + } +} - let vcb = ''; - let valueComment = null; - - if (value instanceof Node) { - if (value.spaceBefore) vcb = '\n'; +exports.createScalarToken = createScalarToken; +exports.resolveAsScalar = resolveAsScalar; +exports.setScalarValue = setScalarValue; - if (value.commentBefore) { - const cs = value.commentBefore.replace(/^/gm, `${ctx.indent}#`); - vcb += `\n${cs}`; - } - valueComment = value.comment; - } else if (value && typeof value === 'object') { - value = doc.schema.createNode(value, true); - } +/***/ }), - ctx.implicitKey = false; - if (!explicitKey && !this.comment && value instanceof Scalar) ctx.indentAtStart = str.length + 1; - chompKeep = false; +/***/ 6307: +/***/ ((__unused_webpack_module, exports) => { - if (!indentSeq && indentSize >= 2 && !ctx.inFlow && !explicitKey && value instanceof YAMLSeq && value.type !== PlainValue.Type.FLOW_SEQ && !value.tag && !doc.anchors.getName(value)) { - // If indentSeq === false, consider '- ' as part of indentation where possible - ctx.indent = ctx.indent.substr(2); - } +"use strict"; - const valueStr = stringify(value, ctx, () => valueComment = null, () => chompKeep = true); - let ws = ' '; - if (vcb || this.comment) { - ws = `${vcb}\n${ctx.indent}`; - } else if (!explicitKey && value instanceof Collection) { - const flow = valueStr[0] === '[' || valueStr[0] === '{'; - if (!flow || valueStr.includes('\n')) ws = `\n${ctx.indent}`; +/** + * 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; + } } - - if (chompKeep && !valueComment && onChompKeep) onChompKeep(); - return addComment(str + ws + valueStr, ctx.indent, valueComment); - } - +} +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; } -PlainValue._defineProperty(Pair, "Type", { - PAIR: 'PAIR', - MERGE_PAIR: 'MERGE_PAIR' -}); +exports.stringify = stringify; -const getAliasCount = (node, anchors) => { - if (node instanceof Alias) { - const anchor = anchors.get(node.source); - return anchor.count * anchor.aliasCount; - } else if (node instanceof Collection) { - let count = 0; - for (const item of node.items) { - const c = getAliasCount(item, anchors); - if (c > count) count = c; - } +/***/ }), - return count; - } else if (node instanceof Pair) { - const kc = getAliasCount(node.key, anchors); - const vc = getAliasCount(node.value, anchors); - return Math.max(kc, vc); - } +/***/ 8497: +/***/ ((__unused_webpack_module, exports) => { - return 1; -}; +"use strict"; -class Alias extends Node { - static stringify({ - range, - source - }, { - anchors, - doc, - implicitKey, - inStringifyKey - }) { - let anchor = Object.keys(anchors).find(a => anchors[a] === source); - if (!anchor && inStringifyKey) anchor = doc.anchors.getName(source) || doc.anchors.newName(); - if (anchor) return `*${anchor}${implicitKey ? ' ' : ''}`; - const msg = doc.anchors.getName(source) ? 'Alias node must be after source node' : 'Source node not found for alias node'; - throw new Error(`${msg} [${range}]`); - } - - constructor(source) { - super(); - this.source = source; - this.type = PlainValue.Type.ALIAS; - } - - set tag(t) { - throw new Error('Alias nodes cannot have tags'); - } - - toJSON(arg, ctx) { - if (!ctx) return toJSON(this.source, arg, ctx); - const { - anchors, - maxAliasCount - } = ctx; - const anchor = anchors.get(this.source); - /* istanbul ignore if */ - if (!anchor || anchor.res === undefined) { - const msg = 'This should not happen: Alias anchor was not resolved?'; - if (this.cstNode) throw new PlainValue.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); +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; } - - if (maxAliasCount >= 0) { - anchor.count += 1; - if (anchor.aliasCount === 0) anchor.aliasCount = getAliasCount(this.source, anchors); - - if (anchor.count * anchor.aliasCount > maxAliasCount) { - const msg = 'Excessive alias count indicates a resource exhaustion attack'; - if (this.cstNode) throw new PlainValue.YAMLReferenceError(this.cstNode, msg);else throw new ReferenceError(msg); - } + 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; +} - return anchor.res; - } // Only called when stringifying an alias mapping key while constructing - // Object output. +exports.visit = visit; - toString(ctx) { - return Alias.stringify(this, ctx); - } +/***/ }), -} +/***/ 9169: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -PlainValue._defineProperty(Alias, "default", true); +"use strict"; -function findPair(items, key) { - const k = key instanceof Scalar ? key.value : key; - for (const it of items) { - if (it instanceof Pair) { - if (it.key === key || it.key === k) return it; - if (it.key && it.key.value === k) return it; +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 ''; + case DOCUMENT: + return ''; + case FLOW_END: + return ''; + case SCALAR: + return ''; + 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'; } - } - - return undefined; -} -class YAMLMap extends Collection { - add(pair, overwrite) { - if (!pair) pair = new Pair(pair);else if (!(pair instanceof Pair)) pair = new Pair(pair.key || pair, pair.value); - const prev = findPair(this.items, pair.key); - const sortEntries = this.schema && this.schema.sortMapEntries; - - if (prev) { - if (overwrite) prev.value = pair.value;else throw new Error(`Key ${pair.key} already set`); - } 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); + 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'; } - } - - 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 && it.value; - return !keepScalar && node instanceof Scalar ? node.value : node; - } - - has(key) { - return !!findPair(this.items, key); - } + return null; +} - set(key, value) { - this.add(new Pair(key, value), true); - } - /** - * @param {*} arg ignored - * @param {*} ctx Conversion context, originally set in Document#toJSON() - * @param {Class} Type If set, forces the returned collection type - * @returns {*} Instance of Type, Map, or Object - */ +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; - toJSON(_, ctx, Type) { - const map = Type ? new Type() : ctx && ctx.mapAsMap ? new Map() : {}; - if (ctx && ctx.onCreate) ctx.onCreate(map); +/***/ }), - for (const item of this.items) item.addToJSMap(ctx, map); +/***/ 5976: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return map; - } +"use strict"; - toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - for (const item of this.items) { - if (!(item instanceof Pair)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); +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; } - - return super.toString(ctx, { - blockItem: n => n.str, - flowChars: { - start: '{', - end: '}' - }, - isMap: true, - itemIndent: ctx.indent || '' - }, onComment, onChompKeep); - } - } - -const MERGE_KEY = '<<'; -class Merge extends Pair { - constructor(pair) { - if (pair instanceof Pair) { - let seq = pair.value; - - if (!(seq instanceof YAMLSeq)) { - seq = new YAMLSeq(); - seq.items.push(pair.value); - seq.range = pair.value.range; - } - - super(pair.key, seq); - this.range = pair.range; - } else { - super(new Scalar(MERGE_KEY), new YAMLSeq()); +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; } - - this.type = Pair.Type.MERGE_PAIR; - } // 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 - - - addToJSMap(ctx, map) { - for (const { - source - } of this.value.items) { - if (!(source instanceof YAMLMap)) throw new Error('Merge sources must be maps'); - 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)) map[key] = value; + /** + * 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); } - } } - - return map; - } - - toString(ctx, onComment) { - const seq = this.value; - if (seq.items.length > 1) return super.toString(ctx, onComment); - this.value = seq.items[0]; - const str = super.toString(ctx, onComment); - this.value = seq; - return str; - } - + *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); + } } -const binaryOptions = { - defaultType: PlainValue.Type.BLOCK_LITERAL, - lineWidth: 76 -}; -const boolOptions = { - trueStr: 'true', - falseStr: 'false' -}; -const intOptions = { - asBigInt: false -}; -const nullOptions = { - nullStr: 'null' -}; -const strOptions = { - defaultType: PlainValue.Type.PLAIN, - doubleQuoted: { - jsonEncoding: false, - minMultiLineLength: 40 - }, - fold: { - lineWidth: 80, - minContentWidth: 20 - } -}; - -function resolveScalar(str, tags, scalarFallback) { - for (const { - format, - test, - resolve - } of tags) { - if (test) { - const match = str.match(test); - - if (match) { - let res = resolve.apply(null, match); - if (!(res instanceof Scalar)) res = new Scalar(res); - if (format) res.format = format; - return res; - } - } - } +exports.Lexer = Lexer; - if (scalarFallback) str = scalarFallback(str); - return new Scalar(str); -} -const FOLD_FLOW = 'flow'; -const FOLD_BLOCK = 'block'; -const FOLD_QUOTED = 'quoted'; // presumes i+1 is at the start of a line -// returns index of last newline in more-indented block +/***/ }), -const consumeMoreIndentedLines = (text, i) => { - let ch = text[i + 1]; +/***/ 1929: +/***/ ((__unused_webpack_module, exports) => { - while (ch === ' ' || ch === '\t') { - do { - ch = text[i += 1]; - } while (ch && ch !== '\n'); +"use strict"; - ch = text[i + 1]; - } - return i; -}; /** - * 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`. - * - * @param {string} text - * @param {string} indent - * @param {string} [mode='flow'] `'block'` prevents more-indented lines - * from being folded; `'quoted'` allows for `\` escapes, including escaped - * newlines - * @param {Object} options - * @param {number} [options.indentAtStart] Accounts for leading contents on - * the first line, defaulting to `indent.length` - * @param {number} [options.lineWidth=80] - * @param {number} [options.minContentWidth=20] Allow highly indented lines to - * stretch the line width - * @param {function} options.onFold Called once if the text is folded - * @param {function} options.onFold Called once if any line of text exceeds - * lineWidth characters + * 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; -function foldFlowLines(text, indent, mode, { - 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 - (typeof indentAtStart === 'number' ? indentAtStart : indent.length); - let split = undefined; - let prev = undefined; - let overflow = false; - let i = -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 === '\\') { - switch (text[i + 1]) { - case 'x': - i += 3; - break; - case 'u': - i += 5; - break; +/***/ }), - case 'U': - i += 9; - break; +/***/ 3328: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - default: - i += 1; - } - } +"use strict"; - 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; - } // i - 2 accounts for not-dropped last char + newline-escaping \ - - - folds.push(i - 2); - escapedFolds[i - 2] = true; - end = i - 2 + endStep; - split = undefined; - } else { - overflow = true; +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; } - } } - - 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 (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; - res += `\n${indent}${text.slice(fold + 1, end)}`; - } - - return res; + return -1; } - -const getFoldOptions = ({ - indentAtStart -}) => indentAtStart ? Object.assign({ - indentAtStart -}, strOptions.fold) : strOptions.fold; // 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, limit) { - 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; +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; } - } - - return true; } - -function doubleQuotedString(value, ctx) { - const { - implicitKey - } = ctx; - const { - jsonEncoding, - minMultiLineLength - } = strOptions.doubleQuoted; - const json = JSON.stringify(value); - if (jsonEncoding) return json; - 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; +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; } - 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; + 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; + } } - - break; - - default: - i += 1; } - } - - str = start ? str + json.slice(start) : json; - return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx)); -} - -function singleQuotedString(value, ctx) { - if (ctx.implicitKey) { - if (/\n/.test(value)) return doubleQuotedString(value, ctx); - } else { - // single quoted string can't have leading or trailing whitespace around newline - if (/[ \t]\n|\n[ \t]/.test(value)) 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(res, indent, FOLD_FLOW, getFoldOptions(ctx)); } - -function blockString({ - comment, - type, - value -}, ctx, onComment, onChompKeep) { - // 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 (/\n[\t ]+$/.test(value) || /^\s*$/.test(value)) { - return doubleQuotedString(value, ctx); - } - - const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : ''); - const indentSize = indent ? '2' : '1'; // root is at -1 - - const literal = type === PlainValue.Type.BLOCK_FOLDED ? false : type === PlainValue.Type.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, strOptions.fold.lineWidth - indent.length); - let header = literal ? '|' : '>'; - if (!value) return header + '\n'; - let wsStart = ''; - let wsEnd = ''; - value = value.replace(/[\n\t ]*$/, ws => { - const n = ws.indexOf('\n'); - - if (n === -1) { - header += '-'; // strip - } else if (value === ws || n !== ws.length - 1) { - header += '+'; // keep - - if (onChompKeep) onChompKeep(); +/** + * 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; } - - wsEnd = ws.replace(/\n$/, ''); - return ''; - }).replace(/^[\n ]*/, ws => { - if (ws.indexOf(' ') !== -1) header += indentSize; - const m = ws.match(/ +$/); - - if (m) { - wsStart = ws.slice(0, -m[0].length); - return m[0]; - } else { - wsStart = ws; - return ''; + /** + * 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(); + } } - }); - if (wsEnd) wsEnd = wsEnd.replace(/\n+(?!\n|$)/g, `$&${indent}`); - if (wsStart) wsStart = wsStart.replace(/\n+/g, `$&${indent}`); - - if (comment) { - header += ' #' + comment.replace(/ ?[\r\n]+/g, ' '); - if (onComment) onComment(); - } - - if (!value) return `${header}${indentSize}\n${indent}${wsEnd}`; - - if (literal) { - value = value.replace(/\n+/g, `$&${indent}`); - return `${header}\n${indent}${wsStart}${value}${wsEnd}`; - } - - value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded - // ^ ind.line ^ empty ^ capture next empty lines only at end of indent - .replace(/\n+/g, `$&${indent}`); - const body = foldFlowLines(`${wsStart}${value}${wsEnd}`, indent, FOLD_BLOCK, strOptions.fold); - return `${header}\n${indent}${body}`; } -function plainString(item, ctx, onComment, onChompKeep) { - const { - comment, - type, - value - } = item; - const { - actualString, - implicitKey, - indent, - inFlow - } = ctx; +exports.Parser = Parser; - if (implicitKey && /[\n[\]{},]/.test(value) || inFlow && /[[\]{},]/.test(value)) { - return doubleQuotedString(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.indexOf('\n') === -1 ? value.indexOf('"') !== -1 && value.indexOf("'") === -1 ? singleQuotedString(value, ctx) : doubleQuotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); - } +/***/ }), - if (!implicitKey && !inFlow && type !== PlainValue.Type.PLAIN && value.indexOf('\n') !== -1) { - // Where allowed & type not set explicitly, prefer block style for multiline strings - return blockString(item, ctx, onComment, onChompKeep); - } +/***/ 8649: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (indent === '' && containsDocumentMarker(value)) { - ctx.forceBlockIndent = true; - return blockString(item, ctx, onComment, onChompKeep); - } +"use strict"; - 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 { - tags - } = ctx.doc.schema; - const resolved = resolveScalar(str, tags, tags.scalarFallback).value; - if (typeof resolved !== 'string') return doubleQuotedString(value, ctx); - } +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); - const body = implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx)); +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); +} - if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { - if (onComment) onComment(); - return addCommentBefore(body, indent, comment); - } +exports.parse = parse; +exports.parseAllDocuments = parseAllDocuments; +exports.parseDocument = parseDocument; +exports.stringify = stringify; - return body; -} -function stringifyString(item, ctx, onComment, onChompKeep) { - const { - defaultType - } = strOptions; - const { - implicitKey, - inFlow - } = ctx; - let { - type, - value - } = item; - - if (typeof value !== 'string') { - value = String(value); - item = Object.assign({}, item, { - value - }); - } +/***/ }), - const _stringify = _type => { - switch (_type) { - case PlainValue.Type.BLOCK_FOLDED: - case PlainValue.Type.BLOCK_LITERAL: - return blockString(item, ctx, onComment, onChompKeep); +/***/ 6831: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case PlainValue.Type.QUOTE_DOUBLE: - return doubleQuotedString(value, ctx); +"use strict"; - case PlainValue.Type.QUOTE_SINGLE: - return singleQuotedString(value, ctx); - case PlainValue.Type.PLAIN: - return plainString(item, ctx, onComment, onChompKeep); +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); - default: - return null; +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; } - }; +} - if (type !== PlainValue.Type.QUOTE_DOUBLE && /[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(value)) { - // force double quotes on control characters - type = PlainValue.Type.QUOTE_DOUBLE; - } else if ((implicitKey || inFlow) && (type === PlainValue.Type.BLOCK_FOLDED || type === PlainValue.Type.BLOCK_LITERAL)) { - // should not happen; blocks are not valid inside flow containers - type = PlainValue.Type.QUOTE_DOUBLE; - } +exports.Schema = Schema; - let res = _stringify(type); - if (res === null) { - res = _stringify(defaultType); - if (res === null) throw new Error(`Unsupported default string type ${defaultType}`); - } +/***/ }), - return res; -} +/***/ 83: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; -function stringifyNumber({ - format, - minFractionDigits, - tag, - value -}) { - if (typeof value === 'bigint') return String(value); - if (!isFinite(value)) return isNaN(value) ? '.nan' : value < 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('.'); +var Node = __nccwpck_require__(1399); +var Pair = __nccwpck_require__(246); +var YAMLMap = __nccwpck_require__(6011); - if (i < 0) { - i = n.length; - n += '.'; +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; } +}; - let d = minFractionDigits - (n.length - i - 1); +exports.map = map; - while (d-- > 0) n += '0'; - } - return n; -} +/***/ }), -function checkFlowCollectionEnd(errors, cst) { - let char, name; +/***/ 6703: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - switch (cst.type) { - case PlainValue.Type.FLOW_MAP: - char = '}'; - name = 'flow map'; - break; +"use strict"; - case PlainValue.Type.FLOW_SEQ: - char = ']'; - name = 'flow sequence'; - break; - default: - errors.push(new PlainValue.YAMLSemanticError(cst, 'Not a flow collection!?')); - return; - } +var Scalar = __nccwpck_require__(9338); - let lastItem; +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 +}; - for (let i = cst.items.length - 1; i >= 0; --i) { - const item = cst.items[i]; +exports.nullTag = nullTag; - if (!item || item.type !== PlainValue.Type.COMMENT) { - lastItem = item; - break; - } - } - if (lastItem && lastItem.char !== char) { - const msg = `Expected ${name} to end with ${char}`; - let err; +/***/ }), - if (typeof lastItem.offset === 'number') { - err = new PlainValue.YAMLSemanticError(cst, msg); - err.offset = lastItem.offset + 1; - } else { - err = new PlainValue.YAMLSemanticError(lastItem, msg); - if (lastItem.range && lastItem.range.end) err.offset = lastItem.range.end - lastItem.range.start; - } +/***/ 1693: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - errors.push(err); - } -} -function checkFlowCommentSpace(errors, comment) { - const prev = comment.context.src[comment.range.start - 1]; +"use strict"; - if (prev !== '\n' && prev !== '\t' && prev !== ' ') { - const msg = 'Comments must be separated from other tokens by white space characters'; - errors.push(new PlainValue.YAMLSemanticError(comment, msg)); - } -} -function getLongKeyError(source, key) { - const sk = String(key); - const k = sk.substr(0, 8) + '...' + sk.substr(-8); - return new PlainValue.YAMLSemanticError(source, `The "${k}" key is too long`); -} -function resolveComments(collection, comments) { - for (const { - afterKey, - before, - comment - } of comments) { - let item = collection.items[before]; - if (!item) { - if (comment !== undefined) { - if (collection.comment) collection.comment += '\n' + comment;else collection.comment = comment; - } - } else { - if (afterKey && item.value) item = item.value; +var createNode = __nccwpck_require__(9652); +var Node = __nccwpck_require__(1399); +var YAMLSeq = __nccwpck_require__(5161); - if (comment === undefined) { - if (afterKey || !item.commentBefore) item.spaceBefore = true; - } else { - if (item.commentBefore) item.commentBefore += '\n' + comment;else item.commentBefore = comment; - } +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)); + } } - } -} - -// on error, will return { str: string, errors: Error[] } -function resolveString(doc, node) { - const res = node.strValue; - if (!res) return ''; - if (typeof res === 'string') return res; - res.errors.forEach(error => { - if (!error.source) error.source = node; - doc.errors.push(error); - }); - return res.str; + 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; + } +}; -function resolveTagHandle(doc, node) { - const { - handle, - suffix - } = node.tag; - let prefix = doc.tagPrefixes.find(p => p.handle === handle); - - if (!prefix) { - const dtp = doc.getDefaults().tagPrefixes; - if (dtp) prefix = dtp.find(p => p.handle === handle); - if (!prefix) throw new PlainValue.YAMLSemanticError(node, `The ${handle} tag handle is non-default and was not declared.`); - } +exports.seq = seq; - if (!suffix) throw new PlainValue.YAMLSemanticError(node, `The ${handle} tag has no suffix.`); - if (handle === '!' && (doc.version || doc.options.version) === '1.0') { - if (suffix[0] === '^') { - doc.warnings.push(new PlainValue.YAMLWarning(node, 'YAML 1.0 ^ tag expansion is not supported')); - return suffix; - } +/***/ }), - if (/[:/]/.test(suffix)) { - // word/foo -> tag:word.yaml.org,2002:foo - const vocab = suffix.match(/^([a-z0-9-]+)\/(.*)/i); - return vocab ? `tag:${vocab[1]}.yaml.org,2002:${vocab[2]}` : `tag:${suffix}`; - } - } +/***/ 2201: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return prefix.prefix + decodeURIComponent(suffix); -} +"use strict"; -function resolveTagName(doc, node) { - const { - tag, - type - } = node; - let nonSpecific = false; - if (tag) { - const { - handle, - suffix, - verbatim - } = tag; +var stringifyString = __nccwpck_require__(6226); - if (verbatim) { - if (verbatim !== '!' && verbatim !== '!!') return verbatim; - const msg = `Verbatim tags aren't resolved, so ${verbatim} is invalid.`; - doc.errors.push(new PlainValue.YAMLSemanticError(node, msg)); - } else if (handle === '!' && !suffix) { - nonSpecific = true; - } else { - try { - return resolveTagHandle(doc, node); - } catch (error) { - doc.errors.push(error); - } +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); } - } +}; - switch (type) { - case PlainValue.Type.BLOCK_FOLDED: - case PlainValue.Type.BLOCK_LITERAL: - case PlainValue.Type.QUOTE_DOUBLE: - case PlainValue.Type.QUOTE_SINGLE: - return PlainValue.defaultTags.STR; +exports.string = string; - case PlainValue.Type.FLOW_MAP: - case PlainValue.Type.MAP: - return PlainValue.defaultTags.MAP; - case PlainValue.Type.FLOW_SEQ: - case PlainValue.Type.SEQ: - return PlainValue.defaultTags.SEQ; +/***/ }), - case PlainValue.Type.PLAIN: - return nonSpecific ? PlainValue.defaultTags.STR : null; +/***/ 2045: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - default: - return null; - } -} +"use strict"; -function resolveByTagName(doc, node, tagName) { - const { - tags - } = doc.schema; - const matchWithTest = []; - for (const tag of tags) { - if (tag.tag === tagName) { - if (tag.test) matchWithTest.push(tag);else { - const res = tag.resolve(doc, node); - return res instanceof Collection ? res : new Scalar(res); - } - } - } +var Scalar = __nccwpck_require__(9338); - const str = resolveString(doc, node); - if (typeof str === 'string' && matchWithTest.length > 0) return resolveScalar(str, matchWithTest, tags.scalarFallback); - return null; -} +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; + } +}; -function getFallbackTagName({ - type -}) { - switch (type) { - case PlainValue.Type.FLOW_MAP: - case PlainValue.Type.MAP: - return PlainValue.defaultTags.MAP; +exports.boolTag = boolTag; - case PlainValue.Type.FLOW_SEQ: - case PlainValue.Type.SEQ: - return PlainValue.defaultTags.SEQ; - default: - return PlainValue.defaultTags.STR; - } -} +/***/ }), -function resolveTag(doc, node, tagName) { - try { - const res = resolveByTagName(doc, node, tagName); +/***/ 6810: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (res) { - if (tagName && node.tag) res.tag = tagName; - return res; - } - } catch (error) { - /* istanbul ignore if */ - if (!error.source) error.source = node; - doc.errors.push(error); - return null; - } +"use strict"; - try { - const fallback = getFallbackTagName(node); - if (!fallback) throw new Error(`The tag ${tagName} is unavailable`); - const msg = `The tag ${tagName} is unavailable, falling back to ${fallback}`; - doc.warnings.push(new PlainValue.YAMLWarning(node, msg)); - const res = resolveByTagName(doc, node, fallback); - res.tag = tagName; - return res; - } catch (error) { - const refError = new PlainValue.YAMLReferenceError(node, error.message); - refError.stack = error.stack; - doc.errors.push(refError); - return null; - } -} -const isCollectionItem = node => { - if (!node) return false; - const { - type - } = node; - return type === PlainValue.Type.MAP_KEY || type === PlainValue.Type.MAP_VALUE || type === PlainValue.Type.SEQ_ITEM; +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 }; -function resolveNodeProps(errors, node) { - const comments = { - before: [], - after: [] - }; - let hasAnchor = false; - let hasTag = false; - const props = isCollectionItem(node.context.parent) ? node.context.parent.props.concat(node.props) : node.props; - - for (const { - start, - end - } of props) { - switch (node.context.src[start]) { - case PlainValue.Char.COMMENT: - { - if (!node.commentHasRequiredWhitespace(start)) { - const msg = 'Comments must be separated from other tokens by white space characters'; - errors.push(new PlainValue.YAMLSemanticError(node, msg)); - } +exports.float = float; +exports.floatExp = floatExp; +exports.floatNaN = floatNaN; - const { - header, - valueRange - } = node; - const cc = valueRange && (start > valueRange.start || header && start > header.start) ? comments.after : comments.before; - cc.push(node.context.src.slice(start + 1, end)); - break; - } - // Actual anchor & tag resolution is handled by schema, here we just complain - case PlainValue.Char.ANCHOR: - if (hasAnchor) { - const msg = 'A node can have at most one anchor'; - errors.push(new PlainValue.YAMLSemanticError(node, msg)); - } +/***/ }), - hasAnchor = true; - break; +/***/ 3019: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case PlainValue.Char.TAG: - if (hasTag) { - const msg = 'A node can have at most one tag'; - errors.push(new PlainValue.YAMLSemanticError(node, msg)); - } +"use strict"; - hasTag = true; - break; - } - } - return { - comments, - hasAnchor, - hasTag - }; -} +var stringifyNumber = __nccwpck_require__(4174); -function resolveNodeValue(doc, node) { - const { - anchors, - errors, - schema - } = doc; +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') +}; - if (node.type === PlainValue.Type.ALIAS) { - const name = node.rawValue; - const src = anchors.getNode(name); +exports.int = int; +exports.intHex = intHex; +exports.intOct = intOct; - if (!src) { - const msg = `Aliased anchor not found: ${name}`; - errors.push(new PlainValue.YAMLReferenceError(node, msg)); - return null; - } // Lazy resolution for circular references +/***/ }), - const res = new Alias(src); +/***/ 27: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - anchors._cstAliases.push(res); +"use strict"; - return res; - } - const tagName = resolveTagName(doc, node); - if (tagName) return resolveTag(doc, node, tagName); +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 +]; - if (node.type !== PlainValue.Type.PLAIN) { - const msg = `Failed to resolve ${node.type} node here`; - errors.push(new PlainValue.YAMLSyntaxError(node, msg)); - return null; - } +exports.schema = schema; - try { - const str = resolveString(doc, node); - return resolveScalar(str, schema.tags, schema.tags.scalarFallback); - } catch (error) { - if (!error.source) error.source = node; - errors.push(error); - return null; - } -} // sets node.resolved on success +/***/ }), -function resolveNode(doc, node) { - if (!node) return null; - if (node.error) doc.errors.push(node.error); - const { - comments, - hasAnchor, - hasTag - } = resolveNodeProps(doc.errors, node); +/***/ 4545: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (hasAnchor) { - const { - anchors - } = doc; - const name = node.anchor; - const prev = anchors.getNode(name); // At this point, aliases for any preceding node with the same anchor - // name have already been resolved, so it may safely be renamed. +"use strict"; - if (prev) anchors.map[anchors.newName(name)] = prev; // During parsing, we need to store the CST node in anchors.map as - // anchors need to be available during resolution to allow for - // circular references. - anchors.map[name] = node; - } +var Scalar = __nccwpck_require__(9338); +var map = __nccwpck_require__(83); +var seq = __nccwpck_require__(1693); - if (node.type === PlainValue.Type.ALIAS && (hasAnchor || hasTag)) { - const msg = 'An alias node must not specify any properties'; - doc.errors.push(new PlainValue.YAMLSemanticError(node, msg)); - } +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); - const res = resolveNodeValue(doc, node); +exports.schema = schema; - if (res) { - res.range = [node.range.start, node.range.end]; - if (doc.options.keepCstNodes) res.cstNode = node; - if (doc.options.keepNodeTypes) res.type = node.type; - const cb = comments.before.join('\n'); - if (cb) { - res.commentBefore = res.commentBefore ? `${res.commentBefore}\n${cb}` : cb; - } +/***/ }), - const ca = comments.after.join('\n'); - if (ca) res.comment = res.comment ? `${res.comment}\n${ca}` : ca; - } +/***/ 4138: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return node.resolved = res; -} +"use strict"; -function resolveMap(doc, cst) { - if (cst.type !== PlainValue.Type.MAP && cst.type !== PlainValue.Type.FLOW_MAP) { - const msg = `A ${cst.type} node cannot be resolved as a mapping`; - doc.errors.push(new PlainValue.YAMLSyntaxError(cst, msg)); - return null; - } - const { - comments, - items - } = cst.type === PlainValue.Type.FLOW_MAP ? resolveFlowMapItems(doc, cst) : resolveBlockMapItems(doc, cst); - const map = new YAMLMap(); - map.items = items; - resolveComments(map, comments); - let hasCollectionKey = false; - - for (let i = 0; i < items.length; ++i) { - const { - key: iKey - } = items[i]; - if (iKey instanceof Collection) hasCollectionKey = true; - - if (doc.schema.merge && iKey && iKey.value === MERGE_KEY) { - items[i] = new Merge(items[i]); - const sources = items[i].value.items; - let error = null; - sources.some(node => { - if (node instanceof Alias) { - // During parsing, alias sources are CST nodes; to account for - // circular references their resolved values can't be used here. - const { - type - } = node.source; - if (type === PlainValue.Type.MAP || type === PlainValue.Type.FLOW_MAP) return false; - return error = 'Merge nodes aliases can only point to maps'; - } - - return error = 'Merge nodes can only have Alias nodes as values'; - }); - if (error) doc.errors.push(new PlainValue.YAMLSemanticError(cst, error)); - } else { - for (let j = i + 1; j < items.length; ++j) { - const { - key: jKey - } = items[j]; - - if (iKey === jKey || iKey && jKey && Object.prototype.hasOwnProperty.call(iKey, 'value') && iKey.value === jKey.value) { - const msg = `Map keys must be unique; "${iKey}" is repeated`; - doc.errors.push(new PlainValue.YAMLSemanticError(cst, msg)); - break; +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__(4545); +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}`); + }); +} - if (hasCollectionKey && !doc.options.mapAsMap) { - const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; - doc.warnings.push(new PlainValue.YAMLWarning(cst, warn)); - } +exports.coreKnownTags = coreKnownTags; +exports.getTags = getTags; - cst.resolved = map; - return map; -} -const valueHasPairComment = ({ - context: { - lineStart, - node, - src - }, - props -}) => { - if (props.length === 0) return false; - const { - start - } = props[0]; - if (node && start > node.valueRange.start) return false; - if (src[start] !== PlainValue.Char.COMMENT) return false; +/***/ }), - for (let i = lineStart; i < start; ++i) if (src[i] === '\n') return false; +/***/ 5724: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return true; -}; +"use strict"; -function resolvePairComment(item, pair) { - if (!valueHasPairComment(item)) return; - const comment = item.getPropValue(0, PlainValue.Char.COMMENT, true); - let found = false; - const cb = pair.value.commentBefore; - if (cb && cb.startsWith(comment)) { - pair.value.commentBefore = cb.substr(comment.length + 1); - found = true; - } else { - const cc = pair.value.comment; +var Scalar = __nccwpck_require__(9338); +var stringifyString = __nccwpck_require__(6226); - if (!item.node && cc && cc.startsWith(comment)) { - pair.value.comment = cc.substr(comment.length + 1); - found = true; +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); } - } +}; - if (found) pair.comment = comment; -} +exports.binary = binary; -function resolveBlockMapItems(doc, cst) { - const comments = []; - const items = []; - let key = undefined; - let keyStart = null; - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; +/***/ }), - switch (item.type) { - case PlainValue.Type.BLANK_LINE: - comments.push({ - afterKey: !!key, - before: items.length - }); - break; +/***/ 2631: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - case PlainValue.Type.COMMENT: - comments.push({ - afterKey: !!key, - before: items.length, - comment: item.comment - }); - break; +"use strict"; - case PlainValue.Type.MAP_KEY: - if (key !== undefined) items.push(new Pair(key)); - if (item.error) doc.errors.push(item.error); - key = resolveNode(doc, item.node); - keyStart = null; - break; - case PlainValue.Type.MAP_VALUE: - { - if (key === undefined) key = null; - if (item.error) doc.errors.push(item.error); +var Scalar = __nccwpck_require__(9338); - if (!item.context.atLineStart && item.node && item.node.type === PlainValue.Type.MAP && !item.node.context.atLineStart) { - const msg = 'Nested mappings are not allowed in compact mappings'; - doc.errors.push(new PlainValue.YAMLSemanticError(item.node, msg)); - } +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 +}; - let valueNode = item.node; +exports.falseTag = falseTag; +exports.trueTag = trueTag; - if (!valueNode && item.props.length > 0) { - // Comments on an empty mapping value need to be preserved, so we - // need to construct a minimal empty node here to use instead of the - // missing `item.node`. -- eemeli/yaml#19 - valueNode = new PlainValue.PlainValue(PlainValue.Type.PLAIN, []); - valueNode.context = { - parent: item, - src: item.context.src - }; - const pos = item.range.start + 1; - valueNode.range = { - start: pos, - end: pos - }; - valueNode.valueRange = { - start: pos, - end: pos - }; - if (typeof item.range.origStart === 'number') { - const origPos = item.range.origStart + 1; - valueNode.range.origStart = valueNode.range.origEnd = origPos; - valueNode.valueRange.origStart = valueNode.valueRange.origEnd = origPos; - } - } +/***/ }), + +/***/ 8035: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const pair = new Pair(key, resolveNode(doc, valueNode)); - resolvePairComment(item, pair); - items.push(pair); +"use strict"; - if (key && typeof keyStart === 'number') { - if (item.range.start > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); - } - key = undefined; - keyStart = null; +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; } - break; + return node; + }, + stringify: stringifyNumber.stringifyNumber +}; - default: - if (key !== undefined) items.push(new Pair(key)); - key = resolveNode(doc, item); - keyStart = item.range.start; - if (item.error) doc.errors.push(item.error); +exports.float = float; +exports.floatExp = floatExp; +exports.floatNaN = floatNaN; - next: for (let j = i + 1;; ++j) { - const nextItem = cst.items[j]; - switch (nextItem && nextItem.type) { - case PlainValue.Type.BLANK_LINE: - case PlainValue.Type.COMMENT: - continue next; +/***/ }), - case PlainValue.Type.MAP_VALUE: - break next; +/***/ 9503: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - default: - { - const msg = 'Implicit map keys need to be followed by map values'; - doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); - break next; - } - } - } +"use strict"; - if (item.valueRangeContainsNewline) { - const msg = 'Implicit map keys need to be on a single line'; - doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); - } +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; } - } - - if (key !== undefined) items.push(new Pair(key)); - return { - comments, - items - }; + 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') +}; -function resolveFlowMapItems(doc, cst) { - const comments = []; - const items = []; - let key = undefined; - let explicitKey = false; - let next = '{'; +exports.int = int; +exports.intBin = intBin; +exports.intHex = intHex; +exports.intOct = intOct; - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - if (typeof item.char === 'string') { - const { - char, - offset - } = item; +/***/ }), - if (char === '?' && key === undefined && !explicitKey) { - explicitKey = true; - next = ':'; - continue; - } +/***/ 8974: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (char === ':') { - if (key === undefined) key = null; +"use strict"; - if (next === ':') { - next = ','; - continue; - } - } else { - if (explicitKey) { - if (key === undefined && char !== ',') key = null; - explicitKey = false; - } - if (key !== undefined) { - items.push(new Pair(key)); - key = undefined; +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); - if (char === ',') { - next = ':'; - continue; - } +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`, + * 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); } - } - - if (char === '}') { - if (i === cst.items.length - 1) continue; - } else if (char === next) { - next = ':'; - continue; - } - - const msg = `Flow map contains an unexpected ${char}`; - const err = new PlainValue.YAMLSyntaxError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } else if (item.type === PlainValue.Type.BLANK_LINE) { - comments.push({ - afterKey: !!key, - before: items.length - }); - } else if (item.type === PlainValue.Type.COMMENT) { - checkFlowCommentSpace(doc.errors, item); - comments.push({ - afterKey: !!key, - before: items.length, - comment: item.comment - }); - } else if (key === undefined) { - if (next === ',') doc.errors.push(new PlainValue.YAMLSemanticError(item, 'Separator , missing in flow map')); - key = resolveNode(doc, item); - } else { - if (next !== ',') doc.errors.push(new PlainValue.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); - items.push(new Pair(key, resolveNode(doc, item))); - key = undefined; - explicitKey = false; + return map; } - } - - checkFlowCollectionEnd(doc.errors, cst); - if (key !== undefined) items.push(new Pair(key)); - return { - comments, - items - }; } +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; + } +}; -function resolveSeq(doc, cst) { - if (cst.type !== PlainValue.Type.SEQ && cst.type !== PlainValue.Type.FLOW_SEQ) { - const msg = `A ${cst.type} node cannot be resolved as a sequence`; - doc.errors.push(new PlainValue.YAMLSyntaxError(cst, msg)); - return null; - } +exports.YAMLOMap = YAMLOMap; +exports.omap = omap; - const { - comments, - items - } = cst.type === PlainValue.Type.FLOW_SEQ ? resolveFlowSeqItems(doc, cst) : resolveBlockSeqItems(doc, cst); - const seq = new YAMLSeq(); - seq.items = items; - resolveComments(seq, comments); - if (!doc.options.mapAsMap && items.some(it => it instanceof Pair && it.key instanceof Collection)) { - const warn = 'Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.'; - doc.warnings.push(new PlainValue.YAMLWarning(cst, warn)); - } +/***/ }), - cst.resolved = seq; - return seq; -} +/***/ 9841: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function resolveBlockSeqItems(doc, cst) { - const comments = []; - const items = []; +"use strict"; - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - switch (item.type) { - case PlainValue.Type.BLANK_LINE: - comments.push({ - before: items.length - }); - break; +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 +}; - case PlainValue.Type.COMMENT: - comments.push({ - comment: item.comment, - before: items.length - }); - break; +exports.createPairs = createPairs; +exports.pairs = pairs; +exports.resolvePairs = resolvePairs; - case PlainValue.Type.SEQ_ITEM: - if (item.error) doc.errors.push(item.error); - items.push(resolveNode(doc, item.node)); - if (item.hasProps) { - const msg = 'Sequence items cannot have tags or anchors before the - indicator'; - doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); - } +/***/ }), - break; +/***/ 5389: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - default: - if (item.error) doc.errors.push(item.error); - doc.errors.push(new PlainValue.YAMLSyntaxError(item, `Unexpected ${item.type} node in sequence`)); - } - } +"use strict"; - return { - comments, - items - }; -} -function resolveFlowSeqItems(doc, cst) { - const comments = []; - const items = []; - let explicitKey = false; - let key = undefined; - let keyStart = null; - let next = '['; - let prevItem = null; - - for (let i = 0; i < cst.items.length; ++i) { - const item = cst.items[i]; - - if (typeof item.char === 'string') { - const { - char, - offset - } = item; - - if (char !== ':' && (explicitKey || key !== undefined)) { - if (explicitKey && key === undefined) key = next ? items.pop() : null; - items.push(new Pair(key)); - explicitKey = false; - key = undefined; - keyStart = null; - } +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 +]; - if (char === next) { - next = null; - } else if (!next && char === '?') { - explicitKey = true; - } else if (next !== '[' && char === ':' && key === undefined) { - if (next === ',') { - key = items.pop(); - - if (key instanceof Pair) { - const msg = 'Chaining flow sequence pairs is invalid'; - const err = new PlainValue.YAMLSemanticError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } +exports.schema = schema; - if (!explicitKey && typeof keyStart === 'number') { - const keyEnd = item.range ? item.range.start : item.offset; - if (keyEnd > keyStart + 1024) doc.errors.push(getLongKeyError(cst, key)); - const { - src - } = prevItem.context; - for (let i = keyStart; i < keyEnd; ++i) if (src[i] === '\n') { - const msg = 'Implicit keys of flow sequence pairs need to be on a single line'; - doc.errors.push(new PlainValue.YAMLSemanticError(prevItem, msg)); - break; - } - } - } else { - key = null; - } +/***/ }), - keyStart = null; - explicitKey = false; - next = null; - } else if (next === '[' || char !== ']' || i < cst.items.length - 1) { - const msg = `Flow sequence contains an unexpected ${char}`; - const err = new PlainValue.YAMLSyntaxError(cst, msg); - err.offset = offset; - doc.errors.push(err); - } - } else if (item.type === PlainValue.Type.BLANK_LINE) { - comments.push({ - before: items.length - }); - } else if (item.type === PlainValue.Type.COMMENT) { - checkFlowCommentSpace(doc.errors, item); - comments.push({ - comment: item.comment, - before: items.length - }); - } else { - if (next) { - const msg = `Expected a ${next} in flow sequence`; - doc.errors.push(new PlainValue.YAMLSemanticError(item, msg)); - } +/***/ 7847: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - const value = resolveNode(doc, item); +"use strict"; - if (key === undefined) { - items.push(value); - prevItem = item; - } else { - items.push(new Pair(key, value)); - key = undefined; - } - keyStart = item.range.start; - next = ','; +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'); } - } - - checkFlowCollectionEnd(doc.errors, cst); - if (key !== undefined) items.push(new Pair(key)); - return { - comments, - items - }; } +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.Alias = Alias; -exports.Collection = Collection; -exports.Merge = Merge; -exports.Node = Node; -exports.Pair = Pair; -exports.Scalar = Scalar; -exports.YAMLMap = YAMLMap; -exports.YAMLSeq = YAMLSeq; -exports.addComment = addComment; -exports.binaryOptions = binaryOptions; -exports.boolOptions = boolOptions; -exports.findPair = findPair; -exports.intOptions = intOptions; -exports.isEmptyPath = isEmptyPath; -exports.nullOptions = nullOptions; -exports.resolveMap = resolveMap; -exports.resolveNode = resolveNode; -exports.resolveSeq = resolveSeq; -exports.resolveString = resolveString; -exports.strOptions = strOptions; -exports.stringifyNumber = stringifyNumber; -exports.stringifyString = stringifyString; -exports.toJSON = toJSON; +exports.YAMLSet = YAMLSet; +exports.set = set; /***/ }), -/***/ 7383: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ 1156: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var PlainValue = __webpack_require__(5215); -var resolveSeq = __webpack_require__(6140); +var stringifyNumber = __nccwpck_require__(4174); -/* global atob, btoa, Buffer */ -const binary = { - identify: value => value instanceof Uint8Array, - // Buffer inherits from 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: (doc, node) => { - const src = resolveSeq.resolveString(doc, node); - - 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 { - const msg = 'This environment does not support reading binary tags; either Buffer or atob is required'; - doc.errors.push(new PlainValue.YAMLReferenceError(node, msg)); - return null; +/** 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 } - }, - options: resolveSeq.binaryOptions, - stringify: ({ - comment, - type, - value - }, ctx, onComment, onChompKeep) => { - let src; - - if (typeof Buffer === 'function') { - src = value instanceof Buffer ? value.toString('base64') : Buffer.from(value.buffer).toString('base64'); - } else if (typeof btoa === 'function') { - let s = ''; - - for (let i = 0; i < value.length; ++i) s += String.fromCharCode(value[i]); - - src = btoa(s); - } else { - throw new Error('This environment does not support writing binary tags; either Buffer or btoa 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$/, '') +}; - if (!type) type = resolveSeq.binaryOptions.defaultType; +exports.floatTime = floatTime; +exports.intTime = intTime; +exports.timestamp = timestamp; - if (type === PlainValue.Type.QUOTE_DOUBLE) { - value = src; - } else { - const { - lineWidth - } = resolveSeq.binaryOptions; - const n = Math.ceil(src.length / lineWidth); - const lines = new Array(n); - - for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { - lines[i] = src.substr(o, lineWidth); - } - value = lines.join(type === PlainValue.Type.BLOCK_LITERAL ? '\n' : ' '); - } +/***/ }), - return resolveSeq.stringifyString({ - comment, - type, - value - }, ctx, onComment, onChompKeep); - } -}; +/***/ 2889: +/***/ ((__unused_webpack_module, exports) => { -function parsePairs(doc, cst) { - const seq = resolveSeq.resolveSeq(doc, cst); +"use strict"; - for (let i = 0; i < seq.items.length; ++i) { - let item = seq.items[i]; - if (item instanceof resolveSeq.Pair) continue;else if (item instanceof resolveSeq.YAMLMap) { - if (item.items.length > 1) { - const msg = 'Each pair must have its own sequence indicator'; - throw new PlainValue.YAMLSemanticError(cst, msg); - } - const pair = item.items[0] || new resolveSeq.Pair(); - if (item.commentBefore) pair.commentBefore = pair.commentBefore ? `${item.commentBefore}\n${pair.commentBefore}` : item.commentBefore; - if (item.comment) pair.comment = pair.comment ? `${item.comment}\n${pair.comment}` : item.comment; - item = pair; +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)}`; + } } - seq.items[i] = item instanceof resolveSeq.Pair ? item : new resolveSeq.Pair(item); - } - - return seq; + return res; } -function createPairs(schema, iterable, ctx) { - const pairs = new resolveSeq.YAMLSeq(schema); - pairs.tag = 'tag:yaml.org,2002:pairs'; - - for (const it of iterable) { - 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; +/** + * 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]; } - - const pair = schema.createPair(key, value, ctx); - pairs.items.push(pair); - } - - return pairs; + return i; } -const pairs = { - default: false, - tag: 'tag:yaml.org,2002:pairs', - resolve: parsePairs, - createNode: createPairs -}; - -class YAMLOMap extends resolveSeq.YAMLSeq { - constructor() { - super(); - - PlainValue._defineProperty(this, "add", resolveSeq.YAMLMap.prototype.add.bind(this)); - - PlainValue._defineProperty(this, "delete", resolveSeq.YAMLMap.prototype.delete.bind(this)); - PlainValue._defineProperty(this, "get", resolveSeq.YAMLMap.prototype.get.bind(this)); +exports.FOLD_BLOCK = FOLD_BLOCK; +exports.FOLD_FLOW = FOLD_FLOW; +exports.FOLD_QUOTED = FOLD_QUOTED; +exports.foldFlowLines = foldFlowLines; - PlainValue._defineProperty(this, "has", resolveSeq.YAMLMap.prototype.has.bind(this)); - PlainValue._defineProperty(this, "set", resolveSeq.YAMLMap.prototype.set.bind(this)); - - this.tag = YAMLOMap.tag; - } +/***/ }), - toJSON(_, ctx) { - const map = new Map(); - if (ctx && ctx.onCreate) ctx.onCreate(map); +/***/ 8409: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (const pair of this.items) { - let key, value; +"use strict"; - if (pair instanceof resolveSeq.Pair) { - key = resolveSeq.toJSON(pair.key, '', ctx); - value = resolveSeq.toJSON(pair.value, key, ctx); - } else { - key = resolveSeq.toJSON(pair, '', ctx); - } - if (map.has(key)) throw new Error('Ordered maps must not include duplicate keys'); - map.set(key, value); +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 map; - } - + return { + anchors: new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '', + indent: '', + indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ', + inFlow, + options: opt + }; } - -PlainValue._defineProperty(YAMLOMap, "tag", 'tag:yaml.org,2002:omap'); - -function parseOMap(doc, cst) { - const pairs = parsePairs(doc, cst); - const seenKeys = []; - - for (const { - key - } of pairs.items) { - if (key instanceof resolveSeq.Scalar) { - if (seenKeys.includes(key.value)) { - const msg = 'Ordered maps must not include duplicate keys'; - throw new PlainValue.YAMLSemanticError(cst, msg); - } else { - seenKeys.push(key.value); - } +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); } - } - - return Object.assign(new YAMLOMap(), pairs); + 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; } - -function createOMap(schema, iterable, ctx) { - const pairs = createPairs(schema, iterable, ctx); - const omap = new YAMLOMap(); - omap.items = pairs.items; - return omap; +// 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}`; } -const omap = { - identify: value => value instanceof Map, - nodeClass: YAMLOMap, - default: false, - tag: 'tag:yaml.org,2002:omap', - resolve: parseOMap, - createNode: createOMap -}; - -class YAMLSet extends resolveSeq.YAMLMap { - constructor() { - super(); - this.tag = YAMLSet.tag; - } +exports.createStringifyContext = createStringifyContext; +exports.stringify = stringify; - add(key) { - const pair = key instanceof resolveSeq.Pair ? key : new resolveSeq.Pair(key); - const prev = resolveSeq.findPair(this.items, pair.key); - if (!prev) this.items.push(pair); - } - get(key, keepPair) { - const pair = resolveSeq.findPair(this.items, key); - return !keepPair && pair instanceof resolveSeq.Pair ? pair.key instanceof resolveSeq.Scalar ? 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 = resolveSeq.findPair(this.items, key); +/***/ 2466: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (prev && !value) { - this.items.splice(this.items.indexOf(prev), 1); - } else if (!prev && value) { - this.items.push(new resolveSeq.Pair(key)); - } - } +"use strict"; - toJSON(_, ctx) { - return super.toJSON(_, ctx, Set); - } - toString(ctx, onComment, onChompKeep) { - if (!ctx) return JSON.stringify(this); - if (this.hasAllNullValues()) return super.toString(ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values'); - } +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, indent, commentString(comment)); + 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 + } } -PlainValue._defineProperty(YAMLSet, "tag", 'tag:yaml.org,2002:set'); +exports.stringifyCollection = stringifyCollection; -function parseSet(doc, cst) { - const map = resolveSeq.resolveMap(doc, cst); - if (!map.hasAllNullValues()) throw new PlainValue.YAMLSemanticError(cst, 'Set items must all have null values'); - return Object.assign(new YAMLSet(), map); -} -function createSet(schema, iterable, ctx) { - const set = new YAMLSet(); +/***/ }), + +/***/ 5182: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; - for (const value of iterable) set.items.push(schema.createPair(value, null, ctx)); - return set; +/** + * 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; -const set = { - identify: value => value instanceof Set, - nodeClass: YAMLSet, - default: false, - tag: 'tag:yaml.org,2002:set', - resolve: parseSet, - createNode: createSet -}; +exports.indentComment = indentComment; +exports.lineComment = lineComment; +exports.stringifyComment = stringifyComment; -const parseSexagesimal = (sign, parts) => { - const n = parts.split(':').reduce((n, p) => n * 60 + Number(p), 0); - return sign === '-' ? -n : n; -}; // hhhh:mm:ss.sss +/***/ }), -const stringifySexagesimal = ({ - value -}) => { - if (isNaN(value) || !isFinite(value)) return resolveSeq.stringifyNumber(value); - let sign = ''; +/***/ 5225: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (value < 0) { - sign = '-'; - value = Math.abs(value); - } +"use strict"; - const parts = [value % 60]; // seconds, including ms - if (value < 60) { - parts.unshift(0); // at least one : is required - } else { - value = Math.round((value - parts[0]) / 60); - parts.unshift(value % 60); // minutes +var Node = __nccwpck_require__(1399); +var stringify = __nccwpck_require__(8409); +var stringifyComment = __nccwpck_require__(5182); - if (value >= 60) { - value = Math.round((value - parts[0]) / 60); - parts.unshift(value); // hours +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'; +} - return sign + parts.map(n => n < 10 ? '0' + String(n) : String(n)).join(':').replace(/000000\d*$/, '') // % 60 may introduce error - ; -}; +exports.stringifyDocument = stringifyDocument; -const intTime = { - identify: value => typeof value === 'number', - default: true, - tag: 'tag:yaml.org,2002:int', - format: 'TIME', - test: /^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/, - resolve: (str, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), - 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, sign, parts) => parseSexagesimal(sign, parts.replace(/_/g, '')), - 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 - '(?:(?: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, year, month, day, hour, minute, second, millisec, tz) => { - if (millisec) millisec = (millisec + '00').substr(1, 3); - let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec || 0); - - if (tz && tz !== 'Z') { - let d = parseSexagesimal(tz[0], tz.slice(1)); - if (Math.abs(d) < 30) d *= 60; - date -= 60000 * d; - } - - return new Date(date); - }, - stringify: ({ - value - }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, '') -}; -/* global console, process, YAML_SILENCE_DEPRECATION_WARNINGS, YAML_SILENCE_WARNINGS */ -function shouldWarn(deprecation) { - const env = typeof process !== 'undefined' && process.env || {}; +/***/ }), - if (deprecation) { - if (typeof YAML_SILENCE_DEPRECATION_WARNINGS !== 'undefined') return !YAML_SILENCE_DEPRECATION_WARNINGS; - return !env.YAML_SILENCE_DEPRECATION_WARNINGS; - } +/***/ 4174: +/***/ ((__unused_webpack_module, exports) => { - if (typeof YAML_SILENCE_WARNINGS !== 'undefined') return !YAML_SILENCE_WARNINGS; - return !env.YAML_SILENCE_WARNINGS; -} +"use strict"; -function warn(warning, type) { - if (shouldWarn(false)) { - const emit = typeof process !== 'undefined' && process.emitWarning; // This will throw in Jest if `warning` is an Error instance due to - // https://github.com/facebook/jest/issues/2549 - if (emit) emit(warning, type);else { - // eslint-disable-next-line no-console - console.warn(type ? `${type}: ${warning}` : warning); +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'; } - } -} -function warnFileDeprecation(filename) { - if (shouldWarn(true)) { - const path = filename.replace(/.*yaml[/\\]/i, '').replace(/\.js$/, '').replace(/\\/g, '/'); - warn(`The endpoint 'yaml/${path}' will be removed in a future release.`, 'DeprecationWarning'); - } -} -const warned = {}; -function warnOptionDeprecation(name, alternative) { - if (!warned[name] && shouldWarn(true)) { - warned[name] = true; - let msg = `The option '${name}' will be removed in a future release`; - msg += alternative ? `, use '${alternative}' instead.` : '.'; - warn(msg, 'DeprecationWarning'); - } + return n; } -exports.binary = binary; -exports.floatTime = floatTime; -exports.intTime = intTime; -exports.omap = omap; -exports.pairs = pairs; -exports.set = set; -exports.timestamp = timestamp; -exports.warn = warn; -exports.warnFileDeprecation = warnFileDeprecation; -exports.warnOptionDeprecation = warnOptionDeprecation; +exports.stringifyNumber = stringifyNumber; /***/ }), -/***/ 3552: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ 4875: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -module.exports = __webpack_require__(5065).YAML +"use strict"; -/***/ }), +var Node = __nccwpck_require__(1399); +var Scalar = __nccwpck_require__(9338); +var stringify = __nccwpck_require__(8409); +var stringifyComment = __nccwpck_require__(5182); -/***/ 2357: -/***/ ((module) => { +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; -"use strict"; -module.exports = require("assert"); /***/ }), -/***/ 3129: -/***/ ((module) => { +/***/ 6226: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -module.exports = require("child_process"); - -/***/ }), -/***/ 8614: -/***/ ((module) => { -"use strict"; -module.exports = require("events"); +var Scalar = __nccwpck_require__(9338); +var foldFlowLines = __nccwpck_require__(2889); -/***/ }), +const getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : 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, false)); +} +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, false)); +} +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, true)); + 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, false)); +} +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; +} -/***/ 5747: -/***/ ((module) => { +exports.stringifyString = stringifyString; -"use strict"; -module.exports = require("fs"); /***/ }), -/***/ 2087: -/***/ ((module) => { +/***/ 6796: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -module.exports = require("os"); -/***/ }), - -/***/ 5622: -/***/ ((module) => { -"use strict"; -module.exports = require("path"); +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`); + } +} -/***/ 1669: -/***/ ((module) => { +exports.visit = visit; +exports.visitAsync = visitAsync; -"use strict"; -module.exports = require("util"); /***/ }) @@ -14254,10 +18464,11 @@ module.exports = require("util"); /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function -/******/ function __webpack_require__(moduleId) { +/******/ function __nccwpck_require__(moduleId) { /******/ // Check if module is in cache -/******/ if(__webpack_module_cache__[moduleId]) { -/******/ return __webpack_module_cache__[moduleId].exports; +/******/ 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] = { @@ -14269,7 +18480,7 @@ module.exports = require("util"); /******/ // Execute the module function /******/ var threw = true; /******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete __webpack_module_cache__[moduleId]; @@ -14285,7 +18496,7 @@ module.exports = require("util"); /************************************************************************/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { -/******/ __webpack_require__.nmd = (module) => { +/******/ __nccwpck_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; @@ -14294,10 +18505,15 @@ module.exports = require("util"); /******/ /******/ /* webpack/runtime/compat */ /******/ -/******/ __webpack_require__.ab = __dirname + "/";/************************************************************************/ -/******/ // module exports must be returned from runtime so entry inlining is disabled +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; +/******/ +/************************************************************************/ +/******/ /******/ // startup /******/ // Load entry module and return exports -/******/ return __webpack_require__(2932); +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __nccwpck_require__(2932); +/******/ module.exports = __webpack_exports__; +/******/ /******/ })() ; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index ccedcc8..86ed66d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "lambda-monorepo", - "version": "0.2.0", + "version": "0.7.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "lambda-monorepo", - "version": "0.2.0", + "version": "0.7.0", "license": "MIT", "dependencies": { "@actions/core": "^1.9.1", @@ -14,7 +14,7 @@ "yaml": "^2.2.2" }, "devDependencies": { - "@vercel/ncc": "^0.24.0", + "@vercel/ncc": "^0.36.1", "jest": "^26.4.2" } }, @@ -1034,9 +1034,9 @@ "dev": true }, "node_modules/@vercel/ncc": { - "version": "0.24.1", - "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.24.1.tgz", - "integrity": "sha512-r9m7brz2hNmq5TF3sxrK4qR/FhXn44XIMglQUir4sT7Sh5GOaYXlMYikHFwJStf8rmQGTlvOoBXt4yHVonRG8A==", + "version": "0.36.1", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.36.1.tgz", + "integrity": "sha512-S4cL7Taa9yb5qbv+6wLgiKVZ03Qfkc4jGRuiUQMQ8HGBD5pcNRnHeYM33zBvJE4/zJGjJJ8GScB+WmTsn9mORw==", "dev": true, "bin": { "ncc": "dist/ncc/cli.js" @@ -6914,9 +6914,9 @@ "dev": true }, "@vercel/ncc": { - "version": "0.24.1", - "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.24.1.tgz", - "integrity": "sha512-r9m7brz2hNmq5TF3sxrK4qR/FhXn44XIMglQUir4sT7Sh5GOaYXlMYikHFwJStf8rmQGTlvOoBXt4yHVonRG8A==", + "version": "0.36.1", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.36.1.tgz", + "integrity": "sha512-S4cL7Taa9yb5qbv+6wLgiKVZ03Qfkc4jGRuiUQMQ8HGBD5pcNRnHeYM33zBvJE4/zJGjJJ8GScB+WmTsn9mORw==", "dev": true }, "abab": { diff --git a/package.json b/package.json index 659f474..d660ea8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lambda-monorepo", - "version": "0.2.0", + "version": "0.7.0", "description": "Deploy your AWS Lambda functions based on the files changed in a mono repo", "main": "dist/index.js", "scripts": { @@ -24,7 +24,7 @@ "yaml": "^2.2.2" }, "devDependencies": { - "@vercel/ncc": "^0.24.0", + "@vercel/ncc": "^0.36.1", "jest": "^26.4.2" } }