diff --git a/CHANGELOG.md b/CHANGELOG.md index 4726039..c54647e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ All notable changes to the InProd Run Changesets GitHub Action will be documente The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Changed + +- **Internal: now wraps the `run-changesets` CLI instead of duplicating its logic** — this action's changeset validation/execution/polling logic (`pollTask`, `validateFile`, `executeFile`, `resolveFiles`, etc.) was a hand-maintained copy of the same logic in the [`@inprod.io/run-changesets`](https://www.npmjs.com/package/@inprod.io/run-changesets) npm package. The two copies had already drifted (differing `Content-Type` handling on status polling, missing `INPROD_FILES` support here). This action now contains no changeset logic of its own — it maps its inputs to the `INPROD_*` environment variables `run-changesets` reads, spawns it as a subprocess, and maps its result files back into Action outputs. No change to inputs/outputs behavior, aside from the addition below. + +### Added + +- **`inprod_files` input** — upload files to InProd's temporary storage before running the changeset, in `VARNAME=path` format; their signed URLs are injected as changeset variables. Previously only available via the `run-changesets` CLI; now available here too as a direct consequence of the change above. + ## [1.0.1] - 2026-02-18 ### Fixed diff --git a/README.md b/README.md index 7c22205..4b1904d 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,23 @@ changeset_variables: | 3. InProd substitutes variable placeholders in the changeset with provided values 4. Changeset file remains clean and secret-free in version control +### `inprod_files` (optional) + +**Description:** Files to upload to InProd's temporary storage before running the changeset, in `VARNAME=path` format + +**Default:** None + +**Purpose:** Lets a changeset reference the contents of a file (e.g. a certificate, a config bundle) as an injected variable, without embedding the file's contents directly in the changeset or in `changeset_variables`. Each uploaded file's signed URL is merged into the changeset variables under the given name. + +**Format:** `VARNAME=path` pairs (one per line), same conventions as `changeset_variables`. See the [run-changesets README](https://github.com/inprod/run-changesets) for the full variable-name validation rules and upload behavior — this input passes straight through to it. + +**Example:** +```yaml +inprod_files: | + TLS_CERT=./certs/server.pem + CONFIG_BUNDLE=./bundles/prod.zip +``` + ## Output Reference ### `status` diff --git a/action.yml b/action.yml index 8c587aa..d859255 100644 --- a/action.yml +++ b/action.yml @@ -38,6 +38,9 @@ inputs: changeset_variables: description: 'Changeset variables in KEY=VALUE format (one per line). Allows injecting secrets from GitHub Secrets without storing in version control. See README for examples.' required: false + inprod_files: + description: 'Files to upload to temporary storage before running the changeset, in VARNAME=path format (one per line). Uploaded URLs are injected as changeset variables. See the run-changesets README for details.' + required: false outputs: status: diff --git a/dist/index.js b/dist/index.js index 3e19424..52cd5cb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -3193,4120 +3193,6 @@ function copyFile(srcFile, destFile, force) { } //# sourceMappingURL=io.js.map -/***/ }), - -/***/ 4281: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - - -var loader = __nccwpck_require__(1950); -var dumper = __nccwpck_require__(9980); - - -function renamed(from, to) { - return function () { - throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + - 'Use yaml.' + to + ' instead, which is now safe by default.'); - }; -} - - -module.exports.Type = __nccwpck_require__(9557); -module.exports.Schema = __nccwpck_require__(2046); -module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(9832); -module.exports.JSON_SCHEMA = __nccwpck_require__(8927); -module.exports.CORE_SCHEMA = __nccwpck_require__(5746); -module.exports.DEFAULT_SCHEMA = __nccwpck_require__(7336); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.dump = dumper.dump; -module.exports.YAMLException = __nccwpck_require__(1248); - -// Re-export all types in case user wants to create custom schema -module.exports.types = { - binary: __nccwpck_require__(8149), - float: __nccwpck_require__(7584), - map: __nccwpck_require__(7316), - null: __nccwpck_require__(4333), - pairs: __nccwpck_require__(6267), - set: __nccwpck_require__(8758), - timestamp: __nccwpck_require__(8966), - bool: __nccwpck_require__(7296), - int: __nccwpck_require__(4652), - merge: __nccwpck_require__(6854), - omap: __nccwpck_require__(8649), - seq: __nccwpck_require__(7161), - str: __nccwpck_require__(3929) -}; - -// Removed functions from JS-YAML 3.0.x -module.exports.safeLoad = renamed('safeLoad', 'load'); -module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); -module.exports.safeDump = renamed('safeDump', 'dump'); - - -/***/ }), - -/***/ 9816: -/***/ ((module) => { - -"use strict"; - - - -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} - - -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} - - -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; -} - - -function extend(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; - } - } - - return target; -} - - -function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } - - return result; -} - - -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} - - -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; - - -/***/ }), - -/***/ 9980: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/*eslint-disable no-use-before-define*/ - -var common = __nccwpck_require__(9816); -var YAMLException = __nccwpck_require__(1248); -var DEFAULT_SCHEMA = __nccwpck_require__(7336); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_BOM = 0xFEFF; -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; - -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - - if (map === null) return {}; - - result = {}; - keys = Object.keys(map); - - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); - } - type = schema.compiledTypeMap['fallback'][tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; - } - - result[tag] = style; - } - - return result; -} - -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} - - -var QUOTING_TYPE_SINGLE = 1, - QUOTING_TYPE_DOUBLE = 2; - -function State(options) { - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; - this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; - this.forceQuotes = options['forceQuotes'] || false; - this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; - - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; - - this.tag = null; - this.result = ''; - - this.duplicates = []; - this.usedDuplicates = null; -} - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; - } - - if (line.length && line !== '\n') result += ind; - - result += line; - } - - return result; -} - -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); -} - -function testImplicitResolving(state, str) { - var index, length, type; - - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - - if (type.resolve(str)) { - return true; - } - } - - return false; -} - -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; -} - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) - || (0x10000 <= c && c <= 0x10FFFF); -} - -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// Including s-white (for some reason, examples doesn't match specs in this aspect) -// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark -function isNsCharOrWhitespace(c) { - return isPrintable(c) - && c !== CHAR_BOM - // - b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; -} - -// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out -// c = flow-in ⇒ ns-plain-safe-in -// c = block-key ⇒ ns-plain-safe-out -// c = flow-key ⇒ ns-plain-safe-in -// [128] ns-plain-safe-out ::= ns-char -// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator -// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) -// | ( /* An ns-char preceding */ “#” ) -// | ( “:” /* Followed by an ns-plain-safe(c) */ ) -function isPlainSafe(c, prev, inblock) { - var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); - var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); - return ( - // ns-plain-safe - inblock ? // c = flow-in - cIsNsCharOrWhitespace - : cIsNsCharOrWhitespace - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - ) - // ns-plain-char - && c !== CHAR_SHARP // false on '#' - && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' - || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' - || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' -} - -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part - return isPrintable(c) && c !== CHAR_BOM - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} - -// Simplified test for values allowed as the last character in plain style. -function isPlainSafeLast(c) { - // just not whitespace or colon, it will be checked to be plain character later - return !isWhitespace(c) && c !== CHAR_COLON; -} - -// Same as 'string'.codePointAt(pos), but works in older browsers. -function codePointAt(string, pos) { - var first = string.charCodeAt(pos), second; - if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { - second = string.charCodeAt(pos + 1); - if (second >= 0xDC00 && second <= 0xDFFF) { - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; - } - } - return first; -} - -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} - -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; - -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, - testAmbiguousType, quotingType, forceQuotes, inblock) { - - var i; - var char = 0; - var prevChar = null; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(codePointAt(string, 0)) - && isPlainSafeLast(codePointAt(string, string.length - 1)); - - if (singleLineOnly || forceQuotes) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - if (plain && !forceQuotes && !testAmbiguousType(string)) { - return STYLE_PLAIN; - } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - if (!forceQuotes) { - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; - } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; -} - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey, inblock) { - state.dump = (function () { - if (string.length === 0) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; - } - if (!state.noCompatMode) { - if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); - } - } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); - } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, - testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { - - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); - } - }()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); - - return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; - - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; - - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; - - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 - } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } - - return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char = 0; - var escapeSeq; - - for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { - char = codePointAt(string, i); - escapeSeq = ESCAPE_SEQUENCES[char]; - - if (!escapeSeq && isPrintable(char)) { - result += string[i]; - if (char >= 0x10000) result += string[i + 1]; - } else { - result += escapeSeq || encodeHex(char); - } - } - - return result; -} - -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length, - value; - - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; - - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } - - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level, value, false, false) || - (typeof value === 'undefined' && - writeNode(state, level, null, false, false))) { - - if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; -} - -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length, - value; - - for (index = 0, length = object.length; index < length; index += 1) { - value = object[index]; - - if (state.replacer) { - value = state.replacer.call(object, String(index), value); - } - - // Write only valid elements, put null instead of invalid elements. - if (writeNode(state, level + 1, value, true, true, false, true) || - (typeof value === 'undefined' && - writeNode(state, level + 1, null, true, true, false, true))) { - - if (!compact || _result !== '') { - _result += generateNextLine(state, level); - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } - - _result += state.dump; - } - } - - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. -} - -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - - pairBuffer = ''; - if (_result !== '') pairBuffer += ', '; - - if (state.condenseFlow) pairBuffer += '"'; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = '{' + _result + '}'; -} - -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; - - if (!compact || _result !== '') { - pairBuffer += generateNextLine(state, level); - } - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (state.replacer) { - objectValue = state.replacer.call(object, objectKey, objectValue); - } - - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. - } - - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); - - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } - } - - pairBuffer += state.dump; - - if (explicitPair) { - pairBuffer += generateNextLine(state, level); - } - - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } - - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. -} - -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { - - if (explicit) { - if (type.multi && type.representName) { - state.tag = type.representName(object); - } else { - state.tag = type.tag; - } - } else { - state.tag = '?'; - } - - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; - - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); - } - - state.dump = _result; - } - - return true; - } - } - - return false; -} - -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey, isblockseq) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } - - var type = _toString.call(state.dump); - var inblock = block; - var tagStr; - - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } - - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; - - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } - - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } - - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object Array]') { - if (block && (state.dump.length !== 0)) { - if (state.noArrayIndent && !isblockseq && level > 0) { - writeBlockSequence(state, level - 1, state.dump, compact); - } else { - writeBlockSequence(state, level, state.dump, compact); - } - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; - } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey, inblock); - } - } else if (type === '[object Undefined]') { - return false; - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); - } - - if (state.tag !== null && state.tag !== '?') { - // Need to encode all characters except those allowed by the spec: - // - // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ - // [36] ns-hex-digit ::= ns-dec-digit - // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ - // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ - // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” - // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” - // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” - // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” - // - // Also need to encode '!' because it has special meaning (end of tag prefix). - // - tagStr = encodeURI( - state.tag[0] === '!' ? state.tag.slice(1) : state.tag - ).replace(/!/g, '%21'); - - if (state.tag[0] === '!') { - tagStr = '!' + tagStr; - } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { - tagStr = '!!' + tagStr.slice(18); - } else { - tagStr = '!<' + tagStr + '>'; - } - - state.dump = tagStr + ' ' + state.dump; - } - } - - return true; -} - -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); - - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} - -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; - - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); - - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); - } - } - } - } -} - -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - - var value = input; - - if (state.replacer) { - value = state.replacer.call({ '': value }, '', value); - } - - if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; - - return ''; -} - -module.exports.dump = dump; - - -/***/ }), - -/***/ 1248: -/***/ ((module) => { - -"use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// - - - -function formatError(exception, compact) { - var where = '', message = exception.reason || '(unknown reason)'; - - if (!exception.mark) return message; - - if (exception.mark.name) { - where += 'in "' + exception.mark.name + '" '; - } - - where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; - - if (!compact && exception.mark.snippet) { - where += '\n\n' + exception.mark.snippet; - } - - return message + ' ' + where; -} - - -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = formatError(this, false); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } -} - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - return this.name + ': ' + formatError(this, compact); -}; - - -module.exports = YAMLException; - - -/***/ }), - -/***/ 1950: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/*eslint-disable max-len,no-use-before-define*/ - -var common = __nccwpck_require__(9816); -var YAMLException = __nccwpck_require__(1248); -var makeSnippet = __nccwpck_require__(9440); -var DEFAULT_SCHEMA = __nccwpck_require__(7336); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function _class(obj) { return Object.prototype.toString.call(obj); } - -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; -} - -function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - /*eslint-disable no-bitwise*/ - lc = c | 0x20; - - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } - - return -1; -} - -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} - -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - - return -1; -} - -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} - -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} - -// set a property of a literal object, while protecting against prototype pollution, -// see https://github.com/nodeca/js-yaml/issues/164 for more details -function setProperty(object, key, value) { - // used for this specific key only because Object.defineProperty is slow - if (key === '__proto__') { - Object.defineProperty(object, key, { - configurable: true, - enumerable: true, - writable: true, - value: value - }); - } else { - object[key] = value; - } -} - -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); -} - - -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_SCHEMA; - this.onWarning = options['onWarning'] || null; - // (Hidden) Remove? makes the loader to expect YAML 1.1 documents - // if such documents have no explicit %YAML directive - this.legacy = options['legacy'] || false; - - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - // position of first leading tab in the current line, - // used to make sure there are no tabs in the indentation - this.firstTabInLine = -1; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - -} - - -function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; - - mark.snippet = makeSnippet(mark); - - return new YAMLException(message, mark); -} - -function throwError(state, message) { - throw generateError(state, message); -} - -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } -} - - -var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); - } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); - } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); - } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); - } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); - } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); - } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); - } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); - } - - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, 'tag prefix is malformed: ' + prefix); - } - - state.tagMap[handle] = prefix; - } -}; - - -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); - } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); - } - - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } - - sourceKeys = Object.keys(source); - - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; - - if (!_hasOwnProperty.call(destination, key)) { - setProperty(destination, key, source[key]); - overridableKeys[key] = true; - } - } -} - -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, - startLine, startLineStart, startPos) { - - var index, quantity; - - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } - - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } - - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } - - - keyNode = String(keyNode); - - if (_result === null) { - _result = {}; - } - - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - - setProperty(_result, keyNode, valueNode); - delete overridableKeys[keyNode]; - } - - return _result; -} - -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; -} - -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; - } - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); - } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; - } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; -} - -function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } - } - - return false; -} - -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } -} - - -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; - - ch = state.input.charCodeAt(state.position); - - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } - - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; - } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } - } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; - } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; - } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); -} - -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } - } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; - } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _lineStart, - _pos, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = Object.create(null), - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); - } else if (ch === 0x2C/* , */) { - // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 - throwError(state, "expected the node content, but found ','"); - } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } - } - - _line = state.line; // Save the current line. - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; - } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); - } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; - } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; - } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); - } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; - } - - if (is_EOL(ch)) { - emptyLines++; - continue; - } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; - } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; - } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; - } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, state.position, false); - } - - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - if (ch !== 0x2D/* - */) { - break; - } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; - } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } - } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _keyLine, - _keyLineStart, - _keyPos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = Object.create(null), - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - // there is a leading tab before this token, so it can't be a block sequence/mapping; - // it can still be flow sequence/mapping or a scalar - if (state.firstTabInLine !== -1) return false; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, 'tab characters must not be used in indentation'); - } - - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - // Neither implicit nor explicit notation. - // Reading is done. Go to the epilogue. - break; - } - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } - - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; - } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); - } - } - - ch = state.input.charCodeAt(++state.position); - } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); - } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, 'tag name is malformed: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; -} - -function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - - } else if (readAlias(state)) { - hasContent = true; - - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } - - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - - if (state.tag === null) { - state.tag = '?'; - } - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - - } else if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; - - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (state.tag !== '!') { - if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; - } else { - // looking for multi type - type = null; - typeList = state.typeMap.multi[state.kind || 'fallback']; - - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type = typeList[typeIndex]; - break; - } - } - } - - if (!type) { - throwError(state, 'unknown tag !<' + state.tag + '>'); - } - - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } - - if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; -} - -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = Object.create(null); - state.anchorMap = Object.create(null); - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; - } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); - } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); - } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); - } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } -} - - -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; - } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); - } - } - - var state = new State(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; -} - - -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } -} - - -function load(input, options) { - var documents = loadDocuments(input, options); - - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); -} - - -module.exports.loadAll = loadAll; -module.exports.load = load; - - -/***/ }), - -/***/ 2046: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/*eslint-disable max-len*/ - -var YAMLException = __nccwpck_require__(1248); -var Type = __nccwpck_require__(9557); - - -function compileList(schema, name) { - var result = []; - - schema[name].forEach(function (currentType) { - var newIndex = result.length; - - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && - previousType.kind === currentType.kind && - previousType.multi === currentType.multi) { - - newIndex = previousIndex; - } - }); - - result[newIndex] = currentType; - }); - - return result; -} - - -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] - } - }, index, length; - - function collectType(type) { - if (type.multi) { - result.multi[type.kind].push(type); - result.multi['fallback'].push(type); - } else { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } - } - - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; -} - - -function Schema(definition) { - return this.extend(definition); -} - - -Schema.prototype.extend = function extend(definition) { - var implicit = []; - var explicit = []; - - if (definition instanceof Type) { - // Schema.extend(type) - explicit.push(definition); - - } else if (Array.isArray(definition)) { - // Schema.extend([ type1, type2, ... ]) - explicit = explicit.concat(definition); - - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); - - } else { - throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + - 'or a schema definition ({ implicit: [...], explicit: [...] })'); - } - - implicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); - } - - if (type.multi) { - throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); - } - }); - - explicit.forEach(function (type) { - if (!(type instanceof Type)) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } - }); - - var result = Object.create(Schema.prototype); - - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); - - result.compiledImplicit = compileList(result, 'implicit'); - result.compiledExplicit = compileList(result, 'explicit'); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - - return result; -}; - - -module.exports = Schema; - - -/***/ }), - -/***/ 5746: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. - - - - - -module.exports = __nccwpck_require__(8927); - - -/***/ }), - -/***/ 7336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - - - - -module.exports = (__nccwpck_require__(5746).extend)({ - implicit: [ - __nccwpck_require__(8966), - __nccwpck_require__(6854) - ], - explicit: [ - __nccwpck_require__(8149), - __nccwpck_require__(8649), - __nccwpck_require__(6267), - __nccwpck_require__(8758) - ] -}); - - -/***/ }), - -/***/ 9832: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 - - - - - -var Schema = __nccwpck_require__(2046); - - -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(3929), - __nccwpck_require__(7161), - __nccwpck_require__(7316) - ] -}); - - -/***/ }), - -/***/ 8927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. - - - - - -module.exports = (__nccwpck_require__(9832).extend)({ - implicit: [ - __nccwpck_require__(4333), - __nccwpck_require__(7296), - __nccwpck_require__(4652), - __nccwpck_require__(7584) - ] -}); - - -/***/ }), - -/***/ 9440: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - - -var common = __nccwpck_require__(9816); - - -// get snippet for a single line, respecting maxLength -function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ''; - var tail = ''; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - - if (position - lineStart > maxHalfLength) { - head = ' ... '; - lineStart = position - maxHalfLength + head.length; - } - - if (lineEnd - position > maxHalfLength) { - tail = ' ...'; - lineEnd = position + maxHalfLength - tail.length; - } - - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, - pos: position - lineStart + head.length // relative position - }; -} - - -function padStart(string, max) { - return common.repeat(' ', max - string.length) + string; -} - - -function makeSnippet(mark, options) { - options = Object.create(options || null); - - if (!mark.buffer) return null; - - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== 'number') options.indent = 1; - if (typeof options.linesBefore !== 'number') options.linesBefore = 3; - if (typeof options.linesAfter !== 'number') options.linesAfter = 2; - - var re = /\r?\n|\r|\0/g; - var lineStarts = [ 0 ]; - var lineEnds = []; - var match; - var foundLineNo = -1; - - while ((match = re.exec(mark.buffer))) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); - - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; - } - } - - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - - var result = '', i, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - - for (i = 1; i <= options.linesBefore; i++) { - if (foundLineNo - i < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i], - lineEnds[foundLineNo - i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), - maxLineLength - ); - result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n' + result; - } - - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; - - for (i = 1; i <= options.linesAfter; i++) { - if (foundLineNo + i >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i], - lineEnds[foundLineNo + i], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), - maxLineLength - ); - result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + - ' | ' + line.str + '\n'; - } - - return result.replace(/\n$/, ''); -} - - -module.exports = makeSnippet; - - -/***/ }), - -/***/ 9557: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var YAMLException = __nccwpck_require__(1248); - -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'multi', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'representName', - 'defaultStyle', - 'styleAliases' -]; - -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; - -function compileStyleAliases(map) { - var result = {}; - - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } - - return result; -} - -function Type(tag, options) { - options = options || {}; - - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); - - // TODO: Add tag format check. - this.options = options; // keep original options in case user wants to extend this type later - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.representName = options['representName'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.multi = options['multi'] || false; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); - - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); - } -} - -module.exports = Type; - - -/***/ }), - -/***/ 8149: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/*eslint-disable no-bitwise*/ - - -var Type = __nccwpck_require__(9557); - - -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - - -function resolveYamlBinary(data) { - if (data === null) return false; - - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; - - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); - - // Skip CR/LF - if (code > 64) continue; - - // Fail on illegal characters - if (code < 0) return false; - - bitlen += 6; - } - - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} - -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; - - // Collect by 6*4 bits (3 bytes) - - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } - - bits = (bits << 6) | map.indexOf(input.charAt(idx)); - } - - // Dump tail - - tailbits = (max % 4) * 6; - - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } - - return new Uint8Array(result); -} - -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; - - // Convert every three bytes to 4 ASCII characters. - - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } - - bits = (bits << 8) + object[idx]; - } - - // Dump tail - - tail = max % 3; - - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; - } - - return result; -} - -function isBinary(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]'; -} - -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); - - -/***/ }), - -/***/ 7296: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -function resolveYamlBoolean(data) { - if (data === null) return false; - - var max = data.length; - - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} - -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} - -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} - -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); - - -/***/ }), - -/***/ 7584: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var common = __nccwpck_require__(9816); -var Type = __nccwpck_require__(9557); - -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); - -function resolveYamlFloat(data) { - if (data === null) return false; - - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; - } - - return true; -} - -function constructYamlFloat(data) { - var value, sign; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } - - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - - } else if (value === '.nan') { - return NaN; - } - return sign * parseFloat(value, 10); -} - - -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - -function representYamlFloat(object, style) { - var res; - - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } - - res = object.toString(10); - - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack - - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} - -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); - - -/***/ }), - -/***/ 4652: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var common = __nccwpck_require__(9816); -var Type = __nccwpck_require__(9557); - -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} - -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} - -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} - -function resolveYamlInteger(data) { - if (data === null) return false; - - var max = data.length, - index = 0, - hasDigits = false, - ch; - - if (!max) return false; - - ch = data[index]; - - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } - - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; - - // base 2, base 8, base 16 - - if (ch === 'b') { - // base 2 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - - if (ch === 'x') { - // base 16 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - - - if (ch === 'o') { - // base 8 - index++; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } - } - - // base 10 (except 0) - - // value should not start with `_`; - if (ch === '_') return false; - - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; - } - - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; - - return true; -} - -function constructYamlInteger(data) { - var value = data, sign = 1, ch; - - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } - - ch = value[0]; - - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } - - if (value === '0') return 0; - - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); - if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); - } - - return sign * parseInt(value, 10); -} - -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); -} - -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } -}); - - -/***/ }), - -/***/ 7316: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); - - -/***/ }), - -/***/ 6854: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -function resolveYamlMerge(data) { - return data === '<<' || data === null; -} - -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); - - -/***/ }), - -/***/ 4333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -function resolveYamlNull(data) { - if (data === null) return true; - - var max = data.length; - - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} - -function constructYamlNull() { - return null; -} - -function isNull(object) { - return object === null; -} - -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; }, - empty: function () { return ''; } - }, - defaultStyle: 'lowercase' -}); - - -/***/ }), - -/***/ 8649: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; - -function resolveYamlOmap(data) { - if (data === null) return true; - - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; - - if (_toString.call(pair) !== '[object Object]') return false; - - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; - } - } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; - } - - return true; -} - -function constructYamlOmap(data) { - return data !== null ? data : []; -} - -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - - -/***/ }), - -/***/ 6267: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return true; -} - -function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); - - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - keys = Object.keys(pair); - - result[index] = [ keys[0], pair[keys[0]] ]; - } - - return result; -} - -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); - - -/***/ }), - -/***/ 7161: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); - - -/***/ }), - -/***/ 8758: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -function resolveYamlSet(data) { - if (data === null) return true; - - var key, object = data; - - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } - } - - return true; -} - -function constructYamlSet(data) { - return data !== null ? data : {}; -} - -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - - -/***/ }), - -/***/ 3929: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); - - -/***/ }), - -/***/ 8966: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(9557); - -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day - -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute - -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} - -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; - - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - - if (match === null) throw new Error('Date resolve error'); - - // match: [1] year [2] month [3] day - - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); - - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } - - // match: [4] hour [5] minute [6] second [7] fraction - - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); - - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; - } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; - } - - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; -} - -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} - -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); - - /***/ }), /***/ 770: @@ -29763,585 +25649,82 @@ module.exports = { const core = __nccwpck_require__(7484); const fs = __nccwpck_require__(9896); const path = __nccwpck_require__(6928); -const { globSync } = __nccwpck_require__(8941); -const yaml = __nccwpck_require__(4281); - -async function pollTask(baseUrl, apiKey, taskId, label, pollingTimeoutSeconds) { - const pollInterval = 5; // seconds - const pollUrl = `${baseUrl}/api/v1/task-status/${taskId}/`; - let elapsed = 0; - - core.info(`${label} dispatched as background task (task_id: ${taskId})`); - core.info(`Polling for completion (interval: ${pollInterval}s, timeout: ${pollingTimeoutSeconds}s)...`); - - while (elapsed < pollingTimeoutSeconds) { - await new Promise(resolve => setTimeout(resolve, pollInterval * 1000)); - elapsed += pollInterval; - - try { - const pollResponse = await fetch(pollUrl, { - method: 'GET', - headers: { - 'Authorization': `Api-Key ${apiKey}`, - 'Content-Type': 'application/json' - } - }); - - if (!pollResponse.ok) { - const errorBody = await pollResponse.text(); - throw new Error( - `Poll failed with status ${pollResponse.status}: ${errorBody || pollResponse.statusText}` - ); - } - - const pollData = await pollResponse.json(); - core.debug(`Poll response: ${JSON.stringify(pollData)}`); - - const status = pollData.status; - core.info(` ${label} status: ${status} (${elapsed}s elapsed)`); - - if (status === 'SUCCESS') { - core.info(`${label} completed successfully`); - return { status: 'SUCCESS', result: pollData.result || {} }; - } else if (status === 'FAILURE') { - const error = pollData.error || 'Unknown error'; - return { status: 'FAILURE', error }; - } else if (status === 'REVOKED') { - return { status: 'REVOKED' }; - } - // PENDING, STARTED, RETRY — continue polling - } catch (e) { - if (e.message && (e.message.includes('Poll failed'))) { - throw e; - } - core.warning(`Error during polling: ${e.message}. Retrying...`); - core.debug(`Poll error details: ${e.stack}`); - } - } - - return { status: 'TIMEOUT' }; -} - -function buildUrl(baseUrl, endpoint, environment) { - const envParam = environment ? `?environment=${encodeURIComponent(environment)}` : ''; - return `${baseUrl}${endpoint}${envParam}`; -} - -function injectYamlVariables(content, changesetVariables) { - const doc = yaml.load(content); - - // Determine mask_value for each injected variable based on existing entries - const existingVars = Array.isArray(doc.variable) ? doc.variable : []; - const injectedVars = Object.entries(changesetVariables).map(([name, value]) => { - // Check if this variable exists in the changeset - const existingEntries = existingVars.filter(v => v.name === name); - // If any existing entry has mask_value: true, preserve that; otherwise use false - const maskValue = existingEntries.some(v => v.mask_value === true) ? true : false; - return { - environment: null, - mask_value: maskValue, - name, - value, - }; - }); - - // Remove all existing entries for variables we're overriding - const overrideNames = new Set(Object.keys(changesetVariables)); - const keptVars = existingVars.filter(v => !overrideNames.has(v.name)); - - doc.variable = [...keptVars, ...injectedVars]; - - return yaml.dump(doc, { lineWidth: -1, noRefs: true }); -} - -function injectJsonVariables(content, changesetVariables) { - const doc = JSON.parse(content); - - // Determine mask_value for each injected variable based on existing entries - const existingVars = Array.isArray(doc.variable) ? doc.variable : []; - const injectedVars = Object.entries(changesetVariables).map(([name, value]) => { - // Check if this variable exists in the changeset - const existingEntries = existingVars.filter(v => v.name === name); - // If any existing entry has mask_value: true, preserve that; otherwise use false - const maskValue = existingEntries.some(v => v.mask_value === true) ? true : false; - return { - environment: null, - mask_value: maskValue, - name, - value, - }; - }); - - // Remove all existing entries for variables we're overriding - const overrideNames = new Set(Object.keys(changesetVariables)); - const keptVars = existingVars.filter(v => !overrideNames.has(v.name)); - - doc.variable = [...keptVars, ...injectedVars]; - - return JSON.stringify(doc, null, 2); -} - -function getFileFormat(filePath) { - const ext = path.extname(filePath).toLowerCase(); - if (ext === '.json') return 'json'; - return 'yaml'; // .yaml, .yml, or any other extension defaults to yaml -} - -function isGlobPattern(pattern) { - return /[*?[\]{}]/.test(pattern); -} - -function resolveFiles(changesetFile) { - if (!changesetFile || changesetFile.trim() === '') { - throw new Error('changeset_file is required'); - } - - if (isGlobPattern(changesetFile)) { - // Normalize to forward slashes for cross-platform glob compatibility - const normalizedPattern = changesetFile.replace(/\\/g, '/'); - const matches = globSync(normalizedPattern, { nodir: true }); - if (matches.length === 0) { - throw new Error(`No files matched the pattern: ${changesetFile}`); - } - const filePaths = matches - .map(f => path.resolve(f)) - .sort((a, b) => path.basename(a).localeCompare(path.basename(b))); - core.info(`Matched ${filePaths.length} file(s) for pattern: ${changesetFile}`); - filePaths.forEach((f, i) => core.info(` [${i + 1}] ${path.basename(f)}`)); - return filePaths; - } - - const filePath = path.resolve(changesetFile); - if (!fs.existsSync(filePath)) { - throw new Error(`Changeset file not found: ${filePath}`); - } - return [filePath]; -} - -// Validate a single changeset file. Returns { taskId, status, result } or throws. -async function validateFile(filePath, options) { - const { apiKey, baseUrl, environment, pollingTimeoutSeconds, changesetVariables } = options; - const content = fs.readFileSync(filePath, 'utf8'); - const format = getFileFormat(filePath); - const endpoint = format === 'json' - ? '/api/v1/change-set/change-set/validate_json/' - : '/api/v1/change-set/change-set/validate_yaml/'; - const validateUrl = buildUrl(baseUrl, endpoint, environment); - - core.debug(`Validate URL: ${validateUrl} (format: ${format})`); - - // Build request body and content type based on file format - let body, contentType; - if (format === 'json') { - contentType = 'application/json'; - body = changesetVariables ? injectJsonVariables(content, changesetVariables) : content; - } else { - contentType = 'application/yaml'; - body = changesetVariables ? injectYamlVariables(content, changesetVariables) : content; - } - - core.debug(`Sending validation request to: ${validateUrl}`); - let validateResponse; - try { - validateResponse = await fetch(validateUrl, { - method: 'POST', - headers: { - 'Authorization': `Api-Key ${apiKey}`, - 'Content-Type': contentType - }, - body - }); - core.debug(`API response status: ${validateResponse.status}`); - } catch (error) { - core.error(`Network error connecting to InProd API: ${error.message}`); - core.debug(`Full error details: ${error.stack}`); - throw new Error(`Failed to connect to InProd API at ${validateUrl}: ${error.message}`); - } - - if (!validateResponse.ok) { - const errorBody = await validateResponse.text(); - throw new Error( - `Validation request failed with status ${validateResponse.status}: ${errorBody || validateResponse.statusText}` - ); - } - - const validateData = await validateResponse.json(); - core.debug(`Validate response: ${JSON.stringify(validateData)}`); - - let validateTaskId; - try { - validateTaskId = validateData.data.attributes.task_id; - } catch (e) { - throw new Error( - `Failed to extract task_id from validation response. Response: ${JSON.stringify(validateData)}` - ); - } - - if (!validateTaskId || validateTaskId.trim() === '') { - throw new Error('Validation API returned an empty task_id'); - } - - const validateResult = await pollTask(baseUrl, apiKey, validateTaskId, 'Validation', pollingTimeoutSeconds); - - if (validateResult.status === 'TIMEOUT') { - return { taskId: validateTaskId, status: 'TIMEOUT', result: {}, error: `Validation did not complete within ${pollingTimeoutSeconds} seconds` }; - } - if (validateResult.status === 'FAILURE') { - return { status: 'FAILURE', result: {}, error: `Validation failed: ${validateResult.error}` }; - } - if (validateResult.status === 'REVOKED') { - return { status: 'REVOKED', result: {}, error: 'Validation task was cancelled' }; - } - - const isValid = validateResult.result.is_valid; - if (!isValid) { - const validationErrors = JSON.stringify(validateResult.result.validation_results || [], null, 2); - core.error(`Validation errors:\n${validationErrors}`); - return { status: 'FAILURE', result: validateResult.result, error: 'Changeset validation failed. See validation errors above.' }; - } - - core.info(`✓ Validation passed`); - if (validateResult.result.changeset_name) { - core.info(` Changeset: ${validateResult.result.changeset_name}`); - } - if (validateResult.result.environment) { - core.info(` Environment: ${JSON.stringify(validateResult.result.environment)}`); - } - - return { status: 'SUCCESS', result: validateResult.result }; -} - -// Execute a single changeset file. Returns { taskId, status, result } or throws. -async function executeFile(filePath, options) { - const { apiKey, baseUrl, environment, pollingTimeoutSeconds, changesetVariables } = options; - const content = fs.readFileSync(filePath, 'utf8'); - const format = getFileFormat(filePath); - const endpoint = format === 'json' - ? '/api/v1/change-set/change-set/execute_json/' - : '/api/v1/change-set/change-set/execute_yaml/'; - const executeUrl = buildUrl(baseUrl, endpoint, environment); - - core.debug(`Execute URL: ${executeUrl} (format: ${format})`); - - // Build request body and content type based on file format - let body, contentType; - if (format === 'json') { - contentType = 'application/json'; - body = changesetVariables ? injectJsonVariables(content, changesetVariables) : content; - } else { - contentType = 'application/yaml'; - body = changesetVariables ? injectYamlVariables(content, changesetVariables) : content; - } - - core.debug(`Sending API request to: ${executeUrl}`); - let executeResponse; - try { - executeResponse = await fetch(executeUrl, { - method: 'POST', - headers: { - 'Authorization': `Api-Key ${apiKey}`, - 'Content-Type': contentType - }, - body - }); - core.debug(`API response status: ${executeResponse.status}`); - } catch (error) { - core.error(`Network error connecting to InProd API: ${error.message}`); - core.debug(`Full error details: ${error.stack}`); - throw new Error(`Failed to connect to InProd API at ${executeUrl}: ${error.message}`); - } - - if (!executeResponse.ok) { - const errorBody = await executeResponse.text(); - throw new Error( - `API request failed with status ${executeResponse.status}: ${errorBody || executeResponse.statusText}` - ); - } - - const executeData = await executeResponse.json(); - core.debug(`Execute response: ${JSON.stringify(executeData)}`); - - let taskId; - try { - taskId = executeData.data.attributes.task_id; - } catch (e) { - throw new Error( - `Failed to extract task_id from API response. Response: ${JSON.stringify(executeData)}` - ); - } - - if (!taskId || taskId.trim() === '') { - throw new Error('API returned an empty task_id'); - } - - core.info(`✓ Changeset submitted successfully`); - - const pollResult = await pollTask(baseUrl, apiKey, taskId, 'Execution', pollingTimeoutSeconds); - - if (pollResult.status === 'SUCCESS') { - core.info(`✓ Changeset executed successfully`); - return { status: 'SUCCESS', result: pollResult.result }; - } else if (pollResult.status === 'FAILURE') { - core.error(`✗ Task failed: ${pollResult.error}`); - return { status: 'FAILURE', result: {}, error: `Changeset execution failed: ${pollResult.error}` }; - } else if (pollResult.status === 'REVOKED') { - core.warning(`⚠ Task was cancelled/revoked`); - return { status: 'REVOKED', result: {}, error: 'Changeset execution was cancelled' }; - } else if (pollResult.status === 'TIMEOUT') { - return { status: 'TIMEOUT', result: {}, error: `Changeset execution did not complete within ${pollingTimeoutSeconds} seconds` }; - } - - return { status: pollResult.status, result: {} }; -} - -// Process a single file through the full flow (validate + execute). -// Returns { file, status, result }. -async function processSingleFile(filePath, options) { - const { validateBeforeExecute, validateOnly } = options; - const fileName = path.basename(filePath); - - core.info(`Read changeset from file: ${fileName}`); - - // Step 1: Validate (if needed) - if (validateOnly || validateBeforeExecute) { - core.info('Validating changeset...'); - const valResult = await validateFile(filePath, options); - - if (valResult.status !== 'SUCCESS') { - return { file: filePath, status: valResult.status, result: valResult.result, error: valResult.error }; - } - - if (validateOnly) { - return { file: filePath, status: 'SUCCESS', result: valResult.result }; - } - } - - // Step 2: Execute - core.info('Submitting changeset for execution...'); - const execResult = await executeFile(filePath, options); +const { execFileSync } = __nccwpck_require__(5317); - if (execResult.error) { - return { file: filePath, status: execResult.status, result: execResult.result, error: execResult.error }; - } - - if (execResult.result.run_id) { - core.info(`Run ID: ${execResult.result.run_id}`); - } - if (execResult.result.changeset_name) { - core.info(`Changeset: ${execResult.result.changeset_name}`); - } - if (execResult.result.environment) { - core.info(`Environment: ${JSON.stringify(execResult.result.environment)}`); - } - - return { file: filePath, status: execResult.status, result: execResult.result }; -} - -const STATUS_PRIORITY = { FAILURE: 0, TIMEOUT: 1, REVOKED: 2, SUBMITTED: 3, SUCCESS: 4 }; - -function worstStatus(results) { - return results.reduce((worst, r) => { - return (STATUS_PRIORITY[r.status] ?? 99) < (STATUS_PRIORITY[worst] ?? 99) ? r.status : worst; - }, 'SUCCESS'); -} +// This file is a pure adapter: it translates GitHub Actions inputs into the INPROD_* +// environment variables the run-changesets CLI (@inprod.io/run-changesets) already reads, +// spawns it, and translates the result files it already writes back into Action outputs. +// No changeset logic lives here — that all lives in run-changesets, referenced unmodified. async function run() { try { - // Get inputs (fall back to environment variables for api_key and base_url) const apiKey = core.getInput('api_key') || process.env.INPROD_API_KEY || ''; - const baseUrl = (core.getInput('base_url') || process.env.INPROD_BASE_URL || '').replace(/\/$/, ''); - const changesetFile = core.getInput('changeset_file', { required: true }); - const environment = core.getInput('environment'); - const validateBeforeExecute = core.getInput('validate_before_execute') !== 'false'; - const validateOnly = core.getInput('validate_only') === 'true'; - const pollingTimeoutMinutes = parseInt(core.getInput('polling_timeout_minutes'), 10) || 10; - const pollingTimeoutSeconds = pollingTimeoutMinutes * 60; - const executionStrategy = core.getInput('execution_strategy') || 'per_file'; - const failFast = core.getInput('fail_fast') === 'true'; - const changesetVariablesInput = core.getInput('changeset_variables'); - - // Parse changeset variables from KEY=VALUE format - let changesetVariables = null; - if (changesetVariablesInput && changesetVariablesInput.trim()) { - changesetVariables = {}; - const lines = changesetVariablesInput.trim().split('\n'); - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) continue; // Skip empty lines and comments - const [key, ...valueParts] = trimmed.split('='); - if (!key || valueParts.length === 0) { - throw new Error(`Invalid changeset_variables format. Expected KEY=VALUE on each line, got: ${trimmed}`); - } - changesetVariables[key.trim()] = valueParts.join('=').trim(); // Handle values with = in them - } - core.debug(`Parsed changeset variables: ${JSON.stringify(Object.keys(changesetVariables))} (values masked)`); - } - - // Mask sensitive values in logs + const baseUrl = core.getInput('base_url') || process.env.INPROD_BASE_URL || ''; core.setSecret(apiKey); - // Validate inputs - if (!apiKey || apiKey.trim() === '') { - throw new Error('api_key is required and cannot be empty'); - } - if (!baseUrl || baseUrl.trim() === '') { - throw new Error('base_url is required and cannot be empty'); + const env = { + ...process.env, + INPROD_API_KEY: apiKey, + INPROD_BASE_URL: baseUrl, + INPROD_CHANGESET_FILE: core.getInput('changeset_file', { required: true }), + INPROD_ENVIRONMENT: core.getInput('environment'), + INPROD_VALIDATE_BEFORE_EXECUTE: core.getInput('validate_before_execute'), + INPROD_VALIDATE_ONLY: core.getInput('validate_only'), + INPROD_POLLING_TIMEOUT_MINUTES: core.getInput('polling_timeout_minutes'), + INPROD_EXECUTION_STRATEGY: core.getInput('execution_strategy'), + INPROD_FAIL_FAST: core.getInput('fail_fast'), + INPROD_CHANGESET_VARIABLES: core.getInput('changeset_variables'), + INPROD_FILES: core.getInput('inprod_files') || process.env.INPROD_FILES || '', + }; + if (core.isDebug()) { + env.INPROD_DEBUG = 'true'; } - // Validate URL format + const entryPoint = path.join(__dirname, 'run-changesets', 'index.js'); + + let spawnError = null; try { - new URL(baseUrl); - } catch (e) { - throw new Error(`Invalid base_url format: ${baseUrl}`); + // stdio: 'inherit' streams run-changesets's own console output directly into the + // Action's job log in real time, exactly as it does when run as a CLI. + execFileSync(process.execPath, [entryPoint], { env, stdio: 'inherit' }); + } catch (err) { + spawnError = err; // non-zero exit — run-changesets already logged its own error above } - // Resolve changeset files - const filePaths = resolveFiles(changesetFile); + const resultPath = path.join(process.cwd(), 'inprod-result.json'); + const statusPath = path.join(process.cwd(), 'inprod-results.env'); - const options = { - apiKey, baseUrl, environment, validateBeforeExecute, validateOnly, - pollingTimeoutSeconds, changesetVariables, - }; + if (fs.existsSync(resultPath) && fs.existsSync(statusPath)) { + const resultArray = JSON.parse(fs.readFileSync(resultPath, 'utf8')); + const status = fs.readFileSync(statusPath, 'utf8').match(/INPROD_STATUS=(\w+)/)[1]; + fs.unlinkSync(resultPath); + fs.unlinkSync(statusPath); - core.info(`InProd Run Changesets Action v1`); - core.info(`Base URL: ${baseUrl}`); - if (environment) { - core.info(`Target environment: ${environment}`); - } - core.info(`Files to process: ${filePaths.length}`); - core.info(`Execution strategy: ${executionStrategy}`); - core.info(`Fail fast: ${failFast}`); - core.info(`Validate before execute: ${validateBeforeExecute}`); - core.info(`Validate only: ${validateOnly}`); - core.info(`Polling timeout: ${pollingTimeoutMinutes} minutes (${pollingTimeoutSeconds} seconds)`); - if (changesetVariables) { - core.info(`Changeset variables: ${Object.keys(changesetVariables).length} variable(s) provided`); - } - - const results = []; - - if (executionStrategy === 'validate_first' && !validateOnly && validateBeforeExecute) { - // Phase 1: Validate all files - for (let i = 0; i < filePaths.length; i++) { - const filePath = filePaths[i]; - const fileName = path.basename(filePath); - core.info(`\n--- Validating [${i + 1}/${filePaths.length}]: ${fileName} ---`); - try { - const valResult = await validateFile(filePath, options); - if (valResult.status !== 'SUCCESS') { - results.push({ file: filePath, taskId: valResult.taskId, status: valResult.status, result: valResult.result, error: valResult.error }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed validation.`); - break; - } - continue; - } - } catch (error) { - results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed validation.`); - break; - } - continue; - } - } + core.setOutput('status', status); + core.setOutput('result', JSON.stringify(resultArray)); - // If any validation failed, stop before executing - const validationFailures = results.filter(r => r.status !== 'SUCCESS'); - if (validationFailures.length > 0) { - // Set outputs and fail - core.setOutput('status', 'FAILURE'); - const resultArray = results.map(r => ({ - file: path.basename(r.file), - status: r.status, - result: r.result || {}, - error: r.error || null, - })); - core.setOutput('result', JSON.stringify(resultArray)); - const msg = validationFailures.length === 1 - ? validationFailures[0].error - : `${validationFailures.length} of ${filePaths.length} changeset(s) failed validation. See result output for details.`; - throw new Error(msg); - } - - core.info(`\n✓ All ${filePaths.length} file(s) passed validation. Starting execution...`); - - // Phase 2: Execute all files (skip re-validation) - const executeOptions = { ...options, validateBeforeExecute: false, validateOnly: false }; - for (let i = 0; i < filePaths.length; i++) { - const filePath = filePaths[i]; - const fileName = path.basename(filePath); - core.info(`\n--- Executing [${i + 1}/${filePaths.length}]: ${fileName} ---`); - try { - const fileResult = await processSingleFile(filePath, executeOptions); - results.push(fileResult); - if (fileResult.error && failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } catch (error) { - results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } - } - } else { - // per_file strategy: full flow for each file sequentially - for (let i = 0; i < filePaths.length; i++) { - const filePath = filePaths[i]; - const fileName = path.basename(filePath); - core.info(`\n--- Processing [${i + 1}/${filePaths.length}]: ${fileName} ---`); - try { - const fileResult = await processSingleFile(filePath, options); - results.push(fileResult); - if (fileResult.error && failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } catch (error) { - results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } + if (spawnError) { + const failedFiles = resultArray.filter(r => r.status !== 'SUCCESS' && r.status !== 'SUBMITTED'); + const msg = failedFiles.length === 1 + ? failedFiles[0].error + : `${failedFiles.length} of ${resultArray.length} changeset(s) failed. See result output for details.`; + core.setFailed(msg); + process.exit(1); } + } else if (spawnError) { + // run-changesets failed before it could write result files (e.g. bad input, missing + // changeset file) — see the job log above (streamed via stdio: 'inherit') for the reason. + core.setFailed(`run-changesets exited with code ${spawnError.status ?? 1}. See the job log above for details.`); + process.exit(1); } - - // Set aggregate outputs - const aggregateStatus = worstStatus(results); - core.setOutput('status', aggregateStatus); - - const resultArray = results.map(r => ({ - file: path.basename(r.file), - status: r.status, - result: r.result || {}, - error: r.error || null, - })); - core.setOutput('result', JSON.stringify(resultArray)); - - core.info(`\nAction completed with status: ${aggregateStatus}`); - - // Fail the action if any file had a non-success status - if (aggregateStatus === 'FAILURE' || aggregateStatus === 'TIMEOUT' || aggregateStatus === 'REVOKED') { - const failedFiles = results.filter(r => r.status !== 'SUCCESS' && r.status !== 'SUBMITTED'); - const msg = failedFiles.length === 1 - ? failedFiles[0].error - : `${failedFiles.length} of ${results.length} changeset(s) failed. See result output for details.`; - throw new Error(msg); - } - } catch (error) { core.error(`Action failed: ${error.message}`); - core.debug(`Error stack: ${error.stack}`); core.setFailed(error.message); process.exit(1); } } -module.exports = { run, pollTask, buildUrl, isGlobPattern, resolveFiles, worstStatus, getFileFormat, injectYamlVariables, injectJsonVariables }; +module.exports = { run }; /* istanbul ignore next */ if (require.main === require.cache[eval('__filename')]) { @@ -30471,30 +25854,6 @@ module.exports = require("node:events"); /***/ }), -/***/ 3024: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:fs"); - -/***/ }), - -/***/ 1455: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:fs/promises"); - -/***/ }), - -/***/ 6760: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:path"); - -/***/ }), - /***/ 7075: /***/ ((module) => { @@ -30503,22 +25862,6 @@ module.exports = require("node:stream"); /***/ }), -/***/ 6193: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:string_decoder"); - -/***/ }), - -/***/ 3136: -/***/ ((module) => { - -"use strict"; -module.exports = require("node:url"); - -/***/ }), - /***/ 7975: /***/ ((module) => { @@ -32262,18 +27605,6 @@ function parseParams (str) { module.exports = parseParams -/***/ }), - -/***/ 8941: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -var R=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ge=R(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.range=Y.balanced=void 0;var Gs=(n,t,e)=>{let s=n instanceof RegExp?Ie(n,e):n,i=t instanceof RegExp?Ie(t,e):t,r=s!==null&&i!=null&&(0,Y.range)(s,i,e);return r&&{start:r[0],end:r[1],pre:e.slice(0,r[0]),body:e.slice(r[0]+s.length,r[1]),post:e.slice(r[1]+i.length)}};Y.balanced=Gs;var Ie=(n,t)=>{let e=t.match(n);return e?e[0]:null},zs=(n,t,e)=>{let s,i,r,h,o,a=e.indexOf(n),l=e.indexOf(t,a+1),f=a;if(a>=0&&l>0){if(n===t)return[a,l];for(s=[],r=e.length;f>=0&&!o;){if(f===a)s.push(f),a=e.indexOf(n,f+1);else if(s.length===1){let c=s.pop();c!==void 0&&(o=[c,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&h!==void 0&&(o=[r,h])}return o};Y.range=zs});var Ke=R(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.EXPANSION_MAX=void 0;it.expand=ei;var ze=Ge(),Ue="\0SLASH"+Math.random()+"\0",$e="\0OPEN"+Math.random()+"\0",ue="\0CLOSE"+Math.random()+"\0",qe="\0COMMA"+Math.random()+"\0",He="\0PERIOD"+Math.random()+"\0",Us=new RegExp(Ue,"g"),$s=new RegExp($e,"g"),qs=new RegExp(ue,"g"),Hs=new RegExp(qe,"g"),Vs=new RegExp(He,"g"),Ks=/\\\\/g,Xs=/\\{/g,Ys=/\\}/g,Js=/\\,/g,Zs=/\\./g;it.EXPANSION_MAX=1e5;function ce(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function Qs(n){return n.replace(Ks,Ue).replace(Xs,$e).replace(Ys,ue).replace(Js,qe).replace(Zs,He)}function ti(n){return n.replace(Us,"\\").replace($s,"{").replace(qs,"}").replace(Hs,",").replace(Vs,".")}function Ve(n){if(!n)return[""];let t=[],e=(0,ze.balanced)("{","}",n);if(!e)return n.split(",");let{pre:s,body:i,post:r}=e,h=s.split(",");h[h.length-1]+="{"+i+"}";let o=Ve(r);return r.length&&(h[h.length-1]+=o.shift(),h.push.apply(h,o)),t.push.apply(t,h),t}function ei(n,t={}){if(!n)return[];let{max:e=it.EXPANSION_MAX}=t;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),ht(Qs(n),e,!0).map(ti)}function si(n){return"{"+n+"}"}function ii(n){return/^-?0\d/.test(n)}function ri(n,t){return n<=t}function ni(n,t){return n>=t}function ht(n,t,e){let s=[],i=(0,ze.balanced)("{","}",n);if(!i)return[n];let r=i.pre,h=i.post.length?ht(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let o=0;o=0;if(!l&&!f)return i.post.match(/,(?!,).*\}/)?(n=i.pre+"{"+i.body+ue+i.post,ht(n,t,!0)):[n];let c;if(l)c=i.body.split(/\.\./);else if(c=Ve(i.body),c.length===1&&c[0]!==void 0&&(c=ht(c[0],t,!1).map(si),c.length===1))return h.map(u=>i.pre+c[0]+u);let d;if(l&&c[0]!==void 0&&c[1]!==void 0){let u=ce(c[0]),m=ce(c[1]),p=Math.max(c[0].length,c[1].length),b=c.length===3&&c[2]!==void 0?Math.abs(ce(c[2])):1,w=ri;m0){let U=new Array(B+1).join("0");y<0?S="-"+U+S.slice(1):S=U+S}}d.push(S)}}else{d=[];for(let u=0;u{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.assertValidPattern=void 0;var hi=1024*64,oi=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>hi)throw new TypeError("pattern is too long")};xt.assertValidPattern=oi});var Je=R(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.parseClass=void 0;var ai={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ot=n=>n.replace(/[[\]\\-]/g,"\\$&"),li=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ye=n=>n.join(""),ci=(n,t)=>{let e=t;if(n.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],r=e+1,h=!1,o=!1,a=!1,l=!1,f=e,c="";t:for(;rc?s.push(ot(c)+"-"+ot(p)):p===c&&s.push(ot(p)),c="",r++;continue}if(n.startsWith("-]",r+1)){s.push(ot(p+"-")),r+=2;continue}if(n.startsWith("-",r+1)){c=p,r+=2;continue}s.push(ot(p)),r++}if(f{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.unescape=void 0;var ui=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!0}={})=>e?t?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?n.replace(/\[([^\/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");At.unescape=ui});var pe=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.AST=void 0;var fi=Je(),Mt=kt(),di=new Set(["!","?","+","*","@"]),Ze=n=>di.has(n),pi="(?!(?:^|/)\\.\\.?(?:$|/))",Pt="(?!\\.)",mi=new Set(["[","."]),gi=new Set(["..","."]),wi=new Set("().*{}+?[]^$\\!"),bi=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),de="[^/]",Qe=de+"*?",ts=de+"+?",fe=class n{type;#t;#s;#n=!1;#r=[];#h;#S;#w;#c=!1;#o;#f;#u=!1;constructor(t,e,s={}){this.type=t,t&&(this.#s=!0),this.#h=e,this.#t=this.#h?this.#h.#t:this,this.#o=this.#t===this?s:this.#t.#o,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#c&&this.#w.push(this),this.#S=this.#h?this.#h.#r.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#f!==void 0?this.#f:this.type?this.#f=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#f=this.#r.map(t=>String(t)).join("")}#a(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#h;for(;s;){for(let i=e.#S+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&this.#h?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#h?.isStart())return!1;if(this.#S===0)return!0;let t=this.#h;for(let e=0;etypeof u!="string"),l=this.#r.map(u=>{let[m,p,b,w]=typeof u=="string"?n.#v(u,this.#s,a):u.toRegExpSource(t);return this.#s=this.#s||b,this.#n=this.#n||w,m}).join(""),f="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&gi.has(this.#r[0]))){let m=mi,p=e&&m.has(l.charAt(0))||l.startsWith("\\.")&&m.has(l.charAt(2))||l.startsWith("\\.\\.")&&m.has(l.charAt(4)),b=!e&&!t&&m.has(l.charAt(0));f=p?pi:b?Pt:""}let c="";return this.isEnd()&&this.#t.#c&&this.#h?.type==="!"&&(c="(?:$|\\/)"),[f+l+c,(0,Mt.unescape)(l),this.#s=!!this.#s,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#d(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#r=[a],this.type=null,this.#s=void 0,[a,(0,Mt.unescape)(this.toString()),!1,!1]}let h=!s||t||e||!Pt?"":this.#d(!0);h===r&&(h=""),h&&(r=`(?:${r})(?:${h})*?`);let o="";if(this.type==="!"&&this.#u)o=(this.isStart()&&!e?Pt:"")+ts;else{let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Pt:"")+Qe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&h?")":this.type==="*"&&h?")?":`)${this.type}`;o=i+r+a}return[o,(0,Mt.unescape)(r),this.#s=!!this.#s,this.#n]}#d(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,r,h]=e.toRegExpSource(t);return this.#n=this.#n||h,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#v(t,e,s=!1){let i=!1,r="",h=!1,o=!1;for(let a=0;a{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.escape=void 0;var yi=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!1}={})=>e?t?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):t?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");Ft.escape=yi});var H=R(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.unescape=g.escape=g.AST=g.Minimatch=g.match=g.makeRe=g.braceExpand=g.defaults=g.filter=g.GLOBSTAR=g.sep=g.minimatch=void 0;var Si=Ke(),jt=Xe(),is=pe(),vi=me(),Ei=kt(),_i=(n,t,e={})=>((0,jt.assertValidPattern)(t),!e.nocomment&&t.charAt(0)==="#"?!1:new J(t,e).match(n));g.minimatch=_i;var Oi=/^\*+([^+@!?\*\[\(]*)$/,Ti=n=>t=>!t.startsWith(".")&&t.endsWith(n),Ci=n=>t=>t.endsWith(n),xi=n=>(n=n.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(n)),Ri=n=>(n=n.toLowerCase(),t=>t.toLowerCase().endsWith(n)),Ai=/^\*+\.\*+$/,ki=n=>!n.startsWith(".")&&n.includes("."),Mi=n=>n!=="."&&n!==".."&&n.includes("."),Pi=/^\.\*+$/,Di=n=>n!=="."&&n!==".."&&n.startsWith("."),Fi=/^\*+$/,ji=n=>n.length!==0&&!n.startsWith("."),Ni=n=>n.length!==0&&n!=="."&&n!=="..",Li=/^\?+([^+@!?\*\[\(]*)?$/,Wi=([n,t=""])=>{let e=rs([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Bi=([n,t=""])=>{let e=ns([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Ii=([n,t=""])=>{let e=ns([n]);return t?s=>e(s)&&s.endsWith(t):e},Gi=([n,t=""])=>{let e=rs([n]);return t?s=>e(s)&&s.endsWith(t):e},rs=([n])=>{let t=n.length;return e=>e.length===t&&!e.startsWith(".")},ns=([n])=>{let t=n.length;return e=>e.length===t&&e!=="."&&e!==".."},hs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",es={win32:{sep:"\\"},posix:{sep:"/"}};g.sep=hs==="win32"?es.win32.sep:es.posix.sep;g.minimatch.sep=g.sep;g.GLOBSTAR=Symbol("globstar **");g.minimatch.GLOBSTAR=g.GLOBSTAR;var zi="[^/]",Ui=zi+"*?",$i="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",qi="(?:(?!(?:\\/|^)\\.).)*?",Hi=(n,t={})=>e=>(0,g.minimatch)(e,n,t);g.filter=Hi;g.minimatch.filter=g.filter;var F=(n,t={})=>Object.assign({},n,t),Vi=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return g.minimatch;let t=g.minimatch;return Object.assign((s,i,r={})=>t(s,i,F(n,r)),{Minimatch:class extends t.Minimatch{constructor(i,r={}){super(i,F(n,r))}static defaults(i){return t.defaults(F(n,i)).Minimatch}},AST:class extends t.AST{constructor(i,r,h={}){super(i,r,F(n,h))}static fromGlob(i,r={}){return t.AST.fromGlob(i,F(n,r))}},unescape:(s,i={})=>t.unescape(s,F(n,i)),escape:(s,i={})=>t.escape(s,F(n,i)),filter:(s,i={})=>t.filter(s,F(n,i)),defaults:s=>t.defaults(F(n,s)),makeRe:(s,i={})=>t.makeRe(s,F(n,i)),braceExpand:(s,i={})=>t.braceExpand(s,F(n,i)),match:(s,i,r={})=>t.match(s,i,F(n,r)),sep:t.sep,GLOBSTAR:g.GLOBSTAR})};g.defaults=Vi;g.minimatch.defaults=g.defaults;var Ki=(n,t={})=>((0,jt.assertValidPattern)(n),t.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,Si.expand)(n,{max:t.braceExpandMax}));g.braceExpand=Ki;g.minimatch.braceExpand=g.braceExpand;var Xi=(n,t={})=>new J(n,t).makeRe();g.makeRe=Xi;g.minimatch.makeRe=g.makeRe;var Yi=(n,t,e={})=>{let s=new J(t,e);return n=n.filter(i=>s.match(i)),s.options.nonull&&!n.length&&n.push(t),n};g.match=Yi;g.minimatch.match=g.match;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Ji=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),J=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){(0,jt.assertValidPattern)(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||hs,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,h,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!ss.test(r[2]))&&!ss.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(f=>this.parse(f))];if(l)return[r[0],...r.slice(1).map(f=>this.parse(f))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let r=s[s.length-1];return i==="**"&&r==="**"?s:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,h-i);let o=s[i+1],a=s[i+2],l=s[i+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let f=s.slice(0);f[i]="**",t.push(f),i--}if(!this.preserveMultipleSlashes){for(let h=1;he.length)}partsMatch(t,e,s=!1){let i=0,r=0,h=[],o="";for(;iE?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var h=0,o=0,a=t.length,l=e.length;h>> no match, partial?`,t,d,e,u),d===a))}let p;if(typeof f=="string"?(p=c===f,this.debug("string match",f,c,p)):(p=f.test(c),this.debug("pattern match",f,c,p)),!p)return!1}if(h===a&&o===l)return!0;if(h===a)return s;if(o===l)return h===a-1&&t[h]==="";throw new Error("wtf?")}braceExpand(){return(0,g.braceExpand)(this.pattern,this.options)}parse(t){(0,jt.assertValidPattern)(t);let e=this.options;if(t==="**")return g.GLOBSTAR;if(t==="")return"";let s,i=null;(s=t.match(Fi))?i=e.dot?Ni:ji:(s=t.match(Oi))?i=(e.nocase?e.dot?Ri:xi:e.dot?Ci:Ti)(s[1]):(s=t.match(Li))?i=(e.nocase?e.dot?Bi:Wi:e.dot?Ii:Gi)(s):(s=t.match(Ai))?i=e.dot?Mi:ki:(s=t.match(Pi))&&(i=Di);let r=is.AST.fromGlob(t,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Ui:e.dot?$i:qi,i=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let d of c.flags.split(""))i.add(d);return typeof c=="string"?Ji(c):c===g.GLOBSTAR?g.GLOBSTAR:c._src});l.forEach((c,d)=>{let u=l[d+1],m=l[d-1];c!==g.GLOBSTAR||m===g.GLOBSTAR||(m===void 0?u!==void 0&&u!==g.GLOBSTAR?l[d+1]="(?:\\/|"+s+"\\/)?"+u:l[d]=s:u===void 0?l[d-1]=m+"(?:\\/|\\/"+s+")?":u!==g.GLOBSTAR&&(l[d-1]=m+"(?:\\/|\\/"+s+"\\/)"+u,l[d+1]=g.GLOBSTAR))});let f=l.filter(c=>c!==g.GLOBSTAR);if(this.partial&&f.length>=1){let c=[];for(let d=1;d<=f.length;d++)c.push(f.slice(0,d).join("/"));return"(?:"+c.join("|")+")"}return f.join("/")}).join("|"),[h,o]=t.length>1?["(?:",")"]:["",""];r="^"+h+r+o+"$",this.partial&&(r="^(?:\\/|"+h+r.slice(1,-1)+o+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let h=i[i.length-1];if(!h)for(let o=i.length-2;!h&&o>=0;o--)h=i[o];for(let o=0;o{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.LRUCache=void 0;var er=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,as=new Set,ge=typeof process=="object"&&process?process:{},ls=(n,t,e,s)=>{typeof ge.emitWarning=="function"?ge.emitWarning(n,t,e,s):console.error(`[${e}] ${t}: ${n}`)},Lt=globalThis.AbortController,os=globalThis.AbortSignal;if(typeof Lt>"u"){os=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,s){this._onabort.push(s)}},Lt=class{constructor(){t()}signal=new os;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e)}}};let n=ge.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{n&&(n=!1,ls("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var sr=n=>!as.has(n),V=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),cs=n=>V(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Nt:null:null,Nt=class extends Array{constructor(n){super(n),this.fill(0)}},ir=class at{heap;length;static#t=!1;static create(t){let e=cs(t);if(!e)return[];at.#t=!0;let s=new at(t,e);return at.#t=!1,s}constructor(t,e){if(!at.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},rr=class us{#t;#s;#n;#r;#h;#S;#w;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#f;#u;#a;#i;#d;#v;#y;#p;#R;#m;#O;#T;#g;#b;#E;#C;#e;#F;static unsafeExposeInternals(t){return{starts:t.#T,ttls:t.#g,autopurgeTimers:t.#b,sizes:t.#O,keyMap:t.#u,keyList:t.#a,valList:t.#i,next:t.#d,prev:t.#v,get head(){return t.#y},get tail(){return t.#p},free:t.#R,isBackgroundFetch:e=>t.#l(e),backgroundFetch:(e,s,i,r)=>t.#z(e,s,i,r),moveToTail:e=>t.#N(e),indexes:e=>t.#k(e),rindexes:e=>t.#M(e),isStale:e=>t.#_(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#f}get size(){return this.#o}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#h}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:r,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:a,dispose:l,onInsert:f,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:u,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:b,fetchMethod:w,memoMethod:v,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:B,ignoreFetchAbort:U,perf:et}=t;if(et!==void 0&&typeof et?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#c=et??er,e!==0&&!V(e))throw new TypeError("max option must be a nonnegative integer");let st=e?cs(e):Array;if(!st)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=m,this.maxEntrySize=p||this.#s,this.sizeCalculation=b,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=v,w!==void 0&&typeof w!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=w,this.#C=!!w,this.#u=new Map,this.#a=new Array(e).fill(void 0),this.#i=new Array(e).fill(void 0),this.#d=new st(e),this.#v=new st(e),this.#y=0,this.#p=0,this.#R=ir.create(e),this.#o=0,this.#f=0,typeof l=="function"&&(this.#n=l),typeof f=="function"&&(this.#r=f),typeof c=="function"?(this.#h=c,this.#m=[]):(this.#h=void 0,this.#m=void 0),this.#E=!!this.#n,this.#F=!!this.#r,this.#e=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!B,this.ignoreFetchAbort=!!U,this.maxEntrySize!==0){if(this.#s!==0&&!V(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!V(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=V(i)||i===0?i:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!V(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let le="LRU_CACHE_UNBOUNDED";sr(le)&&(as.add(le),ls("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",le,us))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#P(){let t=new Nt(this.#t),e=new Nt(this.#t);this.#g=t,this.#T=e;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#b=s,this.#W=(h,o,a=this.#c.now())=>{if(e[h]=o!==0?a:0,t[h]=o,s?.[h]&&(clearTimeout(s[h]),s[h]=void 0),o!==0&&s){let l=setTimeout(()=>{this.#_(h)&&this.#A(this.#a[h],"expire")},o+1);l.unref&&l.unref(),s[h]=l}},this.#x=h=>{e[h]=t[h]!==0?this.#c.now():0},this.#D=(h,o)=>{if(t[o]){let a=t[o],l=e[o];if(!a||!l)return;h.ttl=a,h.start=l,h.now=i||r();let f=h.now-l;h.remainingTTL=a-f}};let i=0,r=()=>{let h=this.#c.now();if(this.ttlResolution>0){i=h;let o=setTimeout(()=>i=0,this.ttlResolution);o.unref&&o.unref()}return h};this.getRemainingTTL=h=>{let o=this.#u.get(h);if(o===void 0)return 0;let a=t[o],l=e[o];if(!a||!l)return 1/0;let f=(i||r())-l;return a-f},this.#_=h=>{let o=e[h],a=t[h];return!!a&&!!o&&(i||r())-o>a}}#x=()=>{};#D=()=>{};#W=()=>{};#_=()=>!1;#$(){let t=new Nt(this.#t);this.#f=0,this.#O=t,this.#L=e=>{this.#f-=t[e],t[e]=0},this.#B=(e,s,i,r)=>{if(this.#l(s))return 0;if(!V(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(s,e),!V(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#j=(e,s,i)=>{if(t[e]=s,this.#s){let r=this.#s-t[e];for(;this.#f>r;)this.#G(!0)}this.#f+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#f)}}#L=t=>{};#j=(t,e,s)=>{};#B=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#p;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#y));)e=this.#v[e]}*#M({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#y;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#p));)e=this.#d[e]}#I(t){return t!==void 0&&this.#u.get(this.#a[t])===t}*entries(){for(let t of this.#k())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*rentries(){for(let t of this.#M())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*keys(){for(let t of this.#k()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*rkeys(){for(let t of this.#M()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*values(){for(let t of this.#k())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#M())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;if(r!==void 0&&t(r,this.#a[s],this))return this.get(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#M()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#M({allowStale:!0}))this.#_(e)&&(this.#A(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#u.get(t);if(e===void 0)return;let s=this.#i[e],i=this.#l(s)?s.__staleWhileFetching:s;if(i===void 0)return;let r={value:i};if(this.#g&&this.#T){let h=this.#g[e],o=this.#T[e];if(h&&o){let a=h-(this.#c.now()-o);r.ttl=a,r.start=Date.now()}}return this.#O&&(r.size=this.#O[e]),r}dump(){let t=[];for(let e of this.#k({allowStale:!0})){let s=this.#a[e],i=this.#i[e],r=this.#l(i)?i.__staleWhileFetching:i;if(r===void 0||s===void 0)continue;let h={value:r};if(this.#g&&this.#T){h.ttl=this.#g[e];let o=this.#c.now()-this.#T[e];h.start=Math.floor(Date.now()-o)}this.#O&&(h.size=this.#O[e]),t.unshift([s,h])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#c.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,f=this.#B(t,e,s.size||0,o);if(this.maxEntrySize&&f>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#A(t,"set"),this;let c=this.#o===0?void 0:this.#u.get(t);if(c===void 0)c=this.#o===0?this.#p:this.#R.length!==0?this.#R.pop():this.#o===this.#t?this.#G(!1):this.#o,this.#a[c]=t,this.#i[c]=e,this.#u.set(t,c),this.#d[this.#p]=c,this.#v[c]=this.#p,this.#p=c,this.#o++,this.#j(c,f,a),a&&(a.set="add"),l=!1,this.#F&&this.#r?.(e,t,"add");else{this.#N(c);let d=this.#i[c];if(e!==d){if(this.#C&&this.#l(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:u}=d;u!==void 0&&!h&&(this.#E&&this.#n?.(u,t,"set"),this.#e&&this.#m?.push([u,t,"set"]))}else h||(this.#E&&this.#n?.(d,t,"set"),this.#e&&this.#m?.push([d,t,"set"]));if(this.#L(c),this.#j(c,f,a),this.#i[c]=e,a){a.set="replace";let u=d&&this.#l(d)?d.__staleWhileFetching:d;u!==void 0&&(a.oldValue=u)}}else a&&(a.set="update");this.#F&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(l||this.#W(c,i,r),a&&this.#D(a,c)),!h&&this.#e&&this.#m){let d=this.#m,u;for(;u=d?.shift();)this.#h?.(...u)}return this}pop(){try{for(;this.#o;){let t=this.#i[this.#y];if(this.#G(!0),this.#l(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#h?.(...e)}}}#G(t){let e=this.#y,s=this.#a[e],i=this.#i[e];return this.#C&&this.#l(i)?i.__abortController.abort(new Error("evicted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#L(e),this.#b?.[e]&&(clearTimeout(this.#b[e]),this.#b[e]=void 0),t&&(this.#a[e]=void 0,this.#i[e]=void 0,this.#R.push(e)),this.#o===1?(this.#y=this.#p=0,this.#R.length=0):this.#y=this.#d[e],this.#u.delete(s),this.#o--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,r=this.#u.get(t);if(r!==void 0){let h=this.#i[r];if(this.#l(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#_(r))i&&(i.has="stale",this.#D(i,r));else return s&&this.#x(r),i&&(i.has="hit",this.#D(i,r)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#u.get(t);if(i===void 0||!s&&this.#_(i))return;let r=this.#i[i];return this.#l(r)?r.__staleWhileFetching:r}#z(t,e,s,i){let r=e===void 0?void 0:this.#i[e];if(this.#l(r))return r;let h=new Lt,{signal:o}=s;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let a={signal:h.signal,options:s,context:i},l=(p,b=!1)=>{let{aborted:w}=h.signal,v=s.ignoreFetchAbort&&p!==void 0,E=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&p!==void 0);if(s.status&&(w&&!b?(s.status.fetchAborted=!0,s.status.fetchError=h.signal.reason,v&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),w&&!v&&!b)return c(h.signal.reason,E);let y=u,S=this.#i[e];return(S===u||v&&b&&S===void 0)&&(p===void 0?y.__staleWhileFetching!==void 0?this.#i[e]=y.__staleWhileFetching:this.#A(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,p,a.options))),p},f=p=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=p),c(p,!1)),c=(p,b)=>{let{aborted:w}=h.signal,v=w&&s.allowStaleOnFetchAbort,E=v||s.allowStaleOnFetchRejection,y=E||s.noDeleteOnFetchRejection,S=u;if(this.#i[e]===u&&(!y||!b&&S.__staleWhileFetching===void 0?this.#A(t,"fetch"):v||(this.#i[e]=S.__staleWhileFetching)),E)return s.status&&S.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),S.__staleWhileFetching;if(S.__returned===S)throw p},d=(p,b)=>{let w=this.#S?.(t,r,a);w&&w instanceof Promise&&w.then(v=>p(v===void 0?void 0:v),b),h.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(p(void 0),s.allowStaleOnFetchAbort&&(p=v=>l(v,!0)))})};s.status&&(s.status.fetchDispatched=!0);let u=new Promise(d).then(l,f),m=Object.assign(u,{__abortController:h,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,m,{...a.options,status:void 0}),e=this.#u.get(t)):this.#i[e]=m,m}#l(t){if(!this.#C)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Lt}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:b=!1,status:w,signal:v}=e;if(!this.#C)return w&&(w.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:w});let E={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:h,noDisposeOnSet:o,size:a,sizeCalculation:l,noUpdateTTL:f,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:u,status:w,signal:v},y=this.#u.get(t);if(y===void 0){w&&(w.fetch="miss");let S=this.#z(t,y,E,p);return S.__returned=S}else{let S=this.#i[y];if(this.#l(S)){let st=s&&S.__staleWhileFetching!==void 0;return w&&(w.fetch="inflight",st&&(w.returnedStale=!0)),st?S.__staleWhileFetching:S.__returned=S}let B=this.#_(y);if(!b&&!B)return w&&(w.fetch="hit"),this.#N(y),i&&this.#x(y),w&&this.#D(w,y),S;let U=this.#z(t,y,E,p),et=U.__staleWhileFetching!==void 0&&s;return w&&(w.fetch=B?"stale":"refresh",et&&B&&(w.returnedStale=!0)),et?U.__staleWhileFetching:U.__returned=U}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:r,...h}=e,o=this.get(t,h);if(!r&&o!==void 0)return o;let a=s(t,o,{options:h,context:i});return this.set(t,a,h),a}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:h}=e,o=this.#u.get(t);if(o!==void 0){let a=this.#i[o],l=this.#l(a);return h&&this.#D(h,o),this.#_(o)?(h&&(h.get="stale"),l?(h&&s&&a.__staleWhileFetching!==void 0&&(h.returnedStale=!0),s?a.__staleWhileFetching:void 0):(r||this.#A(t,"expire"),h&&s&&(h.returnedStale=!0),s?a:void 0)):(h&&(h.get="hit"),l?a.__staleWhileFetching:(this.#N(o),i&&this.#x(o),a))}else h&&(h.get="miss")}#U(t,e){this.#v[e]=t,this.#d[t]=e}#N(t){t!==this.#p&&(t===this.#y?this.#y=this.#d[t]:this.#U(this.#v[t],this.#d[t]),this.#U(this.#p,t),this.#p=t)}delete(t){return this.#A(t,"delete")}#A(t,e){let s=!1;if(this.#o!==0){let i=this.#u.get(t);if(i!==void 0)if(this.#b?.[i]&&(clearTimeout(this.#b?.[i]),this.#b[i]=void 0),s=!0,this.#o===1)this.#q(e);else{this.#L(i);let r=this.#i[i];if(this.#l(r)?r.__abortController.abort(new Error("deleted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(r,t,e),this.#e&&this.#m?.push([r,t,e])),this.#u.delete(t),this.#a[i]=void 0,this.#i[i]=void 0,i===this.#p)this.#p=this.#v[i];else if(i===this.#y)this.#y=this.#d[i];else{let h=this.#v[i];this.#d[h]=this.#d[i];let o=this.#d[i];this.#v[o]=this.#v[i]}this.#o--,this.#R.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,r;for(;r=i?.shift();)this.#h?.(...r)}return s}clear(){return this.#q("delete")}#q(t){for(let e of this.#M({allowStale:!0})){let s=this.#i[e];if(this.#l(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#E&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#u.clear(),this.#i.fill(void 0),this.#a.fill(void 0),this.#g&&this.#T){this.#g.fill(0),this.#T.fill(0);for(let e of this.#b??[])e!==void 0&&clearTimeout(e);this.#b?.fill(void 0)}if(this.#O&&this.#O.fill(0),this.#y=0,this.#p=0,this.#R.length=0,this.#f=0,this.#o=0,this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#h?.(...s)}}};Wt.LRUCache=rr});var Oe=R(P=>{"use strict";var nr=P&&P.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(P,"__esModule",{value:!0});P.Minipass=P.isWritable=P.isReadable=P.isStream=void 0;var ds=typeof process=="object"&&process?process:{stdout:null,stderr:null},_e=__nccwpck_require__(8474),ws=nr(__nccwpck_require__(7075)),hr=__nccwpck_require__(6193),or=n=>!!n&&typeof n=="object"&&(n instanceof qt||n instanceof ws.default||(0,P.isReadable)(n)||(0,P.isWritable)(n));P.isStream=or;var ar=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.pipe=="function"&&n.pipe!==ws.default.Writable.prototype.pipe;P.isReadable=ar;var lr=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.write=="function"&&typeof n.end=="function";P.isWritable=lr;var $=Symbol("EOF"),q=Symbol("maybeEmitEnd"),K=Symbol("emittedEnd"),Bt=Symbol("emittingEnd"),lt=Symbol("emittedError"),It=Symbol("closed"),ps=Symbol("read"),Gt=Symbol("flush"),ms=Symbol("flushChunk"),L=Symbol("encoding"),rt=Symbol("decoder"),T=Symbol("flowing"),ct=Symbol("paused"),nt=Symbol("resume"),C=Symbol("buffer"),M=Symbol("pipes"),x=Symbol("bufferLength"),we=Symbol("bufferPush"),zt=Symbol("bufferShift"),k=Symbol("objectMode"),O=Symbol("destroyed"),be=Symbol("error"),ye=Symbol("emitData"),gs=Symbol("emitEnd"),Se=Symbol("emitEnd2"),I=Symbol("async"),ve=Symbol("abort"),Ut=Symbol("aborted"),ut=Symbol("signal"),Z=Symbol("dataListeners"),D=Symbol("discarded"),ft=n=>Promise.resolve().then(n),cr=n=>n(),ur=n=>n==="end"||n==="finish"||n==="prefinish",fr=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,dr=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),$t=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[nt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ee=class extends $t{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>e.emit("error",i),t.on("error",this.proxyErrors)}},pr=n=>!!n.objectMode,mr=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",qt=class extends _e.EventEmitter{[T]=!1;[ct]=!1;[M]=[];[C]=[];[k];[L];[I];[rt];[$]=!1;[K]=!1;[Bt]=!1;[It]=!1;[lt]=null;[x]=0;[O]=!1;[ut];[Ut]=!1;[Z]=0;[D]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");pr(e)?(this[k]=!0,this[L]=null):mr(e)?(this[L]=e.encoding,this[k]=!1):(this[k]=!1,this[L]=null),this[I]=!!e.async,this[rt]=this[L]?new hr.StringDecoder(this[L]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[C]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[M]});let{signal:s}=e;s&&(this[ut]=s,s.aborted?this[ve]():s.addEventListener("abort",()=>this[ve]()))}get bufferLength(){return this[x]}get encoding(){return this[L]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[I]}set async(t){this[I]=this[I]||!!t}[ve](){this[Ut]=!0,this.emit("abort",this[ut]?.reason),this.destroy(this[ut]?.reason)}get aborted(){return this[Ut]}set aborted(t){}write(t,e,s){if(this[Ut])return!1;if(this[$])throw new Error("write after end");if(this[O])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[I]?ft:cr;if(!this[k]&&!Buffer.isBuffer(t)){if(dr(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[T]&&this[x]!==0&&this[Gt](!0),this[T]?this.emit("data",t):this[we](t),this[x]!==0&&this.emit("readable"),s&&i(s),this[T]):t.length?(typeof t=="string"&&!(e===this[L]&&!this[rt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[L]&&(t=this[rt].write(t)),this[T]&&this[x]!==0&&this[Gt](!0),this[T]?this.emit("data",t):this[we](t),this[x]!==0&&this.emit("readable"),s&&i(s),this[T]):(this[x]!==0&&this.emit("readable"),s&&i(s),this[T])}read(t){if(this[O])return null;if(this[D]=!1,this[x]===0||t===0||t&&t>this[x])return this[q](),null;this[k]&&(t=null),this[C].length>1&&!this[k]&&(this[C]=[this[L]?this[C].join(""):Buffer.concat(this[C],this[x])]);let e=this[ps](t||null,this[C][0]);return this[q](),e}[ps](t,e){if(this[k])this[zt]();else{let s=e;t===s.length||t===null?this[zt]():typeof s=="string"?(this[C][0]=s.slice(t),e=s.slice(0,t),this[x]-=t):(this[C][0]=s.subarray(t),e=s.subarray(0,t),this[x]-=t)}return this.emit("data",e),!this[C].length&&!this[$]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[$]=!0,this.writable=!1,(this[T]||!this[ct])&&this[q](),this}[nt](){this[O]||(!this[Z]&&!this[M].length&&(this[D]=!0),this[ct]=!1,this[T]=!0,this.emit("resume"),this[C].length?this[Gt]():this[$]?this[q]():this.emit("drain"))}resume(){return this[nt]()}pause(){this[T]=!1,this[ct]=!0,this[D]=!1}get destroyed(){return this[O]}get flowing(){return this[T]}get paused(){return this[ct]}[we](t){this[k]?this[x]+=1:this[x]+=t.length,this[C].push(t)}[zt](){return this[k]?this[x]-=1:this[x]-=this[C][0].length,this[C].shift()}[Gt](t=!1){do;while(this[ms](this[zt]())&&this[C].length);!t&&!this[C].length&&!this[$]&&this.emit("drain")}[ms](t){return this.emit("data",t),this[T]}pipe(t,e){if(this[O])return t;this[D]=!1;let s=this[K];return e=e||{},t===ds.stdout||t===ds.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[M].push(e.proxyErrors?new Ee(this,t,e):new $t(this,t,e)),this[I]?ft(()=>this[nt]()):this[nt]()),t}unpipe(t){let e=this[M].find(s=>s.dest===t);e&&(this[M].length===1?(this[T]&&this[Z]===0&&(this[T]=!1),this[M]=[]):this[M].splice(this[M].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[D]=!1,this[Z]++,!this[M].length&&!this[T]&&this[nt]();else if(t==="readable"&&this[x]!==0)super.emit("readable");else if(ur(t)&&this[K])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[lt]){let i=e;this[I]?ft(()=>i.call(this,this[lt])):i.call(this,this[lt])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Z]=this.listeners("data").length,this[Z]===0&&!this[D]&&!this[M].length&&(this[T]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Z]=0,!this[D]&&!this[M].length&&(this[T]=!1)),e}get emittedEnd(){return this[K]}[q](){!this[Bt]&&!this[K]&&!this[O]&&this[C].length===0&&this[$]&&(this[Bt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[It]&&this.emit("close"),this[Bt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==O&&this[O])return!1;if(t==="data")return!this[k]&&!s?!1:this[I]?(ft(()=>this[ye](s)),!0):this[ye](s);if(t==="end")return this[gs]();if(t==="close"){if(this[It]=!0,!this[K]&&!this[O])return!1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[lt]=s,super.emit(be,s);let r=!this[ut]||this.listeners("error").length?super.emit("error",s):!1;return this[q](),r}else if(t==="resume"){let r=super.emit("resume");return this[q](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let i=super.emit(t,...e);return this[q](),i}[ye](t){for(let s of this[M])s.dest.write(t)===!1&&this.pause();let e=this[D]?!1:super.emit("data",t);return this[q](),e}[gs](){return this[K]?!1:(this[K]=!0,this.readable=!1,this[I]?(ft(()=>this[Se]()),!0):this[Se]())}[Se](){if(this[rt]){let e=this[rt].end();if(e){for(let s of this[M])s.dest.write(e);this[D]||super.emit("data",e)}}for(let e of this[M])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[k]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[L]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(O,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[D]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[$])return e();let r,h,o=c=>{this.off("data",a),this.off("end",l),this.off(O,f),e(),h(c)},a=c=>{this.off("error",o),this.off("end",l),this.off(O,f),this.pause(),r({value:c,done:!!this[$]})},l=()=>{this.off("error",o),this.off("data",a),this.off(O,f),e(),r({done:!0,value:void 0})},f=()=>o(new Error("stream destroyed"));return new Promise((c,d)=>{h=d,r=c,this.once(O,f),this.once("error",o),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[D]=!1;let t=!1,e=()=>(this.pause(),this.off(be,e),this.off(O,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(be,e),this.once(O,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this}}}destroy(t){if(this[O])return t?this.emit("error",t):this.emit(O),this;this[O]=!0,this[D]=!0,this[C].length=0,this[x]=0;let e=this;return typeof e.close=="function"&&!this[It]&&e.close(),t?this.emit("error",t):this.emit(O),this}static get isStream(){return P.isStream}};P.Minipass=qt});var Ms=R(_=>{"use strict";var gr=_&&_.__createBinding||(Object.create?(function(n,t,e,s){s===void 0&&(s=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,s,i)}):(function(n,t,e,s){s===void 0&&(s=e),n[s]=t[e]})),wr=_&&_.__setModuleDefault||(Object.create?(function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}):function(n,t){n.default=t}),br=_&&_.__importStar||function(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&gr(t,n,e);return wr(t,n),t};Object.defineProperty(_,"__esModule",{value:!0});_.PathScurry=_.Path=_.PathScurryDarwin=_.PathScurryPosix=_.PathScurryWin32=_.PathScurryBase=_.PathPosix=_.PathWin32=_.PathBase=_.ChildrenCache=_.ResolveCache=void 0;var Qt=fs(),Yt=__nccwpck_require__(6760),yr=__nccwpck_require__(3136),pt=__nccwpck_require__(9896),Sr=br(__nccwpck_require__(3024)),vr=pt.realpathSync.native,Ht=__nccwpck_require__(1455),bs=Oe(),mt={lstatSync:pt.lstatSync,readdir:pt.readdir,readdirSync:pt.readdirSync,readlinkSync:pt.readlinkSync,realpathSync:vr,promises:{lstat:Ht.lstat,readdir:Ht.readdir,readlink:Ht.readlink,realpath:Ht.realpath}},_s=n=>!n||n===mt||n===Sr?mt:{...mt,...n,promises:{...mt.promises,...n.promises||{}}},Os=/^\\\\\?\\([a-z]:)\\?$/i,Er=n=>n.replace(/\//g,"\\").replace(Os,"$1\\"),_r=/[\\\/]/,N=0,Ts=1,Cs=2,G=4,xs=6,Rs=8,Q=10,As=12,j=15,dt=~j,Te=16,ys=32,gt=64,W=128,Vt=256,Xt=512,Ss=gt|W|Xt,Or=1023,Ce=n=>n.isFile()?Rs:n.isDirectory()?G:n.isSymbolicLink()?Q:n.isCharacterDevice()?Cs:n.isBlockDevice()?xs:n.isSocket()?As:n.isFIFO()?Ts:N,vs=new Qt.LRUCache({max:2**12}),wt=n=>{let t=vs.get(n);if(t)return t;let e=n.normalize("NFKD");return vs.set(n,e),e},Es=new Qt.LRUCache({max:2**12}),Kt=n=>{let t=Es.get(n);if(t)return t;let e=wt(n.toLowerCase());return Es.set(n,e),e},bt=class extends Qt.LRUCache{constructor(){super({max:256})}};_.ResolveCache=bt;var Jt=class extends Qt.LRUCache{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}};_.ChildrenCache=Jt;var ks=Symbol("PathScurry setAsCwd"),A=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#h;get uid(){return this.#h}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#c;get blksize(){return this.#c}#o;get ino(){return this.#o}#f;get size(){return this.#f}#u;get blocks(){return this.#u}#a;get atimeMs(){return this.#a}#i;get mtimeMs(){return this.#i}#d;get ctimeMs(){return this.#d}#v;get birthtimeMs(){return this.#v}#y;get atime(){return this.#y}#p;get mtime(){return this.#p}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#O;#T;#g;#b;#E;#C;#e;#F;#P;#x;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=N,s,i,r,h,o){this.name=t,this.#O=r?Kt(t):wt(t),this.#e=e&Or,this.nocase=r,this.roots=i,this.root=s||this,this.#F=h,this.#g=o.fullpath,this.#E=o.relative,this.#C=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=_s(o.fs)}depth(){return this.#T!==void 0?this.#T:this.parent?this.#T=this.parent.depth()+1:this.#T=0}childrenCache(){return this.#F}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#D(i):this.#D(i)}#D(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#F.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#F.set(this,e),this.#e&=~Te,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?Kt(t):wt(t);for(let a of s)if(a.#O===i)return a;let r=this.parent?this.sep:"",h=this.#g?this.#g+r+t:void 0,o=this.newChild(t,N,{...e,parent:this,fullpath:h});return this.canReaddir()||(o.#e|=W),s.push(o),o}relative(){if(this.isCWD)return"";if(this.#E!==void 0)return this.#E;let t=this.name,e=this.parent;if(!e)return this.#E=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#C!==void 0)return this.#C;let t=this.name,e=this.parent;if(!e)return this.#C=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=i}fullpathPosix(){if(this.#b!==void 0)return this.#b;if(this.sep==="/")return this.#b=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#b=`//?/${i}`:this.#b=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#b=s}isUnknown(){return(this.#e&j)===N}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&j)===Rs}isDirectory(){return(this.#e&j)===G}isCharacterDevice(){return(this.#e&j)===Cs}isBlockDevice(){return(this.#e&j)===xs}isFIFO(){return(this.#e&j)===Ts}isSocket(){return(this.#e&j)===As}isSymbolicLink(){return(this.#e&Q)===Q}lstatCached(){return this.#e&ys?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#x}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let t=this.#e&j;return!(t!==N&&t!==Q||this.#e&Vt||this.#e&W)}calledReaddir(){return!!(this.#e&Te)}isENOENT(){return!!(this.#e&W)}isNamed(t){return this.nocase?this.#O===Kt(t):this.#O===wt(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}#W(t){this.#e|=Te;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#N.push(t),this.#A)return;this.#A=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(r,h)=>{if(r)this.#B(r.code),s.provisional=0;else{for(let o of h)this.#I(o,s);this.#W(s)}this.#q(s.slice(0,s.provisional))})}#H;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#H)await this.#H;else{let s=()=>{};this.#H=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#I(i,t);this.#W(t)}catch(i){this.#B(i.code),t.provisional=0}this.#H=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#I(s,t);this.#W(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ss)return!1;let t=j&this.#e;return t===N||t===G||t===Q}shouldWalk(t,e){return(this.#e&G)===G&&!(this.#e&Ss)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#x)return this.#x;if(!((Xt|Vt|W)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#x=this.resolve(t)}catch{this.#L()}}realpathSync(){if(this.#x)return this.#x;if(!((Xt|Vt|W)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#x=this.resolve(t)}catch{this.#L()}}[ks](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#E=s.join(this.sep),i.#C=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#E=void 0,i.#C=void 0,i=i.parent}};_.PathBase=A;var yt=class n extends A{sep="\\";splitSep=_r;constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return Yt.win32.parse(t).root}getRoot(t){if(t=Er(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new Et(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Os,"$1\\"),t===e}};_.PathWin32=yt;var St=class n extends A{splitSep="/";sep="/";constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}};_.PathPosix=St;var vt=class{root;rootPath;roots;cwd;#t;#s;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:r=16*1024,fs:h=mt}={}){this.#r=_s(h),(t instanceof URL||t.startsWith("file://"))&&(t=(0,yr.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new bt,this.#s=new bt,this.#n=new Jt(r);let a=o.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,f=a.length-1,c=e.sep,d=this.rootPath,u=!1;for(let m of a){let p=f--;l=l.child(m,{relative:new Array(p).fill("..").join(c),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(u?"":c)+m}),u=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(r=>r.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set,l=(c,d)=>{a.add(c),c.readdirCB((u,m)=>{if(u)return d(u);let p=m.length;if(!p)return d();let b=()=>{--p===0&&d()};for(let w of m)(!r||r(w))&&o.push(s?w:w.fullpath()),i&&w.isSymbolicLink()?w.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,h)?l(v,b):b()):w.shouldWalk(a,h)?l(w,b):b()},!0)},f=t;return new Promise((c,d)=>{l(f,u=>{if(u)return d(u);c(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let f=l.readdirSync();for(let c of f){(!r||r(c))&&o.push(s?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,h)&&a.add(d)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e;(!r||r(t))&&(yield s?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let f of l){(!r||r(f))&&(yield s?f:f.fullpath());let c=f;if(f.isSymbolicLink()){if(!(i&&(c=f.realpathSync())))continue;c.isUnknown()&&c.lstatSync()}c.shouldWalk(o,h)&&o.add(c)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0});(!r||r(t))&&o.write(s?t:t.fullpath());let a=new Set,l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=(b,w,v=!1)=>{if(b)return o.emit("error",b);if(i&&!v){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(S=>S?.isUnknown()?S.lstat():S));if(E.length){Promise.all(E).then(()=>m(null,w,!0));return}}for(let E of w)E&&(!r||r(E))&&(o.write(s?E:E.fullpath())||(d=!0));f--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,h)&&l.push(y)}d&&!o.flowing?o.once("drain",c):p||c()},p=!0;u.readdirCB(m,!0),p=!1}};return c(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0}),a=new Set;(!r||r(t))&&o.write(s?t:t.fullpath());let l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=u.readdirSync();for(let p of m)(!r||r(p))&&(o.write(s?p:p.fullpath())||(d=!0));f--;for(let p of m){let b=p;if(p.isSymbolicLink()){if(!(i&&(b=p.realpathSync())))continue;b.isUnknown()&&b.lstatSync()}b.shouldWalk(a,h)&&l.push(b)}}d&&!o.flowing&&o.once("drain",c)};return c(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[ks](e)}};_.PathScurryBase=vt;var Et=class extends vt{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,Yt.win32,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return Yt.win32.parse(t).root.toUpperCase()}newRoot(t){return new yt(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}};_.PathScurryWin32=Et;var _t=class extends vt{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,Yt.posix,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new St(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}};_.PathScurryPosix=_t;var Zt=class extends _t{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}};_.PathScurryDarwin=Zt;_.Path=process.platform==="win32"?yt:St;_.PathScurry=process.platform==="win32"?Et:process.platform==="darwin"?Zt:_t});var Re=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.Pattern=void 0;var Tr=H(),Cr=n=>n.length>=1,xr=n=>n.length>=1,xe=class n{#t;#s;#n;length;#r;#h;#S;#w;#c;#o;#f=!0;constructor(t,e,s,i){if(!Cr(t))throw new TypeError("empty pattern list");if(!xr(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[r,h,o,a,...l]=this.#t,[f,c,d,u,...m]=this.#s;l[0]===""&&(l.shift(),m.shift());let p=[r,h,o,a,""].join("/"),b=[f,c,d,u,""].join("/");this.#t=[p,...l],this.#s=[b,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...h]=this.#t,[o,...a]=this.#s;h[0]===""&&(h.shift(),a.shift());let l=r+"/",f=o+"/";this.#t=[l,...h],this.#s=[f,...a],this.length=this.#t.length}}}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===Tr.GLOBSTAR}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#S=this.#S||(this.#n===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#h!==void 0?this.#h:this.hasMore()?(this.#h=new n(this.#t,this.#s,this.#n+1,this.#r),this.#h.#o=this.#o,this.#h.#c=this.#c,this.#h.#w=this.#w,this.#h):this.#h=null}isUNC(){let t=this.#t;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#o!==void 0?this.#o:this.#o=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#f)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#f?!1:(this.#f=!1,!0)}};te.Pattern=xe});var ke=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.Ignore=void 0;var Ps=H(),Rr=Re(),Ar=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ae=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:r,platform:h=Ar}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=h,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:r,optimizationLevel:2,platform:h,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new Ps.Minimatch(t,this.mmopts);for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.Processor=z.SubWalks=z.MatchRecord=z.HasWalkedCache=void 0;var Ds=H(),se=class n{store;constructor(t=new Map){this.store=t}copy(){return new n(new Map(this.store))}hasWalked(t,e){return this.store.get(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),i=this.store.get(s);i?i.add(e.globString()):this.store.set(s,new Set([e.globString()]))}};z.HasWalkedCache=se;var ie=class{store=new Map;add(t,e,s){let i=(e?2:0)|(s?1:0),r=this.store.get(t);this.store.set(t,r===void 0?i:i&r)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}};z.MatchRecord=ie;var re=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}};z.SubWalks=re;var Me=class n{hasWalkedCache;matches=new ie;subwalks=new re;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new se}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,r]of s){this.hasWalkedCache.storeWalked(i,r);let h=r.root(),o=r.isAbsolute()&&this.opts.absolute!==!1;if(h){i=i.resolve(h==="/"&&this.opts.root!==void 0?this.opts.root:h);let c=r.rest();if(c)r=c;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,f=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)i=i.resolve(a),r=l,f=!0;if(a=r.pattern(),l=r.rest(),f){if(this.hasWalkedCache.hasWalked(i,r))continue;this.hasWalkedCache.storeWalked(i,r)}if(typeof a=="string"){let c=a===".."||a===""||a===".";this.matches.add(i.resolve(a),o,c);continue}else if(a===Ds.GLOBSTAR){(!i.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(i,r);let c=l?.pattern(),d=l?.rest();if(!l||(c===""||c===".")&&!d)this.matches.add(i,o,c===""||c===".");else if(c===".."){let u=i.parent||i;d?this.hasWalkedCache.hasWalked(u,d)||this.subwalks.add(u,d):this.matches.add(u,o,!0)}}else a instanceof RegExp&&this.subwalks.add(i,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let r of e)for(let h of s){let o=h.isAbsolute(),a=h.pattern(),l=h.rest();a===Ds.GLOBSTAR?i.testGlobstar(r,h,l,o):a instanceof RegExp?i.testRegExp(r,a,l,o):i.testString(r,a,l,o)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,s.rest(),i);else if(r===".."){let h=t.parent||t;this.subwalks.add(h,s)}else r instanceof RegExp&&this.testRegExp(t,r,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};z.Processor=Me});var Ls=R(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.GlobStream=X.GlobWalker=X.GlobUtil=void 0;var kr=Oe(),js=ke(),Ns=Fs(),Mr=(n,t)=>typeof n=="string"?new js.Ignore([n],t):Array.isArray(n)?new js.Ignore(n,t):n,Ot=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Mr(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#h(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=await r.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=r.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#s?.add){let r=`${t.relativePosix()}/**`;this.#s.add(r)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+i)}else{let r=this.opts.posix?t.relativePosix():t.relative(),h=this.opts.dotRelative&&!r.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(r?h+r+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Ns.Processor(this.opts),s)}walkCB2(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,s,h):o.readdirCB((l,f)=>this.walkCB3(o,f,s,h),!0)}h()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let[o,a]of s.subwalks.entries())r++,this.walkCB2(o,a,s.child(),h);h()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Ns.Processor(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirSync();this.walkCB3Sync(o,a,s,h)}h()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let[o,a]of s.subwalks.entries())r++,this.walkCB2Sync(o,a,s.child(),h);h()}};X.GlobUtil=Ot;var Pe=class extends Ot{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}};X.GlobWalker=Pe;var De=class extends Ot{results;constructor(t,e,s){super(t,e,s),this.results=new kr.Minipass({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};X.GlobStream=De});var je=R(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.Glob=void 0;var Pr=H(),Dr=__nccwpck_require__(3136),ne=Ms(),Fr=Re(),he=Ls(),jr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Fe=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Dr.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||jr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?ne.PathScurryWin32:e.platform==="darwin"?ne.PathScurryDarwin:e.platform?ne.PathScurryPosix:ne.PathScurry;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new Pr.Minimatch(a,i)),[h,o]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=h.map((a,l)=>{let f=o[l];if(!f)throw new Error("invalid pattern object");return new Fr.Pattern(a,f,0,this.platform)})}async walk(){return[...await new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};oe.Glob=Fe});var Ne=R(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.hasMagic=void 0;var Nr=H(),Lr=(n,t={})=>{Array.isArray(n)||(n=[n]);for(let e of n)if(new Nr.Minimatch(e,t).hasMagic())return!0;return!1};ae.hasMagic=Lr});Object.defineProperty(exports, "__esModule", ({value:!0}));exports.glob=exports.sync=exports.iterate=exports.iterateSync=exports.stream=exports.streamSync=exports.Ignore=exports.hasMagic=exports.Glob=exports.unescape=exports.escape=void 0;exports.globStreamSync=Tt;exports.globStream=Le;exports.globSync=We;exports.globIterateSync=Ct;exports.globIterate=Be;var Ws=H(),tt=je(),Wr=Ne(),Is=H();Object.defineProperty(exports, "escape", ({enumerable:!0,get:function(){return Is.escape}}));Object.defineProperty(exports, "unescape", ({enumerable:!0,get:function(){return Is.unescape}}));var Br=je();Object.defineProperty(exports, "Glob", ({enumerable:!0,get:function(){return Br.Glob}}));var Ir=Ne();Object.defineProperty(exports, "hasMagic", ({enumerable:!0,get:function(){return Ir.hasMagic}}));var Gr=ke();Object.defineProperty(exports, "Ignore", ({enumerable:!0,get:function(){return Gr.Ignore}}));function Tt(n,t={}){return new tt.Glob(n,t).streamSync()}function Le(n,t={}){return new tt.Glob(n,t).stream()}function We(n,t={}){return new tt.Glob(n,t).walkSync()}async function Bs(n,t={}){return new tt.Glob(n,t).walk()}function Ct(n,t={}){return new tt.Glob(n,t).iterateSync()}function Be(n,t={}){return new tt.Glob(n,t).iterate()}exports.streamSync=Tt;exports.stream=Object.assign(Le,{sync:Tt});exports.iterateSync=Ct;exports.iterate=Object.assign(Be,{sync:Ct});exports.sync=Object.assign(We,{stream:Tt,iterate:Ct});exports.glob=Object.assign(Bs,{glob:Bs,globSync:We,sync:exports.sync,globStream:Le,stream:exports.stream,globStreamSync:Tt,streamSync:exports.streamSync,globIterate:Be,iterate:exports.iterate,globIterateSync:Ct,iterateSync:exports.iterateSync,Glob:tt.Glob,hasMagic:Wr.hasMagic,escape:Ws.escape,unescape:Ws.unescape});exports.glob.glob=exports.glob; -//# sourceMappingURL=index.min.js.map - - /***/ }) /******/ }); diff --git a/dist/run-changesets/index.js b/dist/run-changesets/index.js new file mode 100755 index 0000000..d305fe3 --- /dev/null +++ b/dist/run-changesets/index.js @@ -0,0 +1,4983 @@ +#!/usr/bin/env node +/******/ (() => { // webpackBootstrap +/******/ "use strict"; +/******/ var __webpack_modules__ = ({ + +/***/ 809: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const fs = __nccwpck_require__(896); +const path = __nccwpck_require__(928); +const { globSync } = __nccwpck_require__(941); +const yaml = __nccwpck_require__(281); + +// ── Logging (replaces @actions/core logging) ────────────────────────────────── + +function info(msg) { + console.log(msg); +} + +function logError(msg) { + console.error(msg); +} + +function warn(msg) { + console.warn(msg); +} + +function debug(msg) { + if (process.env.INPROD_DEBUG === 'true') { + console.log(`[DEBUG] ${msg}`); + } +} + +// ── Output file writing (replaces core.setOutput) ───────────────────────────── + +function writeOutputs(status, resultArray) { + fs.writeFileSync('inprod-results.env', `INPROD_STATUS=${status}\n`); + fs.writeFileSync('inprod-result.json', JSON.stringify(resultArray, null, 2)); +} + +// ── API polling ─────────────────────────────────────────────────────────────── + +async function pollTask(baseUrl, apiKey, taskId, label, pollingTimeoutSeconds) { + const pollInterval = 5; // seconds + const pollUrl = `${baseUrl}/api/v1/task-status/${taskId}/`; + let elapsed = 0; + + info(`${label} dispatched as background task (task_id: ${taskId})`); + info(`Polling for completion (interval: ${pollInterval}s, timeout: ${pollingTimeoutSeconds}s)...`); + + while (elapsed < pollingTimeoutSeconds) { + await new Promise(resolve => setTimeout(resolve, pollInterval * 1000)); + elapsed += pollInterval; + + try { + const pollResponse = await fetch(pollUrl, { + method: 'GET', + headers: { + 'Authorization': `Api-Key ${apiKey}` + } + }); + + if (!pollResponse.ok) { + const errorBody = await pollResponse.text(); + throw new Error( + `Poll failed with status ${pollResponse.status}: ${errorBody || pollResponse.statusText}` + ); + } + + const pollData = await pollResponse.json(); + debug(`Poll response: ${JSON.stringify(pollData)}`); + + const status = pollData.status; + info(` ${label} status: ${status} (${elapsed}s elapsed)`); + + if (status === 'SUCCESS') { + info(`${label} completed successfully`); + return { status: 'SUCCESS', result: pollData.result || {} }; + } else if (status === 'FAILURE') { + const error = pollData.error || 'Unknown error'; + return { status: 'FAILURE', error }; + } else if (status === 'REVOKED') { + return { status: 'REVOKED' }; + } + // PENDING, STARTED, RETRY — continue polling + } catch (e) { + if (e.message && (e.message.includes('Poll failed'))) { + throw e; + } + warn(`Error during polling: ${e.message}. Retrying...`); + debug(`Poll error details: ${e.stack}`); + } + } + + return { status: 'TIMEOUT' }; +} + +// ── URL builder ─────────────────────────────────────────────────────────────── + +function buildUrl(baseUrl, endpoint, environment) { + const envParam = environment ? `?environment=${encodeURIComponent(environment)}` : ''; + return `${baseUrl}${endpoint}${envParam}`; +} + +// ── Variable injection ──────────────────────────────────────────────────────── + +function injectYamlVariables(content, changesetVariables) { + const doc = yaml.load(content); + + const existingVars = Array.isArray(doc.variable) ? doc.variable : []; + const injectedVars = Object.entries(changesetVariables).map(([name, value]) => { + const existingEntries = existingVars.filter(v => v.name === name); + const maskValue = existingEntries.some(v => v.mask_value === true) ? true : false; + return { + environment: null, + mask_value: maskValue, + name, + value, + }; + }); + + const overrideNames = new Set(Object.keys(changesetVariables)); + const keptVars = existingVars.filter(v => !overrideNames.has(v.name)); + + doc.variable = [...keptVars, ...injectedVars]; + + return yaml.dump(doc, { lineWidth: -1, noRefs: true }); +} + +function injectJsonVariables(content, changesetVariables) { + const doc = JSON.parse(content); + + const existingVars = Array.isArray(doc.variable) ? doc.variable : []; + const injectedVars = Object.entries(changesetVariables).map(([name, value]) => { + const existingEntries = existingVars.filter(v => v.name === name); + const maskValue = existingEntries.some(v => v.mask_value === true) ? true : false; + return { + environment: null, + mask_value: maskValue, + name, + value, + }; + }); + + const overrideNames = new Set(Object.keys(changesetVariables)); + const keptVars = existingVars.filter(v => !overrideNames.has(v.name)); + + doc.variable = [...keptVars, ...injectedVars]; + + return JSON.stringify(doc, null, 2); +} + +// ── INPROD_FILES: temp-file upload support ──────────────────────────────────── + +// Exact list from inprod-bow/src/changeset/utils/native2gcfg.py:30-36 (BAD_VARIABLES) +const BAD_VARIABLES = new Set([ + 'break', 'case', 'catch', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'finally', 'for', + 'function', 'if', 'in', 'instanceof', 'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', + 'var', 'void', 'while', 'with', 'class', 'const', 'enum', 'export', 'extends', 'import', 'super', + 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', + 'yield', 'null', 'true', 'false', 'NaN', 'Infinity', 'undefined', 'int', 'byte', 'char', + 'goto', 'long', 'final', 'float', 'short', 'double', 'native', 'throws', 'boolean', 'abstract', + 'volatile', 'transient', 'synchronized', +]); + +// Exact set from inprod-bow/src/changeset/models.py:237 (ChangeSet.RESERVED_VARIABLE_NAMES) +const RESERVED_VARIABLE_NAMES = new Set(['callback_url']); + +// Exact regex from inprod-bow/src/changeset/utils/native2gcfg.py:1857 (test_variable_name) +const VALID_VARIABLE_NAME_RE = /^[A-Za-z_]\w*$/; + +function assertValidVariableName(name) { + if (!name) { + throw new Error(`INPROD_FILES: invalid variable name "${name}" (must not be empty)`); + } + if (name.length > 40) { + throw new Error(`INPROD_FILES: invalid variable name "${name}" (must be 40 characters or fewer)`); + } + if (!VALID_VARIABLE_NAME_RE.test(name)) { + throw new Error(`INPROD_FILES: invalid variable name "${name}" (must start with a letter or underscore, followed by letters, digits, or underscores)`); + } + if (BAD_VARIABLES.has(name)) { + throw new Error(`INPROD_FILES: invalid variable name "${name}" (is a reserved JavaScript word)`); + } + if (RESERVED_VARIABLE_NAMES.has(name)) { + throw new Error(`INPROD_FILES: invalid variable name "${name}" ("${name}" is reserved by InProd)`); + } +} + +function parseInprodFiles(input) { + const trimmedInput = (input || '').trim(); + if (!trimmedInput) return []; + + const parsed = []; + const lines = trimmedInput.split('\n'); + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; + + const eq = trimmed.indexOf('='); + if (eq < 1) { + throw new Error(`INPROD_FILES: malformed entry "${trimmed}" (expected VARNAME=path)`); + } + const name = trimmed.slice(0, eq).trim(); + const filePath = trimmed.slice(eq + 1).trim(); + if (!filePath) { + throw new Error(`INPROD_FILES: malformed entry "${trimmed}" (expected VARNAME=path)`); + } + parsed.push({ name, path: filePath }); + } + return parsed; +} + +async function uploadTempFile(filePath, baseUrl, apiKey) { + const endpoint = `${baseUrl}/api/v1/change-set/temp-file/`; + const fileName = path.basename(filePath); + + const buffer = fs.readFileSync(filePath); + const form = new FormData(); + form.append('file', new Blob([buffer]), fileName); + + let response; + try { + response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Authorization': `Api-Key ${apiKey}` + }, + body: form + }); + } catch (error) { + logError(`Network error connecting to InProd API: ${error.message}`); + debug(`Full error details: ${error.stack}`); + throw new Error(`Failed to connect to InProd API at ${endpoint}: ${error.message}`); + } + + if (response.status === 413) { + throw new Error(`Temp-file upload failed: ${fileName} (${filePath}) exceeds the server size limit`); + } + + if (!response.ok) { + const errorBody = await response.text(); + throw new Error(`Temp-file upload failed for ${fileName}: HTTP ${response.status} ${errorBody || response.statusText}`); + } + + const data = await response.json(); + // Never log `data.url` — it's a 24h bearer credential (see changeset-temp-file-requirements.md §6). + // file_name/expires_at are safe to log even in debug mode. + debug(`Temp-file upload succeeded: file_name=${data.file_name}, expires_at=${data.expires_at}`); + return data; +} + +async function uploadInprodFiles(resolvedFiles, baseUrl, apiKey) { + const vars = {}; + info(`Uploading ${resolvedFiles.length} file(s) to InProd temp-file store...`); + + for (const { name, path: filePath } of resolvedFiles) { + const result = await uploadTempFile(filePath, baseUrl, apiKey); + info(` Uploaded: ${result.file_name} → ${name}`); + vars[name] = result.url; + } + + return vars; +} + +// ── File format detection ───────────────────────────────────────────────────── + +function getFileFormat(filePath) { + const ext = path.extname(filePath).toLowerCase(); + if (ext === '.json') return 'json'; + return 'yaml'; // .yaml, .yml, or any other extension defaults to yaml +} + +// ── Glob / file resolution ──────────────────────────────────────────────────── + +function isGlobPattern(pattern) { + return /[*?[\]{}]/.test(pattern); +} + +function resolveFiles(changesetFile) { + if (!changesetFile || changesetFile.trim() === '') { + throw new Error('changeset_file is required'); + } + + if (isGlobPattern(changesetFile)) { + // Normalize to forward slashes for cross-platform glob compatibility + const normalizedPattern = changesetFile.replace(/\\/g, '/'); + const matches = globSync(normalizedPattern, { nodir: true }); + if (matches.length === 0) { + throw new Error(`No files matched the pattern: ${changesetFile}`); + } + const filePaths = matches + .map(f => path.resolve(f)) + .sort((a, b) => path.basename(a).localeCompare(path.basename(b))); + info(`Matched ${filePaths.length} file(s) for pattern: ${changesetFile}`); + filePaths.forEach((f, i) => info(` [${i + 1}] ${path.basename(f)}`)); + return filePaths; + } + + const filePath = path.resolve(changesetFile); + if (!fs.existsSync(filePath)) { + throw new Error(`Changeset file not found: ${filePath}`); + } + return [filePath]; +} + +// ── Validate a single changeset file ───────────────────────────────────────── + +async function validateFile(filePath, options) { + const { apiKey, baseUrl, environment, pollingTimeoutSeconds, changesetVariables } = options; + const content = fs.readFileSync(filePath, 'utf8'); + const format = getFileFormat(filePath); + const endpoint = format === 'json' + ? '/api/v1/change-set/change-set/validate_json/' + : '/api/v1/change-set/change-set/validate_yaml/'; + const validateUrl = buildUrl(baseUrl, endpoint, environment); + + debug(`Validate URL: ${validateUrl} (format: ${format})`); + + let body, contentType; + if (format === 'json') { + contentType = 'application/json'; + body = changesetVariables ? injectJsonVariables(content, changesetVariables) : content; + } else { + contentType = 'application/yaml'; + body = changesetVariables ? injectYamlVariables(content, changesetVariables) : content; + } + + debug(`Sending validation request to: ${validateUrl}`); + let validateResponse; + try { + validateResponse = await fetch(validateUrl, { + method: 'POST', + headers: { + 'Authorization': `Api-Key ${apiKey}`, + 'Content-Type': contentType + }, + body + }); + debug(`API response status: ${validateResponse.status}`); + } catch (error) { + logError(`Network error connecting to InProd API: ${error.message}`); + debug(`Full error details: ${error.stack}`); + throw new Error(`Failed to connect to InProd API at ${validateUrl}: ${error.message}`); + } + + if (!validateResponse.ok) { + const errorBody = await validateResponse.text(); + throw new Error( + `Validation request failed with status ${validateResponse.status}: ${errorBody || validateResponse.statusText}` + ); + } + + const validateData = await validateResponse.json(); + debug(`Validate response: ${JSON.stringify(validateData)}`); + + let validateTaskId; + try { + validateTaskId = validateData.data.attributes.task_id; + } catch (e) { + throw new Error( + `Failed to extract task_id from validation response. Response: ${JSON.stringify(validateData)}` + ); + } + + if (!validateTaskId || validateTaskId.trim() === '') { + throw new Error('Validation API returned an empty task_id'); + } + + const validateResult = await pollTask(baseUrl, apiKey, validateTaskId, 'Validation', pollingTimeoutSeconds); + + if (validateResult.status === 'TIMEOUT') { + return { taskId: validateTaskId, status: 'TIMEOUT', result: {}, error: `Validation did not complete within ${pollingTimeoutSeconds} seconds` }; + } + if (validateResult.status === 'FAILURE') { + return { status: 'FAILURE', result: {}, error: `Validation failed: ${validateResult.error}` }; + } + if (validateResult.status === 'REVOKED') { + return { status: 'REVOKED', result: {}, error: 'Validation task was cancelled' }; + } + + const isValid = validateResult.result.is_valid; + if (!isValid) { + const validationErrors = JSON.stringify(validateResult.result.validation_results || [], null, 2); + logError(`Validation errors:\n${validationErrors}`); + return { status: 'FAILURE', result: validateResult.result, error: 'Changeset validation failed. See validation errors above.' }; + } + + info(`✓ Validation passed`); + if (validateResult.result.changeset_name) { + info(` Changeset: ${validateResult.result.changeset_name}`); + } + if (validateResult.result.environment) { + info(` Environment: ${JSON.stringify(validateResult.result.environment)}`); + } + + return { status: 'SUCCESS', result: validateResult.result }; +} + +// ── Execute a single changeset file ────────────────────────────────────────── + +async function executeFile(filePath, options) { + const { apiKey, baseUrl, environment, pollingTimeoutSeconds, changesetVariables } = options; + const content = fs.readFileSync(filePath, 'utf8'); + const format = getFileFormat(filePath); + const endpoint = format === 'json' + ? '/api/v1/change-set/change-set/execute_json/' + : '/api/v1/change-set/change-set/execute_yaml/'; + const executeUrl = buildUrl(baseUrl, endpoint, environment); + + debug(`Execute URL: ${executeUrl} (format: ${format})`); + + let body, contentType; + if (format === 'json') { + contentType = 'application/json'; + body = changesetVariables ? injectJsonVariables(content, changesetVariables) : content; + } else { + contentType = 'application/yaml'; + body = changesetVariables ? injectYamlVariables(content, changesetVariables) : content; + } + + debug(`Sending API request to: ${executeUrl}`); + let executeResponse; + try { + executeResponse = await fetch(executeUrl, { + method: 'POST', + headers: { + 'Authorization': `Api-Key ${apiKey}`, + 'Content-Type': contentType + }, + body + }); + debug(`API response status: ${executeResponse.status}`); + } catch (error) { + logError(`Network error connecting to InProd API: ${error.message}`); + debug(`Full error details: ${error.stack}`); + throw new Error(`Failed to connect to InProd API at ${executeUrl}: ${error.message}`); + } + + if (!executeResponse.ok) { + const errorBody = await executeResponse.text(); + throw new Error( + `API request failed with status ${executeResponse.status}: ${errorBody || executeResponse.statusText}` + ); + } + + const executeData = await executeResponse.json(); + debug(`Execute response: ${JSON.stringify(executeData)}`); + + let taskId; + try { + taskId = executeData.data.attributes.task_id; + } catch (e) { + throw new Error( + `Failed to extract task_id from API response. Response: ${JSON.stringify(executeData)}` + ); + } + + if (!taskId || taskId.trim() === '') { + throw new Error('API returned an empty task_id'); + } + + info(`✓ Changeset submitted successfully`); + + const pollResult = await pollTask(baseUrl, apiKey, taskId, 'Execution', pollingTimeoutSeconds); + + if (pollResult.status === 'SUCCESS') { + info(`✓ Changeset executed successfully`); + return { status: 'SUCCESS', result: pollResult.result }; + } else if (pollResult.status === 'FAILURE') { + logError(`✗ Task failed: ${pollResult.error}`); + return { status: 'FAILURE', result: {}, error: `Changeset execution failed: ${pollResult.error}` }; + } else if (pollResult.status === 'REVOKED') { + warn(`⚠ Task was cancelled/revoked`); + return { status: 'REVOKED', result: {}, error: 'Changeset execution was cancelled' }; + } else if (pollResult.status === 'TIMEOUT') { + return { status: 'TIMEOUT', result: {}, error: `Changeset execution did not complete within ${pollingTimeoutSeconds} seconds` }; + } + + return { status: pollResult.status, result: {} }; +} + +// ── Process a single file (validate + execute) ──────────────────────────────── + +async function processSingleFile(filePath, options) { + const { validateBeforeExecute, validateOnly } = options; + const fileName = path.basename(filePath); + + info(`Read changeset from file: ${fileName}`); + + // Step 1: Validate (if needed) + if (validateOnly || validateBeforeExecute) { + info('Validating changeset...'); + const valResult = await validateFile(filePath, options); + + if (valResult.status !== 'SUCCESS') { + return { file: filePath, status: valResult.status, result: valResult.result, error: valResult.error }; + } + + if (validateOnly) { + return { file: filePath, status: 'SUCCESS', result: valResult.result }; + } + } + + // Step 2: Execute + info('Submitting changeset for execution...'); + const execResult = await executeFile(filePath, options); + + if (execResult.error) { + return { file: filePath, status: execResult.status, result: execResult.result, error: execResult.error }; + } + + if (execResult.result.run_id) { + info(`Run ID: ${execResult.result.run_id}`); + } + if (execResult.result.changeset_name) { + info(`Changeset: ${execResult.result.changeset_name}`); + } + if (execResult.result.environment) { + info(`Environment: ${JSON.stringify(execResult.result.environment)}`); + } + + return { file: filePath, status: execResult.status, result: execResult.result }; +} + +// ── Status priority ─────────────────────────────────────────────────────────── + +const STATUS_PRIORITY = { FAILURE: 0, TIMEOUT: 1, REVOKED: 2, SUBMITTED: 3, SUCCESS: 4 }; + +function worstStatus(results) { + return results.reduce((worst, r) => { + return (STATUS_PRIORITY[r.status] ?? 99) < (STATUS_PRIORITY[worst] ?? 99) ? r.status : worst; + }, 'SUCCESS'); +} + +// ── Main entry point ────────────────────────────────────────────────────────── + +async function run() { + try { + // Read all configuration from environment variables + const apiKey = (process.env.INPROD_API_KEY || '').trim(); + const baseUrl = (process.env.INPROD_BASE_URL || '').replace(/\/$/, '').trim(); + const changesetFile = (process.env.INPROD_CHANGESET_FILE || '').trim(); + const environment = (process.env.INPROD_ENVIRONMENT || '').trim(); + const validateBeforeExecute = (process.env.INPROD_VALIDATE_BEFORE_EXECUTE || 'true') !== 'false'; + const validateOnly = (process.env.INPROD_VALIDATE_ONLY || 'false') === 'true'; + const pollingTimeoutMinutes = parseInt(process.env.INPROD_POLLING_TIMEOUT_MINUTES || '10', 10) || 10; + const pollingTimeoutSeconds = pollingTimeoutMinutes * 60; + const executionStrategy = (process.env.INPROD_EXECUTION_STRATEGY || 'per_file').trim(); + const failFast = (process.env.INPROD_FAIL_FAST || 'false') === 'true'; + const changesetVariablesInput = process.env.INPROD_CHANGESET_VARIABLES || ''; + const inprodFilesInput = process.env.INPROD_FILES || ''; + + // Parse changeset variables from KEY=VALUE format + let changesetVariables = null; + if (changesetVariablesInput && changesetVariablesInput.trim()) { + changesetVariables = {}; + const lines = changesetVariablesInput.trim().split('\n'); + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) continue; // Skip empty lines and comments + const [key, ...valueParts] = trimmed.split('='); + if (!key || valueParts.length === 0) { + throw new Error(`Invalid changeset_variables format. Expected KEY=VALUE on each line, got: ${trimmed}`); + } + changesetVariables[key.trim()] = valueParts.join('=').trim(); // Handle values with = in them + } + debug(`Parsed changeset variables: ${JSON.stringify(Object.keys(changesetVariables))} (values masked)`); + } + + // Parse INPROD_FILES (pure — no filesystem/network access yet) + const parsedInprodFiles = parseInprodFiles(inprodFilesInput); + + // Validate required inputs + if (!apiKey) { + throw new Error('api_key is required and cannot be empty'); + } + if (!baseUrl) { + throw new Error('base_url is required and cannot be empty'); + } + + // Validate URL format + try { + new URL(baseUrl); + } catch (e) { + throw new Error(`Invalid base_url format: ${baseUrl}`); + } + + // Resolve every INPROD_FILES path once (absolute, relative to cwd — same convention + // as resolveFiles()), then validate before any HTTP call. The resolved path is reused + // for the upload itself so a later upload-error message can never disagree with the + // "file not found"/"not readable" message for the same file. + const resolvedInprodFiles = parsedInprodFiles.map(({ name, path: rawPath }) => ({ + name, + path: path.resolve(rawPath), + })); + const fileVarNames = new Set(); + for (const { name, path: resolvedPath } of resolvedInprodFiles) { + assertValidVariableName(name); + if (!fs.existsSync(resolvedPath)) { + throw new Error(`INPROD_FILES: ${name} → file not found: ${resolvedPath}`); + } + try { + fs.accessSync(resolvedPath, fs.constants.R_OK); + } catch (e) { + throw new Error(`INPROD_FILES: ${name} → file not readable: ${resolvedPath}`); + } + fileVarNames.add(name); + } + + // Resolve changeset files (also validates changeset_file is provided) + const filePaths = resolveFiles(changesetFile); + + // Reject INPROD_FILES names that collide with an already-masked variable in any + // changeset file about to be processed. File-URL variables can never work while + // masked (stripped from the JS scope before [?? ?? ] is evaluated server-side), so + // this fails fast with a clear message instead of silently overriding. Still zero + // HTTP calls at this point. Spans every resolved file (glob-aware) since + // changesetVariables is injected uniformly into all of them. + if (fileVarNames.size > 0) { + for (const fp of filePaths) { + const content = fs.readFileSync(fp, 'utf8'); + const format = getFileFormat(fp); + const doc = format === 'json' ? JSON.parse(content) : yaml.load(content); + const existingVars = Array.isArray(doc.variable) ? doc.variable : []; + for (const v of existingVars) { + if (fileVarNames.has(v.name) && v.mask_value === true) { + throw new Error( + `INPROD_FILES: "${v.name}" is not a valid variable — it is already declared as masked in ${path.basename(fp)}` + ); + } + } + } + } + + // Upload INPROD_FILES and merge the returned signed URLs into changesetVariables. + // Always re-uploaded on every invocation — signed URLs are never cached/reused. + if (parsedInprodFiles.length > 0) { + const uploadedVars = await uploadInprodFiles(resolvedInprodFiles, baseUrl, apiKey); + changesetVariables = { ...(changesetVariables || {}), ...uploadedVars }; + } + + const options = { + apiKey, baseUrl, environment, validateBeforeExecute, validateOnly, + pollingTimeoutSeconds, changesetVariables, + }; + + info(`InProd Run Changesets`); + info(`Base URL: ${baseUrl}`); + if (environment) { + info(`Target environment: ${environment}`); + } + info(`Files to process: ${filePaths.length}`); + info(`Execution strategy: ${executionStrategy}`); + info(`Fail fast: ${failFast}`); + info(`Validate before execute: ${validateBeforeExecute}`); + info(`Validate only: ${validateOnly}`); + info(`Polling timeout: ${pollingTimeoutMinutes} minutes (${pollingTimeoutSeconds} seconds)`); + if (changesetVariables) { + info(`Changeset variables: ${Object.keys(changesetVariables).length} variable(s) provided`); + } + if (parsedInprodFiles.length > 0) { + info(`Files to upload: ${parsedInprodFiles.length} file(s) via INPROD_FILES`); + } + + const results = []; + + if (executionStrategy === 'validate_first' && !validateOnly && !validateBeforeExecute) { + warn('validate_first strategy is set but INPROD_VALIDATE_BEFORE_EXECUTE is false. Falling back to per_file strategy.'); + } + + if (executionStrategy === 'validate_first' && !validateOnly && validateBeforeExecute) { + // Phase 1: Validate all files + for (let i = 0; i < filePaths.length; i++) { + const filePath = filePaths[i]; + const fileName = path.basename(filePath); + info(`\n--- Validating [${i + 1}/${filePaths.length}]: ${fileName} ---`); + try { + const valResult = await validateFile(filePath, options); + if (valResult.status !== 'SUCCESS') { + results.push({ file: filePath, taskId: valResult.taskId, status: valResult.status, result: valResult.result, error: valResult.error }); + if (failFast) { + logError(`Stopping: fail_fast is enabled and ${fileName} failed validation.`); + break; + } + continue; + } + } catch (error) { + results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); + if (failFast) { + logError(`Stopping: fail_fast is enabled and ${fileName} failed validation.`); + break; + } + continue; + } + } + + // If any validation failed, write outputs and stop before executing + const validationFailures = results.filter(r => r.status !== 'SUCCESS'); + if (validationFailures.length > 0) { + const resultArray = results.map(r => ({ + file: path.basename(r.file), + status: r.status, + result: r.result || {}, + error: r.error || null, + })); + writeOutputs('FAILURE', resultArray); + const msg = validationFailures.length === 1 + ? validationFailures[0].error + : `${validationFailures.length} of ${filePaths.length} changeset(s) failed validation. See result output for details.`; + throw new Error(msg); + } + + info(`\n✓ All ${filePaths.length} file(s) passed validation. Starting execution...`); + + // Phase 2: Execute all files (skip re-validation) + const executeOptions = { ...options, validateBeforeExecute: false, validateOnly: false }; + for (let i = 0; i < filePaths.length; i++) { + const filePath = filePaths[i]; + const fileName = path.basename(filePath); + info(`\n--- Executing [${i + 1}/${filePaths.length}]: ${fileName} ---`); + try { + const fileResult = await processSingleFile(filePath, executeOptions); + results.push(fileResult); + if (fileResult.error && failFast) { + logError(`Stopping: fail_fast is enabled and ${fileName} failed.`); + break; + } + } catch (error) { + results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); + if (failFast) { + logError(`Stopping: fail_fast is enabled and ${fileName} failed.`); + break; + } + } + } + } else { + // per_file strategy: full flow for each file sequentially + for (let i = 0; i < filePaths.length; i++) { + const filePath = filePaths[i]; + const fileName = path.basename(filePath); + info(`\n--- Processing [${i + 1}/${filePaths.length}]: ${fileName} ---`); + try { + const fileResult = await processSingleFile(filePath, options); + results.push(fileResult); + if (fileResult.error && failFast) { + logError(`Stopping: fail_fast is enabled and ${fileName} failed.`); + break; + } + } catch (error) { + results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); + if (failFast) { + logError(`Stopping: fail_fast is enabled and ${fileName} failed.`); + break; + } + } + } + } + + // Compute and write aggregate outputs + const aggregateStatus = worstStatus(results); + const resultArray = results.map(r => ({ + file: path.basename(r.file), + status: r.status, + result: r.result || {}, + error: r.error || null, + })); + writeOutputs(aggregateStatus, resultArray); + + info(`\nRun completed with status: ${aggregateStatus}`); + + // Fail the action if any file had a non-success status + if (aggregateStatus === 'FAILURE' || aggregateStatus === 'TIMEOUT' || aggregateStatus === 'REVOKED') { + const failedFiles = results.filter(r => r.status !== 'SUCCESS' && r.status !== 'SUBMITTED'); + const msg = failedFiles.length === 1 + ? failedFiles[0].error + : `${failedFiles.length} of ${results.length} changeset(s) failed. See result output for details.`; + throw new Error(msg); + } + + } catch (error) { + logError(error.message); + debug(`Error stack: ${error.stack}`); + process.exit(1); + } +} + +module.exports = { + run, pollTask, buildUrl, isGlobPattern, resolveFiles, worstStatus, getFileFormat, + injectYamlVariables, injectJsonVariables, + parseInprodFiles, assertValidVariableName, uploadTempFile, uploadInprodFiles, +}; + +/* istanbul ignore next */ +if (require.main === require.cache[eval('__filename')]) { + run(); +} + + +/***/ }), + +/***/ 281: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const loader = __nccwpck_require__(950) +const dumper = __nccwpck_require__(980) + +function renamed (from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.') + } +} + +module.exports.Type = __nccwpck_require__(557) +module.exports.Schema = __nccwpck_require__(46) +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(832) +module.exports.JSON_SCHEMA = __nccwpck_require__(927) +module.exports.CORE_SCHEMA = __nccwpck_require__(746) +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(336) +module.exports.load = loader.load +module.exports.loadAll = loader.loadAll +module.exports.dump = dumper.dump +module.exports.YAMLException = __nccwpck_require__(248) + +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: __nccwpck_require__(149), + float: __nccwpck_require__(584), + map: __nccwpck_require__(316), + null: __nccwpck_require__(333), + pairs: __nccwpck_require__(267), + set: __nccwpck_require__(758), + timestamp: __nccwpck_require__(966), + bool: __nccwpck_require__(296), + int: __nccwpck_require__(271), + merge: __nccwpck_require__(854), + omap: __nccwpck_require__(649), + seq: __nccwpck_require__(161), + str: __nccwpck_require__(929) +} + +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load') +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll') +module.exports.safeDump = renamed('safeDump', 'dump') + + +/***/ }), + +/***/ 816: +/***/ ((module) => { + + + +function isNothing (subject) { + return (typeof subject === 'undefined') || (subject === null) +} + +function isObject (subject) { + return (typeof subject === 'object') && (subject !== null) +} + +function toArray (sequence) { + if (Array.isArray(sequence)) return sequence + else if (isNothing(sequence)) return [] + + return [sequence] +} + +function extend (target, source) { + if (source) { + const sourceKeys = Object.keys(source) + + for (let index = 0, length = sourceKeys.length; index < length; index += 1) { + const key = sourceKeys[index] + target[key] = source[key] + } + } + + return target +} + +function repeat (string, count) { + let result = '' + + for (let cycle = 0; cycle < count; cycle += 1) { + result += string + } + + return result +} + +function isNegativeZero (number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number) +} + +module.exports.isNothing = isNothing +module.exports.isObject = isObject +module.exports.toArray = toArray +module.exports.repeat = repeat +module.exports.isNegativeZero = isNegativeZero +module.exports.extend = extend + + +/***/ }), + +/***/ 980: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const common = __nccwpck_require__(816) +const YAMLException = __nccwpck_require__(248) +const DEFAULT_SCHEMA = __nccwpck_require__(336) + +const _toString = Object.prototype.toString +const _hasOwnProperty = Object.prototype.hasOwnProperty + +const CHAR_BOM = 0xFEFF +const CHAR_TAB = 0x09 /* Tab */ +const CHAR_LINE_FEED = 0x0A /* LF */ +const CHAR_CARRIAGE_RETURN = 0x0D /* CR */ +const CHAR_SPACE = 0x20 /* Space */ +const CHAR_EXCLAMATION = 0x21 /* ! */ +const CHAR_DOUBLE_QUOTE = 0x22 /* " */ +const CHAR_SHARP = 0x23 /* # */ +const CHAR_PERCENT = 0x25 /* % */ +const CHAR_AMPERSAND = 0x26 /* & */ +const CHAR_SINGLE_QUOTE = 0x27 /* ' */ +const CHAR_ASTERISK = 0x2A /* * */ +const CHAR_COMMA = 0x2C /* , */ +const CHAR_MINUS = 0x2D /* - */ +const CHAR_COLON = 0x3A /* : */ +const CHAR_EQUALS = 0x3D /* = */ +const CHAR_GREATER_THAN = 0x3E /* > */ +const CHAR_QUESTION = 0x3F /* ? */ +const CHAR_COMMERCIAL_AT = 0x40 /* @ */ +const CHAR_LEFT_SQUARE_BRACKET = 0x5B /* [ */ +const CHAR_RIGHT_SQUARE_BRACKET = 0x5D /* ] */ +const CHAR_GRAVE_ACCENT = 0x60 /* ` */ +const CHAR_LEFT_CURLY_BRACKET = 0x7B /* { */ +const CHAR_VERTICAL_LINE = 0x7C /* | */ +const CHAR_RIGHT_CURLY_BRACKET = 0x7D /* } */ + +const ESCAPE_SEQUENCES = {} + +ESCAPE_SEQUENCES[0x00] = '\\0' +ESCAPE_SEQUENCES[0x07] = '\\a' +ESCAPE_SEQUENCES[0x08] = '\\b' +ESCAPE_SEQUENCES[0x09] = '\\t' +ESCAPE_SEQUENCES[0x0A] = '\\n' +ESCAPE_SEQUENCES[0x0B] = '\\v' +ESCAPE_SEQUENCES[0x0C] = '\\f' +ESCAPE_SEQUENCES[0x0D] = '\\r' +ESCAPE_SEQUENCES[0x1B] = '\\e' +ESCAPE_SEQUENCES[0x22] = '\\"' +ESCAPE_SEQUENCES[0x5C] = '\\\\' +ESCAPE_SEQUENCES[0x85] = '\\N' +ESCAPE_SEQUENCES[0xA0] = '\\_' +ESCAPE_SEQUENCES[0x2028] = '\\L' +ESCAPE_SEQUENCES[0x2029] = '\\P' + +const DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +] + +const DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/ + +function compileStyleMap (schema, map) { + if (map === null) return {} + + const result = {} + const keys = Object.keys(map) + + for (let index = 0, length = keys.length; index < length; index += 1) { + let tag = keys[index] + let style = String(map[tag]) + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2) + } + const type = schema.compiledTypeMap['fallback'][tag] + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style] + } + + result[tag] = style + } + + return result +} + +function encodeHex (character) { + let handle + let length + + const string = character.toString(16).toUpperCase() + + if (character <= 0xFF) { + handle = 'x' + length = 2 + } else if (character <= 0xFFFF) { + handle = 'u' + length = 4 + } else if (character <= 0xFFFFFFFF) { + handle = 'U' + length = 8 + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF') + } + + return '\\' + handle + common.repeat('0', length - string.length) + string +} + +const QUOTING_TYPE_SINGLE = 1 +const QUOTING_TYPE_DOUBLE = 2 + +function State (options) { + this.schema = options['schema'] || DEFAULT_SCHEMA + this.indent = Math.max(1, (options['indent'] || 2)) + this.noArrayIndent = options['noArrayIndent'] || false + this.skipInvalid = options['skipInvalid'] || false + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']) + this.styleMap = compileStyleMap(this.schema, options['styles'] || null) + this.sortKeys = options['sortKeys'] || false + this.lineWidth = options['lineWidth'] || 80 + this.noRefs = options['noRefs'] || false + this.noCompatMode = options['noCompatMode'] || false + this.condenseFlow = options['condenseFlow'] || false + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE + this.forceQuotes = options['forceQuotes'] || false + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null + + this.implicitTypes = this.schema.compiledImplicit + this.explicitTypes = this.schema.compiledExplicit + + this.tag = null + this.result = '' + + this.duplicates = [] + this.usedDuplicates = null +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString (string, spaces) { + const ind = common.repeat(' ', spaces) + let position = 0 + let result = '' + const length = string.length + + while (position < length) { + let line + const next = string.indexOf('\n', position) + if (next === -1) { + line = string.slice(position) + position = length + } else { + line = string.slice(position, next + 1) + position = next + 1 + } + + if (line.length && line !== '\n') result += ind + + result += line + } + + return result +} + +function generateNextLine (state, level) { + return '\n' + common.repeat(' ', state.indent * level) +} + +function testImplicitResolving (state, str) { + for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) { + const type = state.implicitTypes[index] + + if (type.resolve(str)) { + return true + } + } + + return false +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace (c) { + return c === CHAR_SPACE || c === CHAR_TAB +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable (c) { + return (c >= 0x00020 && c <= 0x00007E) || + ((c >= 0x000A1 && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) || + ((c >= 0x0E000 && c <= 0x00FFFD) && c !== CHAR_BOM) || + (c >= 0x10000 && c <= 0x10FFFF) +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace (c) { + return isPrintable(c) && + c !== CHAR_BOM && + // - b-char + c !== CHAR_CARRIAGE_RETURN && + c !== CHAR_LINE_FEED +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe (c, prev, inblock) { + const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c) + const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c) + return ( + ( + // ns-plain-safe + inblock // c = flow-in + ? cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace && + // - c-flow-indicator + c !== CHAR_COMMA && + c !== CHAR_LEFT_SQUARE_BRACKET && + c !== CHAR_RIGHT_SQUARE_BRACKET && + c !== CHAR_LEFT_CURLY_BRACKET && + c !== CHAR_RIGHT_CURLY_BRACKET + ) && + // ns-plain-char + c !== CHAR_SHARP && // false on '#' + !(prev === CHAR_COLON && !cIsNsChar) + ) || // false on ': ' + (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#' + (prev === CHAR_COLON && cIsNsChar) // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst (c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && + c !== CHAR_BOM && + !isWhitespace(c) && // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + c !== CHAR_MINUS && + c !== CHAR_QUESTION && + c !== CHAR_COLON && + c !== CHAR_COMMA && + c !== CHAR_LEFT_SQUARE_BRACKET && + c !== CHAR_RIGHT_SQUARE_BRACKET && + c !== CHAR_LEFT_CURLY_BRACKET && + c !== CHAR_RIGHT_CURLY_BRACKET && + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + c !== CHAR_SHARP && + c !== CHAR_AMPERSAND && + c !== CHAR_ASTERISK && + c !== CHAR_EXCLAMATION && + c !== CHAR_VERTICAL_LINE && + c !== CHAR_EQUALS && + c !== CHAR_GREATER_THAN && + c !== CHAR_SINGLE_QUOTE && + c !== CHAR_DOUBLE_QUOTE && + // | “%” | “@” | “`”) + c !== CHAR_PERCENT && + c !== CHAR_COMMERCIAL_AT && + c !== CHAR_GRAVE_ACCENT +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast (c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt (string, pos) { + const first = string.charCodeAt(pos) + let second + + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1) + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000 + } + } + return first +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator (string) { + const leadingSpaceRe = /^\n* / + return leadingSpaceRe.test(string) +} + +const STYLE_PLAIN = 1 +const STYLE_SINGLE = 2 +const STYLE_LITERAL = 3 +const STYLE_FOLDED = 4 +const STYLE_DOUBLE = 5 + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle (string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + let i + let char = 0 + let prevChar = null + let hasLineBreak = false + let hasFoldableLine = false // only checked if shouldTrackWidth + const shouldTrackWidth = lineWidth !== -1 + let previousLineBreak = -1 // count the first line correctly + let plain = isPlainSafeFirst(codePointAt(string, 0)) && + isPlainSafeLast(codePointAt(string, string.length - 1)) + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i) + if (!isPrintable(char)) { + return STYLE_DOUBLE + } + plain = plain && isPlainSafe(char, prevChar, inblock) + prevChar = char + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i) + if (char === CHAR_LINE_FEED) { + hasLineBreak = true + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ') + previousLineBreak = i + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE + } + plain = plain && isPlainSafe(char, prevChar, inblock) + prevChar = char + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')) + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar (state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''" + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'") + } + } + + const indent = state.indent * Math.max(1, level) // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + const lineWidth = (state.lineWidth === -1) + ? -1 + : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent) + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + const singleLineOnly = iskey || + // No block styles in flow mode. + (state.flowLevel > -1 && level >= state.flowLevel) + function testAmbiguity (string) { + return testImplicitResolving(state, string) + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + case STYLE_PLAIN: + return string + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'" + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)) + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)) + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"' + default: + throw new YAMLException('impossible error: invalid scalar style') + } + }()) +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader (string, indentPerLevel) { + const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '' + + // note the special case: the string '\n' counts as a "trailing" empty line. + const clip = string[string.length - 1] === '\n' + const keep = clip && (string[string.length - 2] === '\n' || string === '\n') + const chomp = keep ? '+' : (clip ? '' : '-') + + return indentIndicator + chomp + '\n' +} + +// (See the note for writeScalar.) +function dropEndingNewline (string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString (string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + const lineRe = /(\n+)([^\n]*)/g + + // first line (possibly an empty line) + let result = (function () { + let nextLF = string.indexOf('\n') + nextLF = nextLF !== -1 ? nextLF : string.length + lineRe.lastIndex = nextLF + return foldLine(string.slice(0, nextLF), width) + }()) + // If we haven't reached the first content line yet, don't add an extra \n. + let prevMoreIndented = string[0] === '\n' || string[0] === ' ' + let moreIndented + + // rest of the lines + let match + while ((match = lineRe.exec(string))) { + const prefix = match[1] + const line = match[2] + + moreIndented = (line[0] === ' ') + result += prefix + + ((!prevMoreIndented && !moreIndented && line !== '') ? '\n' : '') + + foldLine(line, width) + prevMoreIndented = moreIndented + } + + return result +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine (line, width) { + if (line === '' || line[0] === ' ') return line + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + const breakRe = / [^ ]/g // note: the match index will always be <= length-2. + let match + // start is an inclusive index. end, curr, and next are exclusive. + let start = 0 + let end + let curr = 0 + let next = 0 + let result = '' + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next // derive end <= length-2 + result += '\n' + line.slice(start, end) + // skip the space that was output as \n + start = end + 1 // derive start <= length-1 + } + curr = next + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n' + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1) + } else { + result += line.slice(start) + } + + return result.slice(1) // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString (string) { + let result = '' + let char = 0 + + for (let i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i) + const escapeSeq = ESCAPE_SEQUENCES[char] + + if (!escapeSeq && isPrintable(char)) { + result += string[i] + if (char >= 0x10000) result += string[i + 1] + } else { + result += escapeSeq || encodeHex(char) + } + } + + return result +} + +function writeFlowSequence (state, level, object) { + let _result = '' + const _tag = state.tag + + for (let index = 0, length = object.length; index < length; index += 1) { + let value = object[index] + + if (state.replacer) { + value = state.replacer.call(object, String(index), value) + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '') + _result += state.dump + } + } + + state.tag = _tag + state.dump = '[' + _result + ']' +} + +function writeBlockSequence (state, level, object, compact) { + let _result = '' + const _tag = state.tag + + for (let index = 0, length = object.length; index < length; index += 1) { + let value = object[index] + + if (state.replacer) { + value = state.replacer.call(object, String(index), value) + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + if (!compact || _result !== '') { + _result += generateNextLine(state, level) + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-' + } else { + _result += '- ' + } + + _result += state.dump + } + } + + state.tag = _tag + state.dump = _result || '[]' // Empty sequence if no valid values. +} + +function writeFlowMapping (state, level, object) { + let _result = '' + const _tag = state.tag + const objectKeyList = Object.keys(object) + + for (let index = 0, length = objectKeyList.length; index < length; index += 1) { + let pairBuffer = '' + if (_result !== '') pairBuffer += ', ' + + if (state.condenseFlow) pairBuffer += '"' + + const objectKey = objectKeyList[index] + let objectValue = object[objectKey] + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue) + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? ' + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ') + + if (!writeNode(state, level, objectValue, false, false)) { + continue // Skip this pair because of invalid value. + } + + pairBuffer += state.dump + + // Both key and value are valid. + _result += pairBuffer + } + + state.tag = _tag + state.dump = '{' + _result + '}' +} + +function writeBlockMapping (state, level, object, compact) { + let _result = '' + const _tag = state.tag + const objectKeyList = Object.keys(object) + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort() + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys) + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function') + } + + for (let index = 0, length = objectKeyList.length; index < length; index += 1) { + let pairBuffer = '' + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level) + } + + const objectKey = objectKeyList[index] + let objectValue = object[objectKey] + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue) + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue // Skip this pair because of invalid key. + } + + const explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024) + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?' + } else { + pairBuffer += '? ' + } + } + + pairBuffer += state.dump + + if (explicitPair) { + pairBuffer += generateNextLine(state, level) + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':' + } else { + pairBuffer += ': ' + } + + pairBuffer += state.dump + + // Both key and value are valid. + _result += pairBuffer + } + + state.tag = _tag + state.dump = _result || '{}' // Empty mapping if no valid pairs. +} + +function detectType (state, object, explicit) { + const typeList = explicit ? state.explicitTypes : state.implicitTypes + + for (let index = 0, length = typeList.length; index < length; index += 1) { + const type = typeList[index] + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object) + } else { + state.tag = type.tag + } + } else { + state.tag = '?' + } + + if (type.represent) { + const style = state.styleMap[type.tag] || type.defaultStyle + + let _result + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style) + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style) + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style') + } + + state.dump = _result + } + + return true + } + } + + return false +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode (state, level, object, block, compact, iskey, isblockseq) { + state.tag = null + state.dump = object + + if (!detectType(state, object, false)) { + detectType(state, object, true) + } + + const type = _toString.call(state.dump) + const inblock = block + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level) + } + + const objectOrArray = type === '[object Object]' || type === '[object Array]' + let duplicateIndex + let duplicate + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object) + duplicate = duplicateIndex !== -1 + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact) + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump + } + } else { + writeFlowMapping(state, level, state.dump) + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact) + } else { + writeBlockSequence(state, level, state.dump, compact) + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump + } + } else { + writeFlowSequence(state, level, state.dump) + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock) + } + } else if (type === '[object Undefined]') { + return false + } else { + if (state.skipInvalid) return false + throw new YAMLException('unacceptable kind of an object to dump ' + type) + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + let tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21') + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18) + } else { + tagStr = '!<' + tagStr + '>' + } + + state.dump = tagStr + ' ' + state.dump + } + } + + return true +} + +function getDuplicateReferences (object, state) { + const objects = [] + const duplicatesIndexes = [] + + inspectNode(object, objects, duplicatesIndexes) + + const length = duplicatesIndexes.length + for (let index = 0; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]) + } + state.usedDuplicates = new Array(length) +} + +function inspectNode (object, objects, duplicatesIndexes) { + if (object !== null && typeof object === 'object') { + const index = objects.indexOf(object) + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index) + } + } else { + objects.push(object) + + if (Array.isArray(object)) { + for (let i = 0, length = object.length; i < length; i += 1) { + inspectNode(object[i], objects, duplicatesIndexes) + } + } else { + const objectKeyList = Object.keys(object) + + for (let i = 0, length = objectKeyList.length; i < length; i += 1) { + inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes) + } + } + } + } +} + +function dump (input, options) { + options = options || {} + + const state = new State(options) + + if (!state.noRefs) getDuplicateReferences(input, state) + + let value = input + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value) + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n' + + return '' +} + +module.exports.dump = dump + + +/***/ }), + +/***/ 248: +/***/ ((module) => { + +// YAML error class. http://stackoverflow.com/questions/8458984 +// + + +function formatError (exception, compact) { + let where = '' + const message = exception.reason || '(unknown reason)' + + if (!exception.mark) return message + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" ' + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')' + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet + } + + return message + ' ' + where +} + +function YAMLException (reason, mark) { + // Super constructor + Error.call(this) + + this.name = 'YAMLException' + this.reason = reason + this.mark = mark + this.message = formatError(this, false) + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor) + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || '' + } +} + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype) +YAMLException.prototype.constructor = YAMLException + +YAMLException.prototype.toString = function toString (compact) { + return this.name + ': ' + formatError(this, compact) +} + +module.exports = YAMLException + + +/***/ }), + +/***/ 950: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const common = __nccwpck_require__(816) +const YAMLException = __nccwpck_require__(248) +const makeSnippet = __nccwpck_require__(440) +const DEFAULT_SCHEMA = __nccwpck_require__(336) + +const _hasOwnProperty = Object.prototype.hasOwnProperty + +const CONTEXT_FLOW_IN = 1 +const CONTEXT_FLOW_OUT = 2 +const CONTEXT_BLOCK_IN = 3 +const CONTEXT_BLOCK_OUT = 4 + +const CHOMPING_CLIP = 1 +const CHOMPING_STRIP = 2 +const CHOMPING_KEEP = 3 + +// eslint-disable-next-line no-control-regex +const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/ +const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/ +// eslint-disable-next-line no-useless-escape +const PATTERN_FLOW_INDICATORS = /[,\[\]{}]/ +// eslint-disable-next-line no-useless-escape +const PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/ +// eslint-disable-next-line no-useless-escape +const PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i + +function _class (obj) { return Object.prototype.toString.call(obj) } + +function isEol (c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */) +} + +function isWhiteSpace (c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */) +} + +function isWsOrEol (c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */) +} + +function isFlowIndicator (c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */ +} + +function fromHexCode (c) { + if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) { + return c - 0x30 + } + + const lc = c | 0x20 + + if ((lc >= 0x61/* a */) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10 + } + + return -1 +} + +function escapedHexLen (c) { + if (c === 0x78/* x */) { return 2 } + if (c === 0x75/* u */) { return 4 } + if (c === 0x55/* U */) { return 8 } + return 0 +} + +function fromDecimalCode (c) { + if ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) { + return c - 0x30 + } + + return -1 +} + +function simpleEscapeSequence (c) { + switch (c) { + case 0x30/* 0 */: return '\x00' + case 0x61/* a */: return '\x07' + case 0x62/* b */: return '\x08' + case 0x74/* t */: return '\x09' + case 0x09/* Tab */: return '\x09' + case 0x6E/* n */: return '\x0A' + case 0x76/* v */: return '\x0B' + case 0x66/* f */: return '\x0C' + case 0x72/* r */: return '\x0D' + case 0x65/* e */: return '\x1B' + case 0x20/* Space */: return ' ' + case 0x22/* " */: return '\x22' + case 0x2F/* / */: return '/' + case 0x5C/* \ */: return '\x5C' + case 0x4E/* N */: return '\x85' + case 0x5F/* _ */: return '\xA0' + case 0x4C/* L */: return '\u2028' + case 0x50/* P */: return '\u2029' + default: return '' + } +} + +function charFromCodepoint (c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c) + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ) +} + +// set a property of a literal object, while protecting against prototype pollution, +// see https://github.com/nodeca/js-yaml/issues/164 for more details +function setProperty (object, key, value) { + // used for this specific key only because Object.defineProperty is slow + if (key === '__proto__') { + Object.defineProperty(object, key, { + configurable: true, + enumerable: true, + writable: true, + value: value + }) + } else { + object[key] = value + } +} + +const simpleEscapeCheck = new Array(256) // integer, for fast access +const simpleEscapeMap = new Array(256) +for (let i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0 + simpleEscapeMap[i] = simpleEscapeSequence(i) +} + +function State (input, options) { + this.input = input + + this.filename = options['filename'] || null + this.schema = options['schema'] || DEFAULT_SCHEMA + this.onWarning = options['onWarning'] || null + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false + + this.json = options['json'] || false + this.listener = options['listener'] || null + this.maxDepth = typeof options['maxDepth'] === 'number' ? options['maxDepth'] : 100 + this.maxTotalMergeKeys = typeof options['maxTotalMergeKeys'] === 'number' ? options['maxTotalMergeKeys'] : 10000 + + this.implicitTypes = this.schema.compiledImplicit + this.typeMap = this.schema.compiledTypeMap + + this.length = input.length + this.position = 0 + this.line = 0 + this.lineStart = 0 + this.lineIndent = 0 + this.depth = 0 + this.totalMergeKeys = 0 + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1 + + this.documents = [] + this.anchorMapTransactions = [] + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result; */ +} + +function generateError (state, message) { + const mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + } + + mark.snippet = makeSnippet(mark) + + return new YAMLException(message, mark) +} + +function throwError (state, message) { + throw generateError(state, message) +} + +function throwWarning (state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)) + } +} + +function storeAnchor (state, name, value) { + const transactions = state.anchorMapTransactions + + if (transactions.length !== 0) { + const transaction = transactions[transactions.length - 1] + + if (!_hasOwnProperty.call(transaction, name)) { + transaction[name] = { + existed: _hasOwnProperty.call(state.anchorMap, name), + value: state.anchorMap[name] + } + } + } + + state.anchorMap[name] = value +} + +function beginAnchorTransaction (state) { + state.anchorMapTransactions.push(Object.create(null)) +} + +function commitAnchorTransaction (state) { + const transaction = state.anchorMapTransactions.pop() + const transactions = state.anchorMapTransactions + + if (transactions.length === 0) return + + const parent = transactions[transactions.length - 1] + const names = Object.keys(transaction) + + for (let index = 0, length = names.length; index < length; index += 1) { + const name = names[index] + + if (!_hasOwnProperty.call(parent, name)) { + parent[name] = transaction[name] + } + } +} + +function rollbackAnchorTransaction (state) { + const transaction = state.anchorMapTransactions.pop() + const names = Object.keys(transaction) + + for (let index = names.length - 1; index >= 0; index -= 1) { + const entry = transaction[names[index]] + + if (entry.existed) { + state.anchorMap[names[index]] = entry.value + } else { + delete state.anchorMap[names[index]] + } + } +} + +function snapshotState (state) { + return { + position: state.position, + line: state.line, + lineStart: state.lineStart, + lineIndent: state.lineIndent, + firstTabInLine: state.firstTabInLine, + tag: state.tag, + anchor: state.anchor, + kind: state.kind, + result: state.result + } +} + +function restoreState (state, snapshot) { + state.position = snapshot.position + state.line = snapshot.line + state.lineStart = snapshot.lineStart + state.lineIndent = snapshot.lineIndent + state.firstTabInLine = snapshot.firstTabInLine + state.tag = snapshot.tag + state.anchor = snapshot.anchor + state.kind = snapshot.kind + state.result = snapshot.result +} + +const directiveHandlers = { + + YAML: function handleYamlDirective (state, name, args) { + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive') + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument') + } + + const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]) + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive') + } + + const major = parseInt(match[1], 10) + const minor = parseInt(match[2], 10) + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document') + } + + state.version = args[0] + state.checkLineBreaks = (minor < 2) + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document') + } + }, + + TAG: function handleTagDirective (state, name, args) { + let prefix + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments') + } + + const handle = args[0] + prefix = args[1] + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive') + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle') + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive') + } + + try { + prefix = decodeURIComponent(prefix) + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix) + } + + state.tagMap[handle] = prefix + } +} + +function captureSegment (state, start, end, checkJson) { + if (start < end) { + const _result = state.input.slice(start, end) + + if (checkJson) { + for (let _position = 0, _length = _result.length; _position < _length; _position += 1) { + const _character = _result.charCodeAt(_position) + if (!(_character === 0x09 || + (_character >= 0x20 && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character') + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters') + } + + state.result += _result + } +} + +function mergeMappings (state, destination, source, overridableKeys) { + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable') + } + + const sourceKeys = Object.keys(source) + + for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + const key = sourceKeys[index] + + if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) { + throwError(state, 'merge keys exceeded maxTotalMergeKeys (' + state.maxTotalMergeKeys + ')') + } + + if (!_hasOwnProperty.call(destination, key)) { + setProperty(destination, key, source[key]) + overridableKeys[key] = true + } + } +} + +function storeMappingPair (state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode) + + for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys') + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]' + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]' + } + + keyNode = String(keyNode) + + if (_result === null) { + _result = {} + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys) + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys) + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line + state.lineStart = startLineStart || state.lineStart + state.position = startPos || state.position + throwError(state, 'duplicated mapping key') + } + + setProperty(_result, keyNode, valueNode) + delete overridableKeys[keyNode] + } + + return _result +} + +function readLineBreak (state) { + const ch = state.input.charCodeAt(state.position) + + if (ch === 0x0A/* LF */) { + state.position++ + } else if (ch === 0x0D/* CR */) { + state.position++ + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++ + } + } else { + throwError(state, 'a line break is expected') + } + + state.line += 1 + state.lineStart = state.position + state.firstTabInLine = -1 +} + +function skipSeparationSpace (state, allowComments, checkIndent) { + let lineBreaks = 0 + let ch = state.input.charCodeAt(state.position) + + while (ch !== 0) { + while (isWhiteSpace(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position + } + ch = state.input.charCodeAt(++state.position) + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position) + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0) + } + + if (isEol(ch)) { + readLineBreak(state) + + ch = state.input.charCodeAt(state.position) + lineBreaks++ + state.lineIndent = 0 + + while (ch === 0x20/* Space */) { + state.lineIndent++ + ch = state.input.charCodeAt(++state.position) + } + } else { + break + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation') + } + + return lineBreaks +} + +function testDocumentSeparator (state) { + let _position = state.position + let ch = state.input.charCodeAt(_position) + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + _position += 3 + + ch = state.input.charCodeAt(_position) + + if (ch === 0 || isWsOrEol(ch)) { + return true + } + } + + return false +} + +function writeFoldedLines (state, count) { + if (count === 1) { + state.result += ' ' + } else if (count > 1) { + state.result += common.repeat('\n', count - 1) + } +} + +function readPlainScalar (state, nodeIndent, withinFlowCollection) { + let captureStart + let captureEnd + let hasPendingContent + let _line + let _lineStart + let _lineIndent + const _kind = state.kind + const _result = state.result + + let ch = state.input.charCodeAt(state.position) + + if (isWsOrEol(ch) || + isFlowIndicator(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + const following = state.input.charCodeAt(state.position + 1) + + if (isWsOrEol(following) || + (withinFlowCollection && isFlowIndicator(following))) { + return false + } + } + + state.kind = 'scalar' + state.result = '' + captureStart = captureEnd = state.position + hasPendingContent = false + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + const following = state.input.charCodeAt(state.position + 1) + + if (isWsOrEol(following) || + (withinFlowCollection && isFlowIndicator(following))) { + break + } + } else if (ch === 0x23/* # */) { + const preceding = state.input.charCodeAt(state.position - 1) + + if (isWsOrEol(preceding)) { + break + } + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + (withinFlowCollection && isFlowIndicator(ch))) { + break + } else if (isEol(ch)) { + _line = state.line + _lineStart = state.lineStart + _lineIndent = state.lineIndent + skipSeparationSpace(state, false, -1) + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true + ch = state.input.charCodeAt(state.position) + continue + } else { + state.position = captureEnd + state.line = _line + state.lineStart = _lineStart + state.lineIndent = _lineIndent + break + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false) + writeFoldedLines(state, state.line - _line) + captureStart = captureEnd = state.position + hasPendingContent = false + } + + if (!isWhiteSpace(ch)) { + captureEnd = state.position + 1 + } + + ch = state.input.charCodeAt(++state.position) + } + + captureSegment(state, captureStart, captureEnd, false) + + if (state.result) { + return true + } + + state.kind = _kind + state.result = _result + return false +} + +function readSingleQuotedScalar (state, nodeIndent) { + let captureStart + let captureEnd + + let ch = state.input.charCodeAt(state.position) + + if (ch !== 0x27/* ' */) { + return false + } + + state.kind = 'scalar' + state.result = '' + state.position++ + captureStart = captureEnd = state.position + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true) + ch = state.input.charCodeAt(++state.position) + + if (ch === 0x27/* ' */) { + captureStart = state.position + state.position++ + captureEnd = state.position + } else { + return true + } + } else if (isEol(ch)) { + captureSegment(state, captureStart, captureEnd, true) + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)) + captureStart = captureEnd = state.position + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar') + } else { + state.position++ + if (!isWhiteSpace(ch)) { + captureEnd = state.position + } + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar') +} + +function readDoubleQuotedScalar (state, nodeIndent) { + let captureStart + let captureEnd + let tmp + + let ch = state.input.charCodeAt(state.position) + + if (ch !== 0x22/* " */) { + return false + } + + state.kind = 'scalar' + state.result = '' + state.position++ + captureStart = captureEnd = state.position + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true) + state.position++ + return true + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true) + ch = state.input.charCodeAt(++state.position) + + if (isEol(ch)) { + skipSeparationSpace(state, false, nodeIndent) + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch] + state.position++ + } else if ((tmp = escapedHexLen(ch)) > 0) { + let hexLength = tmp + let hexResult = 0 + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position) + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp + } else { + throwError(state, 'expected hexadecimal character') + } + } + + state.result += charFromCodepoint(hexResult) + + state.position++ + } else { + throwError(state, 'unknown escape sequence') + } + + captureStart = captureEnd = state.position + } else if (isEol(ch)) { + captureSegment(state, captureStart, captureEnd, true) + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)) + captureStart = captureEnd = state.position + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar') + } else { + state.position++ + if (!isWhiteSpace(ch)) { + captureEnd = state.position + } + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar') +} + +function readFlowCollection (state, nodeIndent) { + let readNext = true + let _line + let _lineStart + let _pos + const _tag = state.tag + let _result + const _anchor = state.anchor + let terminator + let isPair + let isExplicitPair + let isMapping + const overridableKeys = Object.create(null) + let keyNode + let keyTag + let valueNode + + let ch = state.input.charCodeAt(state.position) + + if (ch === 0x5B/* [ */) { + terminator = 0x5D/* ] */ + isMapping = false + _result = [] + } else if (ch === 0x7B/* { */) { + terminator = 0x7D/* } */ + isMapping = true + _result = {} + } else { + return false + } + + if (state.anchor !== null) { + storeAnchor(state, state.anchor, _result) + } + + ch = state.input.charCodeAt(++state.position) + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent) + + ch = state.input.charCodeAt(state.position) + + if (ch === terminator) { + state.position++ + state.tag = _tag + state.anchor = _anchor + state.kind = isMapping ? 'mapping' : 'sequence' + state.result = _result + return true + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries') + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','") + } + + keyTag = keyNode = valueNode = null + isPair = isExplicitPair = false + + if (ch === 0x3F/* ? */) { + const following = state.input.charCodeAt(state.position + 1) + + if (isWsOrEol(following)) { + isPair = isExplicitPair = true + state.position++ + skipSeparationSpace(state, true, nodeIndent) + } + } + + _line = state.line // Save the current line. + _lineStart = state.lineStart + _pos = state.position + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true) + keyTag = state.tag + keyNode = state.result + skipSeparationSpace(state, true, nodeIndent) + + ch = state.input.charCodeAt(state.position) + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true + ch = state.input.charCodeAt(++state.position) + skipSeparationSpace(state, true, nodeIndent) + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true) + valueNode = state.result + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos) + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)) + } else { + _result.push(keyNode) + } + + skipSeparationSpace(state, true, nodeIndent) + + ch = state.input.charCodeAt(state.position) + + if (ch === 0x2C/* , */) { + readNext = true + ch = state.input.charCodeAt(++state.position) + } else { + readNext = false + } + } + + throwError(state, 'unexpected end of the stream within a flow collection') +} + +function readBlockScalar (state, nodeIndent) { + let folding + let chomping = CHOMPING_CLIP + let didReadContent = false + let detectedIndent = false + let textIndent = nodeIndent + let emptyLines = 0 + let atMoreIndented = false + let tmp + + let ch = state.input.charCodeAt(state.position) + + if (ch === 0x7C/* | */) { + folding = false + } else if (ch === 0x3E/* > */) { + folding = true + } else { + return false + } + + state.kind = 'scalar' + state.result = '' + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position) + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP + } else { + throwError(state, 'repeat of a chomping mode identifier') + } + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one') + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1 + detectedIndent = true + } else { + throwError(state, 'repeat of an indentation width identifier') + } + } else { + break + } + } + + if (isWhiteSpace(ch)) { + do { ch = state.input.charCodeAt(++state.position) } + while (isWhiteSpace(ch)) + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position) } + while (!isEol(ch) && (ch !== 0)) + } + } + + while (ch !== 0) { + readLineBreak(state) + state.lineIndent = 0 + + ch = state.input.charCodeAt(state.position) + + // eslint-disable-next-line no-unmodified-loop-condition + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++ + ch = state.input.charCodeAt(++state.position) + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent + } + + if (isEol(ch)) { + emptyLines++ + continue + } + + if (!detectedIndent && textIndent === 0) { + throwError(state, 'missing indentation for block scalar') + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines) + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n' + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + // Lines starting with white space characters (more-indented lines) are not folded. + if (isWhiteSpace(ch)) { + atMoreIndented = true + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines) + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false + state.result += common.repeat('\n', emptyLines + 1) + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' ' + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines) + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines) + } + + didReadContent = true + detectedIndent = true + emptyLines = 0 + const captureStart = state.position + + while (!isEol(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position) + } + + captureSegment(state, captureStart, state.position, false) + } + + return true +} + +function readBlockSequence (state, nodeIndent) { + const _tag = state.tag + const _anchor = state.anchor + const _result = [] + let detected = false + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false + + if (state.anchor !== null) { + storeAnchor(state, state.anchor, _result) + } + + let ch = state.input.charCodeAt(state.position) + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine + throwError(state, 'tab characters must not be used in indentation') + } + + if (ch !== 0x2D/* - */) { + break + } + + const following = state.input.charCodeAt(state.position + 1) + + if (!isWsOrEol(following)) { + break + } + + detected = true + state.position++ + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null) + ch = state.input.charCodeAt(state.position) + continue + } + } + + const _line = state.line + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true) + _result.push(state.result) + skipSeparationSpace(state, true, -1) + + ch = state.input.charCodeAt(state.position) + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry') + } else if (state.lineIndent < nodeIndent) { + break + } + } + + if (detected) { + state.tag = _tag + state.anchor = _anchor + state.kind = 'sequence' + state.result = _result + return true + } + return false +} + +function readBlockMapping (state, nodeIndent, flowIndent) { + let allowCompact + let _keyLine + let _keyLineStart + let _keyPos + const _tag = state.tag + const _anchor = state.anchor + const _result = {} + const overridableKeys = Object.create(null) + let keyTag = null + let keyNode = null + let valueNode = null + let atExplicitKey = false + let detected = false + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false + + if (state.anchor !== null) { + storeAnchor(state, state.anchor, _result) + } + + let ch = state.input.charCodeAt(state.position) + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine + throwError(state, 'tab characters must not be used in indentation') + } + + const following = state.input.charCodeAt(state.position + 1) + const _line = state.line // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && isWsOrEol(following)) { + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos) + keyTag = keyNode = valueNode = null + } + + detected = true + atExplicitKey = true + allowCompact = true + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false + allowCompact = true + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line') + } + + state.position += 1 + ch = following + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line + _keyLineStart = state.lineStart + _keyPos = state.position + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position) + + while (isWhiteSpace(ch)) { + ch = state.input.charCodeAt(++state.position) + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position) + + if (!isWsOrEol(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping') + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos) + keyTag = keyNode = valueNode = null + } + + detected = true + atExplicitKey = false + allowCompact = false + keyTag = state.tag + keyNode = state.result + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed') + } else { + state.tag = _tag + state.anchor = _anchor + return true // Keep the result of `composeNode`. + } + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key') + } else { + state.tag = _tag + state.anchor = _anchor + return true // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line + _keyLineStart = state.lineStart + _keyPos = state.position + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result + } else { + valueNode = state.result + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos) + keyTag = keyNode = valueNode = null + } + + skipSeparationSpace(state, true, -1) + ch = state.input.charCodeAt(state.position) + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry') + } else if (state.lineIndent < nodeIndent) { + break + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos) + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag + state.anchor = _anchor + state.kind = 'mapping' + state.result = _result + } + + return detected +} + +function readTagProperty (state) { + let isVerbatim = false + let isNamed = false + let tagHandle + let tagName + + let ch = state.input.charCodeAt(state.position) + + if (ch !== 0x21/* ! */) return false + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property') + } + + ch = state.input.charCodeAt(++state.position) + + if (ch === 0x3C/* < */) { + isVerbatim = true + ch = state.input.charCodeAt(++state.position) + } else if (ch === 0x21/* ! */) { + isNamed = true + tagHandle = '!!' + ch = state.input.charCodeAt(++state.position) + } else { + tagHandle = '!' + } + + let _position = state.position + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position) } + while (ch !== 0 && ch !== 0x3E/* > */) + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position) + ch = state.input.charCodeAt(++state.position) + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag') + } + } else { + while (ch !== 0 && !isWsOrEol(ch)) { + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1) + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters') + } + + isNamed = true + _position = state.position + 1 + } else { + throwError(state, 'tag suffix cannot contain exclamation marks') + } + } + + ch = state.input.charCodeAt(++state.position) + } + + tagName = state.input.slice(_position, state.position) + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters') + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName) + } + + try { + tagName = decodeURIComponent(tagName) + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName) + } + + if (isVerbatim) { + state.tag = tagName + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName + } else if (tagHandle === '!') { + state.tag = '!' + tagName + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"') + } + + return true +} + +function readAnchorProperty (state) { + let ch = state.input.charCodeAt(state.position) + + if (ch !== 0x26/* & */) return false + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property') + } + + ch = state.input.charCodeAt(++state.position) + const _position = state.position + + while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) { + ch = state.input.charCodeAt(++state.position) + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character') + } + + state.anchor = state.input.slice(_position, state.position) + return true +} + +function readAlias (state) { + let ch = state.input.charCodeAt(state.position) + + if (ch !== 0x2A/* * */) return false + + ch = state.input.charCodeAt(++state.position) + const _position = state.position + + while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) { + ch = state.input.charCodeAt(++state.position) + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character') + } + + const alias = state.input.slice(_position, state.position) + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"') + } + + state.result = state.anchorMap[alias] + skipSeparationSpace(state, true, -1) + return true +} + +function tryReadBlockMappingFromProperty (state, propertyStart, nodeIndent, flowIndent) { + const fallbackState = snapshotState(state) + + beginAnchorTransaction(state) + restoreState(state, propertyStart) + + // Re-read the leading properties as part of the first implicit key, not as + // properties of the current node. + state.tag = null + state.anchor = null + state.kind = null + state.result = null + + if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === 'mapping') { + commitAnchorTransaction(state) + return true + } + + rollbackAnchorTransaction(state) + restoreState(state, fallbackState) + return false +} + +function composeNode (state, parentIndent, nodeContext, allowToSeek, allowCompact) { + let allowBlockScalars + let allowBlockCollections + let indentStatus = 1 // 1: this>parent, 0: this=parent, -1: this= state.maxDepth) { + throwError(state, 'nesting exceeded maxDepth (' + state.maxDepth + ')') + } + + state.depth += 1 + + if (state.listener !== null) { + state.listener('open', state) + } + + state.tag = null + state.anchor = null + state.kind = null + state.result = null + + const allowBlockStyles = allowBlockScalars = allowBlockCollections = + CONTEXT_BLOCK_OUT === nodeContext || + CONTEXT_BLOCK_IN === nodeContext + + if (allowToSeek) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true + + if (state.lineIndent > parentIndent) { + indentStatus = 1 + } else if (state.lineIndent === parentIndent) { + indentStatus = 0 + } else if (state.lineIndent < parentIndent) { + indentStatus = -1 + } + } + } + + if (indentStatus === 1) { + while (true) { + const ch = state.input.charCodeAt(state.position) + const propertyState = snapshotState(state) + + // A duplicate property token after a line break can be the first key of + // a nested block mapping, e.g. `!!map\n !!str key: value`. + if (atNewLine && + ((ch === 0x21/* ! */ && state.tag !== null) || + (ch === 0x26/* & */ && state.anchor !== null))) { + break + } + + if (!readTagProperty(state) && !readAnchorProperty(state)) { + break + } + + if (propertyStart === null) { + propertyStart = propertyState + } + + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true + allowBlockCollections = allowBlockStyles + + if (state.lineIndent > parentIndent) { + indentStatus = 1 + } else if (state.lineIndent === parentIndent) { + indentStatus = 0 + } else if (state.lineIndent < parentIndent) { + indentStatus = -1 + } + } else { + allowBlockCollections = false + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent + } else { + flowIndent = parentIndent + 1 + } + + blockIndent = state.position - state.lineStart + + if (indentStatus === 1) { + if ((allowBlockCollections && + (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent))) || + readFlowCollection(state, flowIndent)) { + hasContent = true + } else { + const ch = state.input.charCodeAt(state.position) + + if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && + ch !== 0x7C/* | */ && ch !== 0x3E/* > */ && + tryReadBlockMappingFromProperty( + state, + propertyStart, + propertyStart.position - propertyStart.lineStart, + flowIndent + )) { + hasContent = true + } else if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true + } else if (readAlias(state)) { + hasContent = true + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties') + } + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true + + if (state.tag === null) { + state.tag = '?' + } + } + + if (state.anchor !== null) { + storeAnchor(state, state.anchor, state.result) + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent) + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + storeAnchor(state, state.anchor, state.result) + } + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"') + } + + for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex] + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result) + state.tag = type.tag + if (state.anchor !== null) { + storeAnchor(state, state.anchor, state.result) + } + break + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag] + } else { + // looking for multi type + type = null + const typeList = state.typeMap.multi[state.kind || 'fallback'] + + for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex] + break + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>') + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"') + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag') + } else { + state.result = type.construct(state.result, state.tag) + if (state.anchor !== null) { + storeAnchor(state, state.anchor, state.result) + } + } + } + + if (state.listener !== null) { + state.listener('close', state) + } + + state.depth -= 1 + return state.tag !== null || state.anchor !== null || hasContent +} + +function readDocument (state) { + const documentStart = state.position + let hasDirectives = false + let ch + + state.version = null + state.checkLineBreaks = state.legacy + state.tagMap = Object.create(null) + state.anchorMap = Object.create(null) + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1) + + ch = state.input.charCodeAt(state.position) + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break + } + + hasDirectives = true + ch = state.input.charCodeAt(++state.position) + let _position = state.position + + while (ch !== 0 && !isWsOrEol(ch)) { + ch = state.input.charCodeAt(++state.position) + } + + const directiveName = state.input.slice(_position, state.position) + const directiveArgs = [] + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length') + } + + while (ch !== 0) { + while (isWhiteSpace(ch)) { + ch = state.input.charCodeAt(++state.position) + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position) } + while (ch !== 0 && !isEol(ch)) + break + } + + if (isEol(ch)) break + + _position = state.position + + while (ch !== 0 && !isWsOrEol(ch)) { + ch = state.input.charCodeAt(++state.position) + } + + directiveArgs.push(state.input.slice(_position, state.position)) + } + + if (ch !== 0) readLineBreak(state) + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs) + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"') + } + } + + skipSeparationSpace(state, true, -1) + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3 + skipSeparationSpace(state, true, -1) + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected') + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true) + skipSeparationSpace(state, true, -1) + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content') + } + + state.documents.push(state.result) + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3 + skipSeparationSpace(state, true, -1) + } + return + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected') + } +} + +function loadDocuments (input, options) { + input = String(input) + options = options || {} + + if (input.length !== 0) { + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n' + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1) + } + } + + const state = new State(input, options) + + const nullpos = input.indexOf('\0') + + if (nullpos !== -1) { + state.position = nullpos + throwError(state, 'null byte is not allowed in input') + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0' + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1 + state.position += 1 + } + + while (state.position < (state.length - 1)) { + readDocument(state) + } + + return state.documents +} + +function loadAll (input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator + iterator = null + } + + const documents = loadDocuments(input, options) + + if (typeof iterator !== 'function') { + return documents + } + + for (let index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]) + } +} + +function load (input, options) { + const documents = loadDocuments(input, options) + + if (documents.length === 0) { + return undefined + } else if (documents.length === 1) { + return documents[0] + } + throw new YAMLException('expected a single document in the stream, but found more') +} + +module.exports.loadAll = loadAll +module.exports.load = load + + +/***/ }), + +/***/ 46: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const YAMLException = __nccwpck_require__(248) +const Type = __nccwpck_require__(557) + +function compileList (schema, name) { + const result = [] + + schema[name].forEach(function (currentType) { + let newIndex = result.length + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + newIndex = previousIndex + } + }) + + result[newIndex] = currentType + }) + + return result +} + +function compileMap (/* lists... */) { + const result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + } + function collectType (type) { + if (type.multi) { + result.multi[type.kind].push(type) + result.multi['fallback'].push(type) + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type + } + } + + for (let index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType) + } + return result +} + +function Schema (definition) { + return this.extend(definition) +} + +Schema.prototype.extend = function extend (definition) { + let implicit = [] + let explicit = [] + + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition) + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition) + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit) + if (definition.explicit) explicit = explicit.concat(definition.explicit) + } else { + throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })') + } + + implicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.') + } + + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.') + } + + if (type.multi) { + throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.') + } + }) + + explicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.') + } + }) + + const result = Object.create(Schema.prototype) + + result.implicit = (this.implicit || []).concat(implicit) + result.explicit = (this.explicit || []).concat(explicit) + + result.compiledImplicit = compileList(result, 'implicit') + result.compiledExplicit = compileList(result, 'explicit') + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit) + + return result +} + +module.exports = Schema + + +/***/ }), + +/***/ 746: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + + +module.exports = __nccwpck_require__(927) + + +/***/ }), + +/***/ 336: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + + +module.exports = (__nccwpck_require__(746).extend)({ + implicit: [ + __nccwpck_require__(966), + __nccwpck_require__(854) + ], + explicit: [ + __nccwpck_require__(149), + __nccwpck_require__(649), + __nccwpck_require__(267), + __nccwpck_require__(758) + ] +}) + + +/***/ }), + +/***/ 832: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + + +const Schema = __nccwpck_require__(46) + +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(929), + __nccwpck_require__(161), + __nccwpck_require__(316) + ] +}) + + +/***/ }), + +/***/ 927: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + + +module.exports = (__nccwpck_require__(832).extend)({ + implicit: [ + __nccwpck_require__(333), + __nccwpck_require__(296), + __nccwpck_require__(271), + __nccwpck_require__(584) + ] +}) + + +/***/ }), + +/***/ 440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const common = __nccwpck_require__(816) + +// get snippet for a single line, respecting maxLength +function getLine (buffer, lineStart, lineEnd, position, maxLineLength) { + let head = '' + let tail = '' + const maxHalfLength = Math.floor(maxLineLength / 2) - 1 + + if (position - lineStart > maxHalfLength) { + head = ' ... ' + lineStart = position - maxHalfLength + head.length + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...' + lineEnd = position + maxHalfLength - tail.length + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + } +} + +function padStart (string, max) { + return common.repeat(' ', max - string.length) + string +} + +function makeSnippet (mark, options) { + options = Object.create(options || null) + + if (!mark.buffer) return null + + if (!options.maxLength) options.maxLength = 79 + if (typeof options.indent !== 'number') options.indent = 1 + if (typeof options.linesBefore !== 'number') options.linesBefore = 3 + if (typeof options.linesAfter !== 'number') options.linesAfter = 2 + + const re = /\r?\n|\r|\0/g + const lineStarts = [0] + const lineEnds = [] + let match + let foundLineNo = -1 + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index) + lineStarts.push(match.index + match[0].length) + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2 + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1 + + let result = '' + const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length + const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3) + + for (let i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break + const line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ) + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result + } + + const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength) + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n' + + for (let i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break + const line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ) + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + } + + return result.replace(/\n$/, '') +} + +module.exports = makeSnippet + + +/***/ }), + +/***/ 557: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const YAMLException = __nccwpck_require__(248) + +const TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +] + +const YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +] + +function compileStyleAliases (map) { + const result = {} + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style + }) + }) + } + + return result +} + +function Type (tag, options) { + options = options || {} + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.') + } + }) + + // TODO: Add tag format check. + this.options = options // keep original options in case user wants to extend this type later + this.tag = tag + this.kind = options['kind'] || null + this.resolve = options['resolve'] || function () { return true } + this.construct = options['construct'] || function (data) { return data } + this.instanceOf = options['instanceOf'] || null + this.predicate = options['predicate'] || null + this.represent = options['represent'] || null + this.representName = options['representName'] || null + this.defaultStyle = options['defaultStyle'] || null + this.multi = options['multi'] || false + this.styleAliases = compileStyleAliases(options['styleAliases'] || null) + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.') + } +} + +module.exports = Type + + +/***/ }), + +/***/ 149: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +const BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r' + +function resolveYamlBinary (data) { + if (data === null) return false + + let bitlen = 0 + const max = data.length + const map = BASE64_MAP + + // Convert one by one. + for (let idx = 0; idx < max; idx++) { + const code = map.indexOf(data.charAt(idx)) + + // Skip CR/LF + if (code > 64) continue + + // Fail on illegal characters + if (code < 0) return false + + bitlen += 6 + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0 +} + +function constructYamlBinary (data) { + const input = data.replace(/[\r\n=]/g, '') // remove CR/LF & padding to simplify scan + const max = input.length + const map = BASE64_MAP + let bits = 0 + const result = [] + + // Collect by 6*4 bits (3 bytes) + + for (let idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF) + result.push((bits >> 8) & 0xFF) + result.push(bits & 0xFF) + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)) + } + + // Dump tail + + const tailbits = (max % 4) * 6 + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF) + result.push((bits >> 8) & 0xFF) + result.push(bits & 0xFF) + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF) + result.push((bits >> 2) & 0xFF) + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF) + } + + return new Uint8Array(result) +} + +function representYamlBinary (object /*, style */) { + let result = '' + let bits = 0 + const max = object.length + const map = BASE64_MAP + + // Convert every three bytes to 4 ASCII characters. + + for (let idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F] + result += map[(bits >> 12) & 0x3F] + result += map[(bits >> 6) & 0x3F] + result += map[bits & 0x3F] + } + + bits = (bits << 8) + object[idx] + } + + // Dump tail + + const tail = max % 3 + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F] + result += map[(bits >> 12) & 0x3F] + result += map[(bits >> 6) & 0x3F] + result += map[bits & 0x3F] + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F] + result += map[(bits >> 4) & 0x3F] + result += map[(bits << 2) & 0x3F] + result += map[64] + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F] + result += map[(bits << 4) & 0x3F] + result += map[64] + result += map[64] + } + + return result +} + +function isBinary (obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]' +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}) + + +/***/ }), + +/***/ 296: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +function resolveYamlBoolean (data) { + if (data === null) return false + + const max = data.length + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')) +} + +function constructYamlBoolean (data) { + return data === 'true' || + data === 'True' || + data === 'TRUE' +} + +function isBoolean (object) { + return Object.prototype.toString.call(object) === '[object Boolean]' +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false' }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE' }, + camelcase: function (object) { return object ? 'True' : 'False' } + }, + defaultStyle: 'lowercase' +}) + + +/***/ }), + +/***/ 584: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const common = __nccwpck_require__(816) +const Type = __nccwpck_require__(557) + +const YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$') + +const YAML_FLOAT_SPECIAL_PATTERN = new RegExp( + '^(?:' + + // .inf + '[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$') + +function resolveYamlFloat (data) { + if (data === null) return false + + if (!YAML_FLOAT_PATTERN.test(data)) { + return false + } + + if (isFinite(parseFloat(data, 10))) { + return true + } + + return YAML_FLOAT_SPECIAL_PATTERN.test(data) +} + +function constructYamlFloat (data) { + let value = data.toLowerCase() + const sign = value[0] === '-' ? -1 : 1 + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1) + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY + } else if (value === '.nan') { + return NaN + } + return sign * parseFloat(value, 10) +} + +const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/ + +function representYamlFloat (object, style) { + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan' + case 'uppercase': return '.NAN' + case 'camelcase': return '.NaN' + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf' + case 'uppercase': return '.INF' + case 'camelcase': return '.Inf' + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf' + case 'uppercase': return '-.INF' + case 'camelcase': return '-.Inf' + } + } else if (common.isNegativeZero(object)) { + return '-0.0' + } + + const res = object.toString(10) + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res +} + +function isFloat (object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)) +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}) + + +/***/ }), + +/***/ 271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const common = __nccwpck_require__(816) +const Type = __nccwpck_require__(557) + +function isHexCode (c) { + return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) || + ((c >= 0x41/* A */) && (c <= 0x46/* F */)) || + ((c >= 0x61/* a */) && (c <= 0x66/* f */)) +} + +function isOctCode (c) { + return ((c >= 0x30/* 0 */) && (c <= 0x37/* 7 */)) +} + +function isDecCode (c) { + return ((c >= 0x30/* 0 */) && (c <= 0x39/* 9 */)) +} + +function resolveYamlInteger (data) { + if (data === null) return false + + const max = data.length + let index = 0 + let hasDigits = false + + if (!max) return false + + let ch = data[index] + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index] + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true + ch = data[++index] + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++ + + for (; index < max; index++) { + ch = data[index] + if (ch !== '0' && ch !== '1') return false + hasDigits = true + } + return hasDigits && isFinite(parseYamlInteger(data)) + } + + if (ch === 'x') { + // base 16 + index++ + + for (; index < max; index++) { + if (!isHexCode(data.charCodeAt(index))) return false + hasDigits = true + } + return hasDigits && isFinite(parseYamlInteger(data)) + } + + if (ch === 'o') { + // base 8 + index++ + + for (; index < max; index++) { + if (!isOctCode(data.charCodeAt(index))) return false + hasDigits = true + } + return hasDigits && isFinite(parseYamlInteger(data)) + } + } + + // base 10 (except 0) + + for (; index < max; index++) { + if (!isDecCode(data.charCodeAt(index))) { + return false + } + hasDigits = true + } + + if (!hasDigits) return false + + return isFinite(parseYamlInteger(data)) +} + +function parseYamlInteger (data) { + let value = data + let sign = 1 + + let ch = value[0] + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1 + value = value.slice(1) + ch = value[0] + } + + if (value === '0') return 0 + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2) + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16) + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8) + } + + return sign * parseInt(value, 10) +} + +function constructYamlInteger (data) { + return parseYamlInteger(data) +} + +function isInteger (object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)) +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1) }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1) }, + decimal: function (obj) { return obj.toString(10) }, + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1) } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [2, 'bin'], + octal: [8, 'oct'], + decimal: [10, 'dec'], + hexadecimal: [16, 'hex'] + } +}) + + +/***/ }), + +/***/ 316: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {} } +}) + + +/***/ }), + +/***/ 854: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +function resolveYamlMerge (data) { + return data === '<<' || data === null +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}) + + +/***/ }), + +/***/ 333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +function resolveYamlNull (data) { + if (data === null) return true + + const max = data.length + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')) +} + +function constructYamlNull () { + return null +} + +function isNull (object) { + return object === null +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~' }, + lowercase: function () { return 'null' }, + uppercase: function () { return 'NULL' }, + camelcase: function () { return 'Null' }, + empty: function () { return '' } + }, + defaultStyle: 'lowercase' +}) + + +/***/ }), + +/***/ 649: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +const _hasOwnProperty = Object.prototype.hasOwnProperty +const _toString = Object.prototype.toString + +function resolveYamlOmap (data) { + if (data === null) return true + + const objectKeys = [] + const object = data + + for (let index = 0, length = object.length; index < length; index += 1) { + const pair = object[index] + let pairHasKey = false + + if (_toString.call(pair) !== '[object Object]') return false + + let pairKey + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true + else return false + } + } + + if (!pairHasKey) return false + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey) + else return false + } + + return true +} + +function constructYamlOmap (data) { + return data !== null ? data : [] +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}) + + +/***/ }), + +/***/ 267: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +const _toString = Object.prototype.toString + +function resolveYamlPairs (data) { + if (data === null) return true + + const object = data + + const result = new Array(object.length) + + for (let index = 0, length = object.length; index < length; index += 1) { + const pair = object[index] + + if (_toString.call(pair) !== '[object Object]') return false + + const keys = Object.keys(pair) + + if (keys.length !== 1) return false + + result[index] = [keys[0], pair[keys[0]]] + } + + return true +} + +function constructYamlPairs (data) { + if (data === null) return [] + + const object = data + const result = new Array(object.length) + + for (let index = 0, length = object.length; index < length; index += 1) { + const pair = object[index] + + const keys = Object.keys(pair) + + result[index] = [keys[0], pair[keys[0]]] + } + + return result +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}) + + +/***/ }), + +/***/ 161: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : [] } +}) + + +/***/ }), + +/***/ 758: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +const _hasOwnProperty = Object.prototype.hasOwnProperty + +function resolveYamlSet (data) { + if (data === null) return true + + const object = data + + for (const key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false + } + } + + return true +} + +function constructYamlSet (data) { + return data !== null ? data : {} +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}) + + +/***/ }), + +/***/ 929: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : '' } +}) + + +/***/ }), + +/***/ 966: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Type = __nccwpck_require__(557) + +const YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$') // [3] day + +const YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tzHour + '(?::([0-9][0-9]))?))?$') // [11] tzMinute + +function resolveYamlTimestamp (data) { + if (data === null) return false + if (YAML_DATE_REGEXP.exec(data) !== null) return true + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true + return false +} + +function constructYamlTimestamp (data) { + let fraction = 0 + let delta = null + + let match = YAML_DATE_REGEXP.exec(data) + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data) + + if (match === null) throw new Error('Date resolve error') + + // match: [1] year [2] month [3] day + + const year = +(match[1]) + const month = +(match[2]) - 1 // JS month starts with 0 + const day = +(match[3]) + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)) + } + + // match: [4] hour [5] minute [6] second [7] fraction + + const hour = +(match[4]) + const minute = +(match[5]) + const second = +(match[6]) + + if (match[7]) { + fraction = match[7].slice(0, 3) + while (fraction.length < 3) { // milli-seconds + fraction += '0' + } + fraction = +fraction + } + + // match: [8] tz [9] tz_sign [10] tzHour [11] tzMinute + + if (match[9]) { + const tzHour = +(match[10]) + const tzMinute = +(match[11] || 0) + delta = (tzHour * 60 + tzMinute) * 60000 // delta in mili-seconds + if (match[9] === '-') delta = -delta + } + + const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)) + + if (delta) date.setTime(date.getTime() - delta) + + return date +} + +function representYamlTimestamp (object /*, style */) { + return object.toISOString() +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}) + + +/***/ }), + +/***/ 896: +/***/ ((module) => { + +module.exports = require("fs"); + +/***/ }), + +/***/ 474: +/***/ ((module) => { + +module.exports = require("node:events"); + +/***/ }), + +/***/ 24: +/***/ ((module) => { + +module.exports = require("node:fs"); + +/***/ }), + +/***/ 455: +/***/ ((module) => { + +module.exports = require("node:fs/promises"); + +/***/ }), + +/***/ 760: +/***/ ((module) => { + +module.exports = require("node:path"); + +/***/ }), + +/***/ 75: +/***/ ((module) => { + +module.exports = require("node:stream"); + +/***/ }), + +/***/ 193: +/***/ ((module) => { + +module.exports = require("node:string_decoder"); + +/***/ }), + +/***/ 136: +/***/ ((module) => { + +module.exports = require("node:url"); + +/***/ }), + +/***/ 928: +/***/ ((module) => { + +module.exports = require("path"); + +/***/ }), + +/***/ 941: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var R=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var Ge=R(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.range=Y.balanced=void 0;var Gs=(n,t,e)=>{let s=n instanceof RegExp?Ie(n,e):n,i=t instanceof RegExp?Ie(t,e):t,r=s!==null&&i!=null&&(0,Y.range)(s,i,e);return r&&{start:r[0],end:r[1],pre:e.slice(0,r[0]),body:e.slice(r[0]+s.length,r[1]),post:e.slice(r[1]+i.length)}};Y.balanced=Gs;var Ie=(n,t)=>{let e=t.match(n);return e?e[0]:null},zs=(n,t,e)=>{let s,i,r,h,o,a=e.indexOf(n),l=e.indexOf(t,a+1),f=a;if(a>=0&&l>0){if(n===t)return[a,l];for(s=[],r=e.length;f>=0&&!o;){if(f===a)s.push(f),a=e.indexOf(n,f+1);else if(s.length===1){let c=s.pop();c!==void 0&&(o=[c,l])}else i=s.pop(),i!==void 0&&i=0?a:l}s.length&&h!==void 0&&(o=[r,h])}return o};Y.range=zs});var Ke=R(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.EXPANSION_MAX=void 0;it.expand=ei;var ze=Ge(),Ue="\0SLASH"+Math.random()+"\0",$e="\0OPEN"+Math.random()+"\0",ue="\0CLOSE"+Math.random()+"\0",qe="\0COMMA"+Math.random()+"\0",He="\0PERIOD"+Math.random()+"\0",Us=new RegExp(Ue,"g"),$s=new RegExp($e,"g"),qs=new RegExp(ue,"g"),Hs=new RegExp(qe,"g"),Vs=new RegExp(He,"g"),Ks=/\\\\/g,Xs=/\\{/g,Ys=/\\}/g,Js=/\\,/g,Zs=/\\./g;it.EXPANSION_MAX=1e5;function ce(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function Qs(n){return n.replace(Ks,Ue).replace(Xs,$e).replace(Ys,ue).replace(Js,qe).replace(Zs,He)}function ti(n){return n.replace(Us,"\\").replace($s,"{").replace(qs,"}").replace(Hs,",").replace(Vs,".")}function Ve(n){if(!n)return[""];let t=[],e=(0,ze.balanced)("{","}",n);if(!e)return n.split(",");let{pre:s,body:i,post:r}=e,h=s.split(",");h[h.length-1]+="{"+i+"}";let o=Ve(r);return r.length&&(h[h.length-1]+=o.shift(),h.push.apply(h,o)),t.push.apply(t,h),t}function ei(n,t={}){if(!n)return[];let{max:e=it.EXPANSION_MAX}=t;return n.slice(0,2)==="{}"&&(n="\\{\\}"+n.slice(2)),ht(Qs(n),e,!0).map(ti)}function si(n){return"{"+n+"}"}function ii(n){return/^-?0\d/.test(n)}function ri(n,t){return n<=t}function ni(n,t){return n>=t}function ht(n,t,e){let s=[],i=(0,ze.balanced)("{","}",n);if(!i)return[n];let r=i.pre,h=i.post.length?ht(i.post,t,!1):[""];if(/\$$/.test(i.pre))for(let o=0;o=0;if(!l&&!f)return i.post.match(/,(?!,).*\}/)?(n=i.pre+"{"+i.body+ue+i.post,ht(n,t,!0)):[n];let c;if(l)c=i.body.split(/\.\./);else if(c=Ve(i.body),c.length===1&&c[0]!==void 0&&(c=ht(c[0],t,!1).map(si),c.length===1))return h.map(u=>i.pre+c[0]+u);let d;if(l&&c[0]!==void 0&&c[1]!==void 0){let u=ce(c[0]),m=ce(c[1]),p=Math.max(c[0].length,c[1].length),b=c.length===3&&c[2]!==void 0?Math.abs(ce(c[2])):1,w=ri;m0){let U=new Array(B+1).join("0");y<0?S="-"+U+S.slice(1):S=U+S}}d.push(S)}}else{d=[];for(let u=0;u{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.assertValidPattern=void 0;var hi=1024*64,oi=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>hi)throw new TypeError("pattern is too long")};Ct.assertValidPattern=oi});var Je=R(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.parseClass=void 0;var ai={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ot=n=>n.replace(/[[\]\\-]/g,"\\$&"),li=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Ye=n=>n.join(""),ci=(n,t)=>{let e=t;if(n.charAt(e)!=="[")throw new Error("not in a brace expression");let s=[],i=[],r=e+1,h=!1,o=!1,a=!1,l=!1,f=e,c="";t:for(;rc?s.push(ot(c)+"-"+ot(p)):p===c&&s.push(ot(p)),c="",r++;continue}if(n.startsWith("-]",r+1)){s.push(ot(p+"-")),r+=2;continue}if(n.startsWith("-",r+1)){c=p,r+=2;continue}s.push(ot(p)),r++}if(f{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.unescape=void 0;var ui=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!0}={})=>e?t?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):t?n.replace(/\[([^\/\\{}])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");At.unescape=ui});var pe=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.AST=void 0;var fi=Je(),Mt=kt(),di=new Set(["!","?","+","*","@"]),Ze=n=>di.has(n),pi="(?!(?:^|/)\\.\\.?(?:$|/))",Pt="(?!\\.)",mi=new Set(["[","."]),gi=new Set(["..","."]),wi=new Set("().*{}+?[]^$\\!"),bi=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),de="[^/]",Qe=de+"*?",ts=de+"+?",fe=class n{type;#t;#s;#n=!1;#r=[];#h;#S;#w;#c=!1;#o;#f;#u=!1;constructor(t,e,s={}){this.type=t,t&&(this.#s=!0),this.#h=e,this.#t=this.#h?this.#h.#t:this,this.#o=this.#t===this?s:this.#t.#o,this.#w=this.#t===this?[]:this.#t.#w,t==="!"&&!this.#t.#c&&this.#w.push(this),this.#S=this.#h?this.#h.#r.length:0}get hasMagic(){if(this.#s!==void 0)return this.#s;for(let t of this.#r)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#s=!0;return this.#s}toString(){return this.#f!==void 0?this.#f:this.type?this.#f=this.type+"("+this.#r.map(t=>String(t)).join("|")+")":this.#f=this.#r.map(t=>String(t)).join("")}#a(){if(this!==this.#t)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#w.pop();){if(t.type!=="!")continue;let e=t,s=e.#h;for(;s;){for(let i=e.#S+1;!s.type&&itypeof e=="string"?e:e.toJSON()):[this.type,...this.#r.map(e=>e.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#t||this.#t.#c&&this.#h?.type==="!")&&t.push({}),t}isStart(){if(this.#t===this)return!0;if(!this.#h?.isStart())return!1;if(this.#S===0)return!0;let t=this.#h;for(let e=0;etypeof u!="string"),l=this.#r.map(u=>{let[m,p,b,w]=typeof u=="string"?n.#v(u,this.#s,a):u.toRegExpSource(t);return this.#s=this.#s||b,this.#n=this.#n||w,m}).join(""),f="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&gi.has(this.#r[0]))){let m=mi,p=e&&m.has(l.charAt(0))||l.startsWith("\\.")&&m.has(l.charAt(2))||l.startsWith("\\.\\.")&&m.has(l.charAt(4)),b=!e&&!t&&m.has(l.charAt(0));f=p?pi:b?Pt:""}let c="";return this.isEnd()&&this.#t.#c&&this.#h?.type==="!"&&(c="(?:$|\\/)"),[f+l+c,(0,Mt.unescape)(l),this.#s=!!this.#s,this.#n]}let s=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",r=this.#d(e);if(this.isStart()&&this.isEnd()&&!r&&this.type!=="!"){let a=this.toString();return this.#r=[a],this.type=null,this.#s=void 0,[a,(0,Mt.unescape)(this.toString()),!1,!1]}let h=!s||t||e||!Pt?"":this.#d(!0);h===r&&(h=""),h&&(r=`(?:${r})(?:${h})*?`);let o="";if(this.type==="!"&&this.#u)o=(this.isStart()&&!e?Pt:"")+ts;else{let a=this.type==="!"?"))"+(this.isStart()&&!e&&!t?Pt:"")+Qe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&h?")":this.type==="*"&&h?")?":`)${this.type}`;o=i+r+a}return[o,(0,Mt.unescape)(r),this.#s=!!this.#s,this.#n]}#d(t){return this.#r.map(e=>{if(typeof e=="string")throw new Error("string type in extglob ast??");let[s,i,r,h]=e.toRegExpSource(t);return this.#n=this.#n||h,s}).filter(e=>!(this.isStart()&&this.isEnd())||!!e).join("|")}static#v(t,e,s=!1){let i=!1,r="",h=!1,o=!1;for(let a=0;a{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.escape=void 0;var yi=(n,{windowsPathsNoEscape:t=!1,magicalBraces:e=!1}={})=>e?t?n.replace(/[?*()[\]{}]/g,"[$&]"):n.replace(/[?*()[\]\\{}]/g,"\\$&"):t?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");Ft.escape=yi});var H=R(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.unescape=g.escape=g.AST=g.Minimatch=g.match=g.makeRe=g.braceExpand=g.defaults=g.filter=g.GLOBSTAR=g.sep=g.minimatch=void 0;var Si=Ke(),jt=Xe(),is=pe(),vi=me(),Ei=kt(),_i=(n,t,e={})=>((0,jt.assertValidPattern)(t),!e.nocomment&&t.charAt(0)==="#"?!1:new J(t,e).match(n));g.minimatch=_i;var Oi=/^\*+([^+@!?\*\[\(]*)$/,xi=n=>t=>!t.startsWith(".")&&t.endsWith(n),Ti=n=>t=>t.endsWith(n),Ci=n=>(n=n.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(n)),Ri=n=>(n=n.toLowerCase(),t=>t.toLowerCase().endsWith(n)),Ai=/^\*+\.\*+$/,ki=n=>!n.startsWith(".")&&n.includes("."),Mi=n=>n!=="."&&n!==".."&&n.includes("."),Pi=/^\.\*+$/,Di=n=>n!=="."&&n!==".."&&n.startsWith("."),Fi=/^\*+$/,ji=n=>n.length!==0&&!n.startsWith("."),Ni=n=>n.length!==0&&n!=="."&&n!=="..",Li=/^\?+([^+@!?\*\[\(]*)?$/,Wi=([n,t=""])=>{let e=rs([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Bi=([n,t=""])=>{let e=ns([n]);return t?(t=t.toLowerCase(),s=>e(s)&&s.toLowerCase().endsWith(t)):e},Ii=([n,t=""])=>{let e=ns([n]);return t?s=>e(s)&&s.endsWith(t):e},Gi=([n,t=""])=>{let e=rs([n]);return t?s=>e(s)&&s.endsWith(t):e},rs=([n])=>{let t=n.length;return e=>e.length===t&&!e.startsWith(".")},ns=([n])=>{let t=n.length;return e=>e.length===t&&e!=="."&&e!==".."},hs=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",es={win32:{sep:"\\"},posix:{sep:"/"}};g.sep=hs==="win32"?es.win32.sep:es.posix.sep;g.minimatch.sep=g.sep;g.GLOBSTAR=Symbol("globstar **");g.minimatch.GLOBSTAR=g.GLOBSTAR;var zi="[^/]",Ui=zi+"*?",$i="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",qi="(?:(?!(?:\\/|^)\\.).)*?",Hi=(n,t={})=>e=>(0,g.minimatch)(e,n,t);g.filter=Hi;g.minimatch.filter=g.filter;var F=(n,t={})=>Object.assign({},n,t),Vi=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return g.minimatch;let t=g.minimatch;return Object.assign((s,i,r={})=>t(s,i,F(n,r)),{Minimatch:class extends t.Minimatch{constructor(i,r={}){super(i,F(n,r))}static defaults(i){return t.defaults(F(n,i)).Minimatch}},AST:class extends t.AST{constructor(i,r,h={}){super(i,r,F(n,h))}static fromGlob(i,r={}){return t.AST.fromGlob(i,F(n,r))}},unescape:(s,i={})=>t.unescape(s,F(n,i)),escape:(s,i={})=>t.escape(s,F(n,i)),filter:(s,i={})=>t.filter(s,F(n,i)),defaults:s=>t.defaults(F(n,s)),makeRe:(s,i={})=>t.makeRe(s,F(n,i)),braceExpand:(s,i={})=>t.braceExpand(s,F(n,i)),match:(s,i,r={})=>t.match(s,i,F(n,r)),sep:t.sep,GLOBSTAR:g.GLOBSTAR})};g.defaults=Vi;g.minimatch.defaults=g.defaults;var Ki=(n,t={})=>((0,jt.assertValidPattern)(n),t.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,Si.expand)(n,{max:t.braceExpandMax}));g.braceExpand=Ki;g.minimatch.braceExpand=g.braceExpand;var Xi=(n,t={})=>new J(n,t).makeRe();g.makeRe=Xi;g.minimatch.makeRe=g.makeRe;var Yi=(n,t,e={})=>{let s=new J(t,e);return n=n.filter(i=>s.match(i)),s.options.nonull&&!n.length&&n.push(t),n};g.match=Yi;g.minimatch.match=g.match;var ss=/[?*]|[+@!]\(.*?\)|\[|\]/,Ji=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),J=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(t,e={}){(0,jt.assertValidPattern)(t),e=e||{},this.options=e,this.pattern=t,this.platform=e.platform||hs,this.isWindows=this.platform==="win32";let s="allowWindowsEscape";this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e[s]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!e.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!e.nonegate,this.comment=!1,this.empty=!1,this.partial=!!e.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=e.windowsNoMagicRoot!==void 0?e.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let e of t)if(typeof e!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,e=this.options;if(!e.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],e.debug&&(this.debug=(...r)=>console.error(...r)),this.debug(this.pattern,this.globSet);let s=this.globSet.map(r=>this.slashSplit(r));this.globParts=this.preprocess(s),this.debug(this.pattern,this.globParts);let i=this.globParts.map((r,h,o)=>{if(this.isWindows&&this.windowsNoMagicRoot){let a=r[0]===""&&r[1]===""&&(r[2]==="?"||!ss.test(r[2]))&&!ss.test(r[3]),l=/^[a-z]:/i.test(r[0]);if(a)return[...r.slice(0,4),...r.slice(4).map(f=>this.parse(f))];if(l)return[r[0],...r.slice(1).map(f=>this.parse(f))]}return r.map(a=>this.parse(a))});if(this.debug(this.pattern,i),this.set=i.filter(r=>r.indexOf(!1)===-1),this.isWindows)for(let r=0;r=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):e>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(e=>{let s=-1;for(;(s=e.indexOf("**",s+1))!==-1;){let i=s;for(;e[i+1]==="**";)i++;i!==s&&e.splice(s,i-s)}return e})}levelOneOptimize(t){return t.map(e=>(e=e.reduce((s,i)=>{let r=s[s.length-1];return i==="**"&&r==="**"?s:i===".."&&r&&r!==".."&&r!=="."&&r!=="**"?(s.pop(),s):(s.push(i),s)},[]),e.length===0?[""]:e))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let e=!1;do{if(e=!1,!this.preserveMultipleSlashes){for(let i=1;ii&&s.splice(i+1,h-i);let o=s[i+1],a=s[i+2],l=s[i+3];if(o!==".."||!a||a==="."||a===".."||!l||l==="."||l==="..")continue;e=!0,s.splice(i,1);let f=s.slice(0);f[i]="**",t.push(f),i--}if(!this.preserveMultipleSlashes){for(let h=1;he.length)}partsMatch(t,e,s=!1){let i=0,r=0,h=[],o="";for(;iE?e=e.slice(y):E>y&&(t=t.slice(E)))}}let{optimizationLevel:r=1}=this.options;r>=2&&(t=this.levelTwoFileOptimize(t)),this.debug("matchOne",this,{file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var h=0,o=0,a=t.length,l=e.length;h>> no match, partial?`,t,d,e,u),d===a))}let p;if(typeof f=="string"?(p=c===f,this.debug("string match",f,c,p)):(p=f.test(c),this.debug("pattern match",f,c,p)),!p)return!1}if(h===a&&o===l)return!0;if(h===a)return s;if(o===l)return h===a-1&&t[h]==="";throw new Error("wtf?")}braceExpand(){return(0,g.braceExpand)(this.pattern,this.options)}parse(t){(0,jt.assertValidPattern)(t);let e=this.options;if(t==="**")return g.GLOBSTAR;if(t==="")return"";let s,i=null;(s=t.match(Fi))?i=e.dot?Ni:ji:(s=t.match(Oi))?i=(e.nocase?e.dot?Ri:Ci:e.dot?Ti:xi)(s[1]):(s=t.match(Li))?i=(e.nocase?e.dot?Bi:Wi:e.dot?Ii:Gi)(s):(s=t.match(Ai))?i=e.dot?Mi:ki:(s=t.match(Pi))&&(i=Di);let r=is.AST.fromGlob(t,this.options).toMMPattern();return i&&typeof r=="object"&&Reflect.defineProperty(r,"test",{value:i}),r}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let e=this.options,s=e.noglobstar?Ui:e.dot?$i:qi,i=new Set(e.nocase?["i"]:[]),r=t.map(a=>{let l=a.map(c=>{if(c instanceof RegExp)for(let d of c.flags.split(""))i.add(d);return typeof c=="string"?Ji(c):c===g.GLOBSTAR?g.GLOBSTAR:c._src});l.forEach((c,d)=>{let u=l[d+1],m=l[d-1];c!==g.GLOBSTAR||m===g.GLOBSTAR||(m===void 0?u!==void 0&&u!==g.GLOBSTAR?l[d+1]="(?:\\/|"+s+"\\/)?"+u:l[d]=s:u===void 0?l[d-1]=m+"(?:\\/|\\/"+s+")?":u!==g.GLOBSTAR&&(l[d-1]=m+"(?:\\/|\\/"+s+"\\/)"+u,l[d+1]=g.GLOBSTAR))});let f=l.filter(c=>c!==g.GLOBSTAR);if(this.partial&&f.length>=1){let c=[];for(let d=1;d<=f.length;d++)c.push(f.slice(0,d).join("/"));return"(?:"+c.join("|")+")"}return f.join("/")}).join("|"),[h,o]=t.length>1?["(?:",")"]:["",""];r="^"+h+r+o+"$",this.partial&&(r="^(?:\\/|"+h+r.slice(1,-1)+o+")$"),this.negate&&(r="^(?!"+r+").+$");try{this.regexp=new RegExp(r,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,e=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&e)return!0;let s=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let r=this.set;this.debug(this.pattern,"set",r);let h=i[i.length-1];if(!h)for(let o=i.length-2;!h&&o>=0;o--)h=i[o];for(let o=0;o{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.LRUCache=void 0;var er=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,as=new Set,ge=typeof process=="object"&&process?process:{},ls=(n,t,e,s)=>{typeof ge.emitWarning=="function"?ge.emitWarning(n,t,e,s):console.error(`[${e}] ${t}: ${n}`)},Lt=globalThis.AbortController,os=globalThis.AbortSignal;if(typeof Lt>"u"){os=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,s){this._onabort.push(s)}},Lt=class{constructor(){t()}signal=new os;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(let s of this.signal._onabort)s(e);this.signal.onabort?.(e)}}};let n=ge.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{n&&(n=!1,ls("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}var sr=n=>!as.has(n),V=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),cs=n=>V(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Nt:null:null,Nt=class extends Array{constructor(n){super(n),this.fill(0)}},ir=class at{heap;length;static#t=!1;static create(t){let e=cs(t);if(!e)return[];at.#t=!0;let s=new at(t,e);return at.#t=!1,s}constructor(t,e){if(!at.#t)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0}push(t){this.heap[this.length++]=t}pop(){return this.heap[--this.length]}},rr=class us{#t;#s;#n;#r;#h;#S;#w;#c;get perf(){return this.#c}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#o;#f;#u;#a;#i;#d;#v;#y;#p;#R;#m;#O;#x;#g;#b;#E;#T;#e;#F;static unsafeExposeInternals(t){return{starts:t.#x,ttls:t.#g,autopurgeTimers:t.#b,sizes:t.#O,keyMap:t.#u,keyList:t.#a,valList:t.#i,next:t.#d,prev:t.#v,get head(){return t.#y},get tail(){return t.#p},free:t.#R,isBackgroundFetch:e=>t.#l(e),backgroundFetch:(e,s,i,r)=>t.#z(e,s,i,r),moveToTail:e=>t.#N(e),indexes:e=>t.#k(e),rindexes:e=>t.#M(e),isStale:e=>t.#_(e)}}get max(){return this.#t}get maxSize(){return this.#s}get calculatedSize(){return this.#f}get size(){return this.#o}get fetchMethod(){return this.#S}get memoMethod(){return this.#w}get dispose(){return this.#n}get onInsert(){return this.#r}get disposeAfter(){return this.#h}constructor(t){let{max:e=0,ttl:s,ttlResolution:i=1,ttlAutopurge:r,updateAgeOnGet:h,updateAgeOnHas:o,allowStale:a,dispose:l,onInsert:f,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:u,maxSize:m=0,maxEntrySize:p=0,sizeCalculation:b,fetchMethod:w,memoMethod:v,noDeleteOnFetchRejection:E,noDeleteOnStaleGet:y,allowStaleOnFetchRejection:S,allowStaleOnFetchAbort:B,ignoreFetchAbort:U,perf:et}=t;if(et!==void 0&&typeof et?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#c=et??er,e!==0&&!V(e))throw new TypeError("max option must be a nonnegative integer");let st=e?cs(e):Array;if(!st)throw new Error("invalid max value: "+e);if(this.#t=e,this.#s=m,this.maxEntrySize=p||this.#s,this.sizeCalculation=b,this.sizeCalculation){if(!this.#s&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(v!==void 0&&typeof v!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=v,w!==void 0&&typeof w!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#S=w,this.#T=!!w,this.#u=new Map,this.#a=new Array(e).fill(void 0),this.#i=new Array(e).fill(void 0),this.#d=new st(e),this.#v=new st(e),this.#y=0,this.#p=0,this.#R=ir.create(e),this.#o=0,this.#f=0,typeof l=="function"&&(this.#n=l),typeof f=="function"&&(this.#r=f),typeof c=="function"?(this.#h=c,this.#m=[]):(this.#h=void 0,this.#m=void 0),this.#E=!!this.#n,this.#F=!!this.#r,this.#e=!!this.#h,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!E,this.allowStaleOnFetchRejection=!!S,this.allowStaleOnFetchAbort=!!B,this.ignoreFetchAbort=!!U,this.maxEntrySize!==0){if(this.#s!==0&&!V(this.#s))throw new TypeError("maxSize must be a positive integer if specified");if(!V(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#$()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!y,this.updateAgeOnGet=!!h,this.updateAgeOnHas=!!o,this.ttlResolution=V(i)||i===0?i:1,this.ttlAutopurge=!!r,this.ttl=s||0,this.ttl){if(!V(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#t===0&&this.ttl===0&&this.#s===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#s){let le="LRU_CACHE_UNBOUNDED";sr(le)&&(as.add(le),ls("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",le,us))}}getRemainingTTL(t){return this.#u.has(t)?1/0:0}#P(){let t=new Nt(this.#t),e=new Nt(this.#t);this.#g=t,this.#x=e;let s=this.ttlAutopurge?new Array(this.#t):void 0;this.#b=s,this.#W=(h,o,a=this.#c.now())=>{if(e[h]=o!==0?a:0,t[h]=o,s?.[h]&&(clearTimeout(s[h]),s[h]=void 0),o!==0&&s){let l=setTimeout(()=>{this.#_(h)&&this.#A(this.#a[h],"expire")},o+1);l.unref&&l.unref(),s[h]=l}},this.#C=h=>{e[h]=t[h]!==0?this.#c.now():0},this.#D=(h,o)=>{if(t[o]){let a=t[o],l=e[o];if(!a||!l)return;h.ttl=a,h.start=l,h.now=i||r();let f=h.now-l;h.remainingTTL=a-f}};let i=0,r=()=>{let h=this.#c.now();if(this.ttlResolution>0){i=h;let o=setTimeout(()=>i=0,this.ttlResolution);o.unref&&o.unref()}return h};this.getRemainingTTL=h=>{let o=this.#u.get(h);if(o===void 0)return 0;let a=t[o],l=e[o];if(!a||!l)return 1/0;let f=(i||r())-l;return a-f},this.#_=h=>{let o=e[h],a=t[h];return!!a&&!!o&&(i||r())-o>a}}#C=()=>{};#D=()=>{};#W=()=>{};#_=()=>!1;#$(){let t=new Nt(this.#t);this.#f=0,this.#O=t,this.#L=e=>{this.#f-=t[e],t[e]=0},this.#B=(e,s,i,r)=>{if(this.#l(s))return 0;if(!V(i))if(r){if(typeof r!="function")throw new TypeError("sizeCalculation must be a function");if(i=r(s,e),!V(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#j=(e,s,i)=>{if(t[e]=s,this.#s){let r=this.#s-t[e];for(;this.#f>r;)this.#G(!0)}this.#f+=t[e],i&&(i.entrySize=s,i.totalCalculatedSize=this.#f)}}#L=t=>{};#j=(t,e,s)=>{};#B=(t,e,s,i)=>{if(s||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#k({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#p;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#y));)e=this.#v[e]}*#M({allowStale:t=this.allowStale}={}){if(this.#o)for(let e=this.#y;!(!this.#I(e)||((t||!this.#_(e))&&(yield e),e===this.#p));)e=this.#d[e]}#I(t){return t!==void 0&&this.#u.get(this.#a[t])===t}*entries(){for(let t of this.#k())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*rentries(){for(let t of this.#M())this.#i[t]!==void 0&&this.#a[t]!==void 0&&!this.#l(this.#i[t])&&(yield[this.#a[t],this.#i[t]])}*keys(){for(let t of this.#k()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*rkeys(){for(let t of this.#M()){let e=this.#a[t];e!==void 0&&!this.#l(this.#i[t])&&(yield e)}}*values(){for(let t of this.#k())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}*rvalues(){for(let t of this.#M())this.#i[t]!==void 0&&!this.#l(this.#i[t])&&(yield this.#i[t])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;if(r!==void 0&&t(r,this.#a[s],this))return this.get(this.#a[s],e)}}forEach(t,e=this){for(let s of this.#k()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}rforEach(t,e=this){for(let s of this.#M()){let i=this.#i[s],r=this.#l(i)?i.__staleWhileFetching:i;r!==void 0&&t.call(e,r,this.#a[s],this)}}purgeStale(){let t=!1;for(let e of this.#M({allowStale:!0}))this.#_(e)&&(this.#A(this.#a[e],"expire"),t=!0);return t}info(t){let e=this.#u.get(t);if(e===void 0)return;let s=this.#i[e],i=this.#l(s)?s.__staleWhileFetching:s;if(i===void 0)return;let r={value:i};if(this.#g&&this.#x){let h=this.#g[e],o=this.#x[e];if(h&&o){let a=h-(this.#c.now()-o);r.ttl=a,r.start=Date.now()}}return this.#O&&(r.size=this.#O[e]),r}dump(){let t=[];for(let e of this.#k({allowStale:!0})){let s=this.#a[e],i=this.#i[e],r=this.#l(i)?i.__staleWhileFetching:i;if(r===void 0||s===void 0)continue;let h={value:r};if(this.#g&&this.#x){h.ttl=this.#g[e];let o=this.#c.now()-this.#x[e];h.start=Math.floor(Date.now()-o)}this.#O&&(h.size=this.#O[e]),t.unshift([s,h])}return t}load(t){this.clear();for(let[e,s]of t){if(s.start){let i=Date.now()-s.start;s.start=this.#c.now()-i}this.set(e,s.value,s)}}set(t,e,s={}){if(e===void 0)return this.delete(t),this;let{ttl:i=this.ttl,start:r,noDisposeOnSet:h=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:a}=s,{noUpdateTTL:l=this.noUpdateTTL}=s,f=this.#B(t,e,s.size||0,o);if(this.maxEntrySize&&f>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#A(t,"set"),this;let c=this.#o===0?void 0:this.#u.get(t);if(c===void 0)c=this.#o===0?this.#p:this.#R.length!==0?this.#R.pop():this.#o===this.#t?this.#G(!1):this.#o,this.#a[c]=t,this.#i[c]=e,this.#u.set(t,c),this.#d[this.#p]=c,this.#v[c]=this.#p,this.#p=c,this.#o++,this.#j(c,f,a),a&&(a.set="add"),l=!1,this.#F&&this.#r?.(e,t,"add");else{this.#N(c);let d=this.#i[c];if(e!==d){if(this.#T&&this.#l(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:u}=d;u!==void 0&&!h&&(this.#E&&this.#n?.(u,t,"set"),this.#e&&this.#m?.push([u,t,"set"]))}else h||(this.#E&&this.#n?.(d,t,"set"),this.#e&&this.#m?.push([d,t,"set"]));if(this.#L(c),this.#j(c,f,a),this.#i[c]=e,a){a.set="replace";let u=d&&this.#l(d)?d.__staleWhileFetching:d;u!==void 0&&(a.oldValue=u)}}else a&&(a.set="update");this.#F&&this.onInsert?.(e,t,e===d?"update":"replace")}if(i!==0&&!this.#g&&this.#P(),this.#g&&(l||this.#W(c,i,r),a&&this.#D(a,c)),!h&&this.#e&&this.#m){let d=this.#m,u;for(;u=d?.shift();)this.#h?.(...u)}return this}pop(){try{for(;this.#o;){let t=this.#i[this.#y];if(this.#G(!0),this.#l(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#e&&this.#m){let t=this.#m,e;for(;e=t?.shift();)this.#h?.(...e)}}}#G(t){let e=this.#y,s=this.#a[e],i=this.#i[e];return this.#T&&this.#l(i)?i.__abortController.abort(new Error("evicted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(i,s,"evict"),this.#e&&this.#m?.push([i,s,"evict"])),this.#L(e),this.#b?.[e]&&(clearTimeout(this.#b[e]),this.#b[e]=void 0),t&&(this.#a[e]=void 0,this.#i[e]=void 0,this.#R.push(e)),this.#o===1?(this.#y=this.#p=0,this.#R.length=0):this.#y=this.#d[e],this.#u.delete(s),this.#o--,e}has(t,e={}){let{updateAgeOnHas:s=this.updateAgeOnHas,status:i}=e,r=this.#u.get(t);if(r!==void 0){let h=this.#i[r];if(this.#l(h)&&h.__staleWhileFetching===void 0)return!1;if(this.#_(r))i&&(i.has="stale",this.#D(i,r));else return s&&this.#C(r),i&&(i.has="hit",this.#D(i,r)),!0}else i&&(i.has="miss");return!1}peek(t,e={}){let{allowStale:s=this.allowStale}=e,i=this.#u.get(t);if(i===void 0||!s&&this.#_(i))return;let r=this.#i[i];return this.#l(r)?r.__staleWhileFetching:r}#z(t,e,s,i){let r=e===void 0?void 0:this.#i[e];if(this.#l(r))return r;let h=new Lt,{signal:o}=s;o?.addEventListener("abort",()=>h.abort(o.reason),{signal:h.signal});let a={signal:h.signal,options:s,context:i},l=(p,b=!1)=>{let{aborted:w}=h.signal,v=s.ignoreFetchAbort&&p!==void 0,E=s.ignoreFetchAbort||!!(s.allowStaleOnFetchAbort&&p!==void 0);if(s.status&&(w&&!b?(s.status.fetchAborted=!0,s.status.fetchError=h.signal.reason,v&&(s.status.fetchAbortIgnored=!0)):s.status.fetchResolved=!0),w&&!v&&!b)return c(h.signal.reason,E);let y=u,S=this.#i[e];return(S===u||v&&b&&S===void 0)&&(p===void 0?y.__staleWhileFetching!==void 0?this.#i[e]=y.__staleWhileFetching:this.#A(t,"fetch"):(s.status&&(s.status.fetchUpdated=!0),this.set(t,p,a.options))),p},f=p=>(s.status&&(s.status.fetchRejected=!0,s.status.fetchError=p),c(p,!1)),c=(p,b)=>{let{aborted:w}=h.signal,v=w&&s.allowStaleOnFetchAbort,E=v||s.allowStaleOnFetchRejection,y=E||s.noDeleteOnFetchRejection,S=u;if(this.#i[e]===u&&(!y||!b&&S.__staleWhileFetching===void 0?this.#A(t,"fetch"):v||(this.#i[e]=S.__staleWhileFetching)),E)return s.status&&S.__staleWhileFetching!==void 0&&(s.status.returnedStale=!0),S.__staleWhileFetching;if(S.__returned===S)throw p},d=(p,b)=>{let w=this.#S?.(t,r,a);w&&w instanceof Promise&&w.then(v=>p(v===void 0?void 0:v),b),h.signal.addEventListener("abort",()=>{(!s.ignoreFetchAbort||s.allowStaleOnFetchAbort)&&(p(void 0),s.allowStaleOnFetchAbort&&(p=v=>l(v,!0)))})};s.status&&(s.status.fetchDispatched=!0);let u=new Promise(d).then(l,f),m=Object.assign(u,{__abortController:h,__staleWhileFetching:r,__returned:void 0});return e===void 0?(this.set(t,m,{...a.options,status:void 0}),e=this.#u.get(t)):this.#i[e]=m,m}#l(t){if(!this.#T)return!1;let e=t;return!!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof Lt}async fetch(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,ttl:h=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:f=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=this.allowStaleOnFetchAbort,context:p,forceRefresh:b=!1,status:w,signal:v}=e;if(!this.#T)return w&&(w.fetch="get"),this.get(t,{allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,status:w});let E={allowStale:s,updateAgeOnGet:i,noDeleteOnStaleGet:r,ttl:h,noDisposeOnSet:o,size:a,sizeCalculation:l,noUpdateTTL:f,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:m,ignoreFetchAbort:u,status:w,signal:v},y=this.#u.get(t);if(y===void 0){w&&(w.fetch="miss");let S=this.#z(t,y,E,p);return S.__returned=S}else{let S=this.#i[y];if(this.#l(S)){let st=s&&S.__staleWhileFetching!==void 0;return w&&(w.fetch="inflight",st&&(w.returnedStale=!0)),st?S.__staleWhileFetching:S.__returned=S}let B=this.#_(y);if(!b&&!B)return w&&(w.fetch="hit"),this.#N(y),i&&this.#C(y),w&&this.#D(w,y),S;let U=this.#z(t,y,E,p),et=U.__staleWhileFetching!==void 0&&s;return w&&(w.fetch=B?"stale":"refresh",et&&B&&(w.returnedStale=!0)),et?U.__staleWhileFetching:U.__returned=U}}async forceFetch(t,e={}){let s=await this.fetch(t,e);if(s===void 0)throw new Error("fetch() returned undefined");return s}memo(t,e={}){let s=this.#w;if(!s)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:r,...h}=e,o=this.get(t,h);if(!r&&o!==void 0)return o;let a=s(t,o,{options:h,context:i});return this.set(t,a,h),a}get(t,e={}){let{allowStale:s=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:r=this.noDeleteOnStaleGet,status:h}=e,o=this.#u.get(t);if(o!==void 0){let a=this.#i[o],l=this.#l(a);return h&&this.#D(h,o),this.#_(o)?(h&&(h.get="stale"),l?(h&&s&&a.__staleWhileFetching!==void 0&&(h.returnedStale=!0),s?a.__staleWhileFetching:void 0):(r||this.#A(t,"expire"),h&&s&&(h.returnedStale=!0),s?a:void 0)):(h&&(h.get="hit"),l?a.__staleWhileFetching:(this.#N(o),i&&this.#C(o),a))}else h&&(h.get="miss")}#U(t,e){this.#v[e]=t,this.#d[t]=e}#N(t){t!==this.#p&&(t===this.#y?this.#y=this.#d[t]:this.#U(this.#v[t],this.#d[t]),this.#U(this.#p,t),this.#p=t)}delete(t){return this.#A(t,"delete")}#A(t,e){let s=!1;if(this.#o!==0){let i=this.#u.get(t);if(i!==void 0)if(this.#b?.[i]&&(clearTimeout(this.#b?.[i]),this.#b[i]=void 0),s=!0,this.#o===1)this.#q(e);else{this.#L(i);let r=this.#i[i];if(this.#l(r)?r.__abortController.abort(new Error("deleted")):(this.#E||this.#e)&&(this.#E&&this.#n?.(r,t,e),this.#e&&this.#m?.push([r,t,e])),this.#u.delete(t),this.#a[i]=void 0,this.#i[i]=void 0,i===this.#p)this.#p=this.#v[i];else if(i===this.#y)this.#y=this.#d[i];else{let h=this.#v[i];this.#d[h]=this.#d[i];let o=this.#d[i];this.#v[o]=this.#v[i]}this.#o--,this.#R.push(i)}}if(this.#e&&this.#m?.length){let i=this.#m,r;for(;r=i?.shift();)this.#h?.(...r)}return s}clear(){return this.#q("delete")}#q(t){for(let e of this.#M({allowStale:!0})){let s=this.#i[e];if(this.#l(s))s.__abortController.abort(new Error("deleted"));else{let i=this.#a[e];this.#E&&this.#n?.(s,i,t),this.#e&&this.#m?.push([s,i,t])}}if(this.#u.clear(),this.#i.fill(void 0),this.#a.fill(void 0),this.#g&&this.#x){this.#g.fill(0),this.#x.fill(0);for(let e of this.#b??[])e!==void 0&&clearTimeout(e);this.#b?.fill(void 0)}if(this.#O&&this.#O.fill(0),this.#y=0,this.#p=0,this.#R.length=0,this.#f=0,this.#o=0,this.#e&&this.#m){let e=this.#m,s;for(;s=e?.shift();)this.#h?.(...s)}}};Wt.LRUCache=rr});var Oe=R(P=>{"use strict";var nr=P&&P.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(P,"__esModule",{value:!0});P.Minipass=P.isWritable=P.isReadable=P.isStream=void 0;var ds=typeof process=="object"&&process?process:{stdout:null,stderr:null},_e=__nccwpck_require__(474),ws=nr(__nccwpck_require__(75)),hr=__nccwpck_require__(193),or=n=>!!n&&typeof n=="object"&&(n instanceof qt||n instanceof ws.default||(0,P.isReadable)(n)||(0,P.isWritable)(n));P.isStream=or;var ar=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.pipe=="function"&&n.pipe!==ws.default.Writable.prototype.pipe;P.isReadable=ar;var lr=n=>!!n&&typeof n=="object"&&n instanceof _e.EventEmitter&&typeof n.write=="function"&&typeof n.end=="function";P.isWritable=lr;var $=Symbol("EOF"),q=Symbol("maybeEmitEnd"),K=Symbol("emittedEnd"),Bt=Symbol("emittingEnd"),lt=Symbol("emittedError"),It=Symbol("closed"),ps=Symbol("read"),Gt=Symbol("flush"),ms=Symbol("flushChunk"),L=Symbol("encoding"),rt=Symbol("decoder"),x=Symbol("flowing"),ct=Symbol("paused"),nt=Symbol("resume"),T=Symbol("buffer"),M=Symbol("pipes"),C=Symbol("bufferLength"),we=Symbol("bufferPush"),zt=Symbol("bufferShift"),k=Symbol("objectMode"),O=Symbol("destroyed"),be=Symbol("error"),ye=Symbol("emitData"),gs=Symbol("emitEnd"),Se=Symbol("emitEnd2"),I=Symbol("async"),ve=Symbol("abort"),Ut=Symbol("aborted"),ut=Symbol("signal"),Z=Symbol("dataListeners"),D=Symbol("discarded"),ft=n=>Promise.resolve().then(n),cr=n=>n(),ur=n=>n==="end"||n==="finish"||n==="prefinish",fr=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,dr=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),$t=class{src;dest;opts;ondrain;constructor(t,e,s){this.src=t,this.dest=e,this.opts=s,this.ondrain=()=>t[nt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Ee=class extends $t{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,s){super(t,e,s),this.proxyErrors=i=>this.dest.emit("error",i),t.on("error",this.proxyErrors)}},pr=n=>!!n.objectMode,mr=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",qt=class extends _e.EventEmitter{[x]=!1;[ct]=!1;[M]=[];[T]=[];[k];[L];[I];[rt];[$]=!1;[K]=!1;[Bt]=!1;[It]=!1;[lt]=null;[C]=0;[O]=!1;[ut];[Ut]=!1;[Z]=0;[D]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");pr(e)?(this[k]=!0,this[L]=null):mr(e)?(this[L]=e.encoding,this[k]=!1):(this[k]=!1,this[L]=null),this[I]=!!e.async,this[rt]=this[L]?new hr.StringDecoder(this[L]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[T]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[M]});let{signal:s}=e;s&&(this[ut]=s,s.aborted?this[ve]():s.addEventListener("abort",()=>this[ve]()))}get bufferLength(){return this[C]}get encoding(){return this[L]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[k]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[I]}set async(t){this[I]=this[I]||!!t}[ve](){this[Ut]=!0,this.emit("abort",this[ut]?.reason),this.destroy(this[ut]?.reason)}get aborted(){return this[Ut]}set aborted(t){}write(t,e,s){if(this[Ut])return!1;if(this[$])throw new Error("write after end");if(this[O])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(s=e,e="utf8"),e||(e="utf8");let i=this[I]?ft:cr;if(!this[k]&&!Buffer.isBuffer(t)){if(dr(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[k]?(this[x]&&this[C]!==0&&this[Gt](!0),this[x]?this.emit("data",t):this[we](t),this[C]!==0&&this.emit("readable"),s&&i(s),this[x]):t.length?(typeof t=="string"&&!(e===this[L]&&!this[rt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[L]&&(t=this[rt].write(t)),this[x]&&this[C]!==0&&this[Gt](!0),this[x]?this.emit("data",t):this[we](t),this[C]!==0&&this.emit("readable"),s&&i(s),this[x]):(this[C]!==0&&this.emit("readable"),s&&i(s),this[x])}read(t){if(this[O])return null;if(this[D]=!1,this[C]===0||t===0||t&&t>this[C])return this[q](),null;this[k]&&(t=null),this[T].length>1&&!this[k]&&(this[T]=[this[L]?this[T].join(""):Buffer.concat(this[T],this[C])]);let e=this[ps](t||null,this[T][0]);return this[q](),e}[ps](t,e){if(this[k])this[zt]();else{let s=e;t===s.length||t===null?this[zt]():typeof s=="string"?(this[T][0]=s.slice(t),e=s.slice(0,t),this[C]-=t):(this[T][0]=s.subarray(t),e=s.subarray(0,t),this[C]-=t)}return this.emit("data",e),!this[T].length&&!this[$]&&this.emit("drain"),e}end(t,e,s){return typeof t=="function"&&(s=t,t=void 0),typeof e=="function"&&(s=e,e="utf8"),t!==void 0&&this.write(t,e),s&&this.once("end",s),this[$]=!0,this.writable=!1,(this[x]||!this[ct])&&this[q](),this}[nt](){this[O]||(!this[Z]&&!this[M].length&&(this[D]=!0),this[ct]=!1,this[x]=!0,this.emit("resume"),this[T].length?this[Gt]():this[$]?this[q]():this.emit("drain"))}resume(){return this[nt]()}pause(){this[x]=!1,this[ct]=!0,this[D]=!1}get destroyed(){return this[O]}get flowing(){return this[x]}get paused(){return this[ct]}[we](t){this[k]?this[C]+=1:this[C]+=t.length,this[T].push(t)}[zt](){return this[k]?this[C]-=1:this[C]-=this[T][0].length,this[T].shift()}[Gt](t=!1){do;while(this[ms](this[zt]())&&this[T].length);!t&&!this[T].length&&!this[$]&&this.emit("drain")}[ms](t){return this.emit("data",t),this[x]}pipe(t,e){if(this[O])return t;this[D]=!1;let s=this[K];return e=e||{},t===ds.stdout||t===ds.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,s?e.end&&t.end():(this[M].push(e.proxyErrors?new Ee(this,t,e):new $t(this,t,e)),this[I]?ft(()=>this[nt]()):this[nt]()),t}unpipe(t){let e=this[M].find(s=>s.dest===t);e&&(this[M].length===1?(this[x]&&this[Z]===0&&(this[x]=!1),this[M]=[]):this[M].splice(this[M].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let s=super.on(t,e);if(t==="data")this[D]=!1,this[Z]++,!this[M].length&&!this[x]&&this[nt]();else if(t==="readable"&&this[C]!==0)super.emit("readable");else if(ur(t)&&this[K])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[lt]){let i=e;this[I]?ft(()=>i.call(this,this[lt])):i.call(this,this[lt])}return s}removeListener(t,e){return this.off(t,e)}off(t,e){let s=super.off(t,e);return t==="data"&&(this[Z]=this.listeners("data").length,this[Z]===0&&!this[D]&&!this[M].length&&(this[x]=!1)),s}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Z]=0,!this[D]&&!this[M].length&&(this[x]=!1)),e}get emittedEnd(){return this[K]}[q](){!this[Bt]&&!this[K]&&!this[O]&&this[T].length===0&&this[$]&&(this[Bt]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[It]&&this.emit("close"),this[Bt]=!1)}emit(t,...e){let s=e[0];if(t!=="error"&&t!=="close"&&t!==O&&this[O])return!1;if(t==="data")return!this[k]&&!s?!1:this[I]?(ft(()=>this[ye](s)),!0):this[ye](s);if(t==="end")return this[gs]();if(t==="close"){if(this[It]=!0,!this[K]&&!this[O])return!1;let r=super.emit("close");return this.removeAllListeners("close"),r}else if(t==="error"){this[lt]=s,super.emit(be,s);let r=!this[ut]||this.listeners("error").length?super.emit("error",s):!1;return this[q](),r}else if(t==="resume"){let r=super.emit("resume");return this[q](),r}else if(t==="finish"||t==="prefinish"){let r=super.emit(t);return this.removeAllListeners(t),r}let i=super.emit(t,...e);return this[q](),i}[ye](t){for(let s of this[M])s.dest.write(t)===!1&&this.pause();let e=this[D]?!1:super.emit("data",t);return this[q](),e}[gs](){return this[K]?!1:(this[K]=!0,this.readable=!1,this[I]?(ft(()=>this[Se]()),!0):this[Se]())}[Se](){if(this[rt]){let e=this[rt].end();if(e){for(let s of this[M])s.dest.write(e);this[D]||super.emit("data",e)}}for(let e of this[M])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[k]||(t.dataLength=0);let e=this.promise();return this.on("data",s=>{t.push(s),this[k]||(t.dataLength+=s.length)}),await e,t}async concat(){if(this[k])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[L]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(O,()=>e(new Error("stream destroyed"))),this.on("error",s=>e(s)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[D]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let i=this.read();if(i!==null)return Promise.resolve({done:!1,value:i});if(this[$])return e();let r,h,o=c=>{this.off("data",a),this.off("end",l),this.off(O,f),e(),h(c)},a=c=>{this.off("error",o),this.off("end",l),this.off(O,f),this.pause(),r({value:c,done:!!this[$]})},l=()=>{this.off("error",o),this.off("data",a),this.off(O,f),e(),r({done:!0,value:void 0})},f=()=>o(new Error("stream destroyed"));return new Promise((c,d)=>{h=d,r=c,this.once(O,f),this.once("error",o),this.once("end",l),this.once("data",a)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[D]=!1;let t=!1,e=()=>(this.pause(),this.off(be,e),this.off(O,e),this.off("end",e),t=!0,{done:!0,value:void 0}),s=()=>{if(t)return e();let i=this.read();return i===null?e():{done:!1,value:i}};return this.once("end",e),this.once(be,e),this.once(O,e),{next:s,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[O])return t?this.emit("error",t):this.emit(O),this;this[O]=!0,this[D]=!0,this[T].length=0,this[C]=0;let e=this;return typeof e.close=="function"&&!this[It]&&e.close(),t?this.emit("error",t):this.emit(O),this}static get isStream(){return P.isStream}};P.Minipass=qt});var Ms=R(_=>{"use strict";var gr=_&&_.__createBinding||(Object.create?(function(n,t,e,s){s===void 0&&(s=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,s,i)}):(function(n,t,e,s){s===void 0&&(s=e),n[s]=t[e]})),wr=_&&_.__setModuleDefault||(Object.create?(function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}):function(n,t){n.default=t}),br=_&&_.__importStar||function(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&gr(t,n,e);return wr(t,n),t};Object.defineProperty(_,"__esModule",{value:!0});_.PathScurry=_.Path=_.PathScurryDarwin=_.PathScurryPosix=_.PathScurryWin32=_.PathScurryBase=_.PathPosix=_.PathWin32=_.PathBase=_.ChildrenCache=_.ResolveCache=void 0;var Qt=fs(),Yt=__nccwpck_require__(760),yr=__nccwpck_require__(136),pt=__nccwpck_require__(896),Sr=br(__nccwpck_require__(24)),vr=pt.realpathSync.native,Ht=__nccwpck_require__(455),bs=Oe(),mt={lstatSync:pt.lstatSync,readdir:pt.readdir,readdirSync:pt.readdirSync,readlinkSync:pt.readlinkSync,realpathSync:vr,promises:{lstat:Ht.lstat,readdir:Ht.readdir,readlink:Ht.readlink,realpath:Ht.realpath}},_s=n=>!n||n===mt||n===Sr?mt:{...mt,...n,promises:{...mt.promises,...n.promises||{}}},Os=/^\\\\\?\\([a-z]:)\\?$/i,Er=n=>n.replace(/\//g,"\\").replace(Os,"$1\\"),_r=/[\\\/]/,N=0,xs=1,Ts=2,G=4,Cs=6,Rs=8,Q=10,As=12,j=15,dt=~j,xe=16,ys=32,gt=64,W=128,Vt=256,Xt=512,Ss=gt|W|Xt,Or=1023,Te=n=>n.isFile()?Rs:n.isDirectory()?G:n.isSymbolicLink()?Q:n.isCharacterDevice()?Ts:n.isBlockDevice()?Cs:n.isSocket()?As:n.isFIFO()?xs:N,vs=new Qt.LRUCache({max:2**12}),wt=n=>{let t=vs.get(n);if(t)return t;let e=n.normalize("NFKD");return vs.set(n,e),e},Es=new Qt.LRUCache({max:2**12}),Kt=n=>{let t=Es.get(n);if(t)return t;let e=wt(n.toLowerCase());return Es.set(n,e),e},bt=class extends Qt.LRUCache{constructor(){super({max:256})}};_.ResolveCache=bt;var Jt=class extends Qt.LRUCache{constructor(t=16*1024){super({maxSize:t,sizeCalculation:e=>e.length+1})}};_.ChildrenCache=Jt;var ks=Symbol("PathScurry setAsCwd"),A=class{name;root;roots;parent;nocase;isCWD=!1;#t;#s;get dev(){return this.#s}#n;get mode(){return this.#n}#r;get nlink(){return this.#r}#h;get uid(){return this.#h}#S;get gid(){return this.#S}#w;get rdev(){return this.#w}#c;get blksize(){return this.#c}#o;get ino(){return this.#o}#f;get size(){return this.#f}#u;get blocks(){return this.#u}#a;get atimeMs(){return this.#a}#i;get mtimeMs(){return this.#i}#d;get ctimeMs(){return this.#d}#v;get birthtimeMs(){return this.#v}#y;get atime(){return this.#y}#p;get mtime(){return this.#p}#R;get ctime(){return this.#R}#m;get birthtime(){return this.#m}#O;#x;#g;#b;#E;#T;#e;#F;#P;#C;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(t,e=N,s,i,r,h,o){this.name=t,this.#O=r?Kt(t):wt(t),this.#e=e&Or,this.nocase=r,this.roots=i,this.root=s||this,this.#F=h,this.#g=o.fullpath,this.#E=o.relative,this.#T=o.relativePosix,this.parent=o.parent,this.parent?this.#t=this.parent.#t:this.#t=_s(o.fs)}depth(){return this.#x!==void 0?this.#x:this.parent?this.#x=this.parent.depth()+1:this.#x=0}childrenCache(){return this.#F}resolve(t){if(!t)return this;let e=this.getRootString(t),i=t.substring(e.length).split(this.splitSep);return e?this.getRoot(e).#D(i):this.#D(i)}#D(t){let e=this;for(let s of t)e=e.child(s);return e}children(){let t=this.#F.get(this);if(t)return t;let e=Object.assign([],{provisional:0});return this.#F.set(this,e),this.#e&=~xe,e}child(t,e){if(t===""||t===".")return this;if(t==="..")return this.parent||this;let s=this.children(),i=this.nocase?Kt(t):wt(t);for(let a of s)if(a.#O===i)return a;let r=this.parent?this.sep:"",h=this.#g?this.#g+r+t:void 0,o=this.newChild(t,N,{...e,parent:this,fullpath:h});return this.canReaddir()||(o.#e|=W),s.push(o),o}relative(){if(this.isCWD)return"";if(this.#E!==void 0)return this.#E;let t=this.name,e=this.parent;if(!e)return this.#E=this.name;let s=e.relative();return s+(!s||!e.parent?"":this.sep)+t}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#T!==void 0)return this.#T;let t=this.name,e=this.parent;if(!e)return this.#T=this.fullpathPosix();let s=e.relativePosix();return s+(!s||!e.parent?"":"/")+t}fullpath(){if(this.#g!==void 0)return this.#g;let t=this.name,e=this.parent;if(!e)return this.#g=this.name;let i=e.fullpath()+(e.parent?this.sep:"")+t;return this.#g=i}fullpathPosix(){if(this.#b!==void 0)return this.#b;if(this.sep==="/")return this.#b=this.fullpath();if(!this.parent){let i=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(i)?this.#b=`//?/${i}`:this.#b=i}let t=this.parent,e=t.fullpathPosix(),s=e+(!e||!t.parent?"":"/")+this.name;return this.#b=s}isUnknown(){return(this.#e&j)===N}isType(t){return this[`is${t}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#e&j)===Rs}isDirectory(){return(this.#e&j)===G}isCharacterDevice(){return(this.#e&j)===Ts}isBlockDevice(){return(this.#e&j)===Cs}isFIFO(){return(this.#e&j)===xs}isSocket(){return(this.#e&j)===As}isSymbolicLink(){return(this.#e&Q)===Q}lstatCached(){return this.#e&ys?this:void 0}readlinkCached(){return this.#P}realpathCached(){return this.#C}readdirCached(){let t=this.children();return t.slice(0,t.provisional)}canReadlink(){if(this.#P)return!0;if(!this.parent)return!1;let t=this.#e&j;return!(t!==N&&t!==Q||this.#e&Vt||this.#e&W)}calledReaddir(){return!!(this.#e&xe)}isENOENT(){return!!(this.#e&W)}isNamed(t){return this.nocase?this.#O===Kt(t):this.#O===wt(t)}async readlink(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=await this.#t.promises.readlink(this.fullpath()),s=(await this.parent.realpath())?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}readlinkSync(){let t=this.#P;if(t)return t;if(this.canReadlink()&&this.parent)try{let e=this.#t.readlinkSync(this.fullpath()),s=this.parent.realpathSync()?.resolve(e);if(s)return this.#P=s}catch(e){this.#M(e.code);return}}#W(t){this.#e|=xe;for(let e=t.provisional;es(null,t))}readdirCB(t,e=!1){if(!this.canReaddir()){e?t(null,[]):queueMicrotask(()=>t(null,[]));return}let s=this.children();if(this.calledReaddir()){let r=s.slice(0,s.provisional);e?t(null,r):queueMicrotask(()=>t(null,r));return}if(this.#N.push(t),this.#A)return;this.#A=!0;let i=this.fullpath();this.#t.readdir(i,{withFileTypes:!0},(r,h)=>{if(r)this.#B(r.code),s.provisional=0;else{for(let o of h)this.#I(o,s);this.#W(s)}this.#q(s.slice(0,s.provisional))})}#H;async readdir(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();if(this.#H)await this.#H;else{let s=()=>{};this.#H=new Promise(i=>s=i);try{for(let i of await this.#t.promises.readdir(e,{withFileTypes:!0}))this.#I(i,t);this.#W(t)}catch(i){this.#B(i.code),t.provisional=0}this.#H=void 0,s()}return t.slice(0,t.provisional)}readdirSync(){if(!this.canReaddir())return[];let t=this.children();if(this.calledReaddir())return t.slice(0,t.provisional);let e=this.fullpath();try{for(let s of this.#t.readdirSync(e,{withFileTypes:!0}))this.#I(s,t);this.#W(t)}catch(s){this.#B(s.code),t.provisional=0}return t.slice(0,t.provisional)}canReaddir(){if(this.#e&Ss)return!1;let t=j&this.#e;return t===N||t===G||t===Q}shouldWalk(t,e){return(this.#e&G)===G&&!(this.#e&Ss)&&!t.has(this)&&(!e||e(this))}async realpath(){if(this.#C)return this.#C;if(!((Xt|Vt|W)&this.#e))try{let t=await this.#t.promises.realpath(this.fullpath());return this.#C=this.resolve(t)}catch{this.#L()}}realpathSync(){if(this.#C)return this.#C;if(!((Xt|Vt|W)&this.#e))try{let t=this.#t.realpathSync(this.fullpath());return this.#C=this.resolve(t)}catch{this.#L()}}[ks](t){if(t===this)return;t.isCWD=!1,this.isCWD=!0;let e=new Set([]),s=[],i=this;for(;i&&i.parent;)e.add(i),i.#E=s.join(this.sep),i.#T=s.join("/"),i=i.parent,s.push("..");for(i=t;i&&i.parent&&!e.has(i);)i.#E=void 0,i.#T=void 0,i=i.parent}};_.PathBase=A;var yt=class n extends A{sep="\\";splitSep=_r;constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}getRootString(t){return Yt.win32.parse(t).root}getRoot(t){if(t=Er(t.toUpperCase()),t===this.root.name)return this.root;for(let[e,s]of Object.entries(this.roots))if(this.sameRoot(t,e))return this.roots[t]=s;return this.roots[t]=new Et(t,this).root}sameRoot(t,e=this.root.name){return t=t.toUpperCase().replace(/\//g,"\\").replace(Os,"$1\\"),t===e}};_.PathWin32=yt;var St=class n extends A{splitSep="/";sep="/";constructor(t,e=N,s,i,r,h,o){super(t,e,s,i,r,h,o)}getRootString(t){return t.startsWith("/")?"/":""}getRoot(t){return this.root}newChild(t,e=N,s={}){return new n(t,e,this.root,this.roots,this.nocase,this.childrenCache(),s)}};_.PathPosix=St;var vt=class{root;rootPath;roots;cwd;#t;#s;#n;nocase;#r;constructor(t=process.cwd(),e,s,{nocase:i,childrenCacheSize:r=16*1024,fs:h=mt}={}){this.#r=_s(h),(t instanceof URL||t.startsWith("file://"))&&(t=(0,yr.fileURLToPath)(t));let o=e.resolve(t);this.roots=Object.create(null),this.rootPath=this.parseRootPath(o),this.#t=new bt,this.#s=new bt,this.#n=new Jt(r);let a=o.substring(this.rootPath.length).split(s);if(a.length===1&&!a[0]&&a.pop(),i===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=i,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let l=this.root,f=a.length-1,c=e.sep,d=this.rootPath,u=!1;for(let m of a){let p=f--;l=l.child(m,{relative:new Array(p).fill("..").join(c),relativePosix:new Array(p).fill("..").join("/"),fullpath:d+=(u?"":c)+m}),u=!0}this.cwd=l}depth(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.depth()}childrenCache(){return this.#n}resolve(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#t.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpath();return this.#t.set(e,i),i}resolvePosix(...t){let e="";for(let r=t.length-1;r>=0;r--){let h=t[r];if(!(!h||h===".")&&(e=e?`${h}/${e}`:h,this.isAbsolute(h)))break}let s=this.#s.get(e);if(s!==void 0)return s;let i=this.cwd.resolve(e).fullpathPosix();return this.#s.set(e,i),i}relative(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relative()}relativePosix(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.relativePosix()}basename(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.name}dirname(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),(t.parent||t).fullpath()}async readdir(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s}=e;if(t.canReaddir()){let i=await t.readdir();return s?i:i.map(r=>r.name)}else return[]}readdirSync(t=this.cwd,e={withFileTypes:!0}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0}=e;return t.canReaddir()?s?t.readdirSync():t.readdirSync().map(i=>i.name):[]}async lstat(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstat()}lstatSync(t=this.cwd){return typeof t=="string"&&(t=this.cwd.resolve(t)),t.lstatSync()}async readlink(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.readlink();return e?s:s?.fullpath()}readlinkSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.readlinkSync();return e?s:s?.fullpath()}async realpath(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=await t.realpath();return e?s:s?.fullpath()}realpathSync(t=this.cwd,{withFileTypes:e}={withFileTypes:!1}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t.withFileTypes,t=this.cwd);let s=t.realpathSync();return e?s:s?.fullpath()}async walk(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set,l=(c,d)=>{a.add(c),c.readdirCB((u,m)=>{if(u)return d(u);let p=m.length;if(!p)return d();let b=()=>{--p===0&&d()};for(let w of m)(!r||r(w))&&o.push(s?w:w.fullpath()),i&&w.isSymbolicLink()?w.realpath().then(v=>v?.isUnknown()?v.lstat():v).then(v=>v?.shouldWalk(a,h)?l(v,b):b()):w.shouldWalk(a,h)?l(w,b):b()},!0)},f=t;return new Promise((c,d)=>{l(f,u=>{if(u)return d(u);c(o)})})}walkSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=[];(!r||r(t))&&o.push(s?t:t.fullpath());let a=new Set([t]);for(let l of a){let f=l.readdirSync();for(let c of f){(!r||r(c))&&o.push(s?c:c.fullpath());let d=c;if(c.isSymbolicLink()){if(!(i&&(d=c.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,h)&&a.add(d)}}return o}[Symbol.asyncIterator](){return this.iterate()}iterate(t=this.cwd,e={}){return typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd),this.stream(t,e)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e;(!r||r(t))&&(yield s?t:t.fullpath());let o=new Set([t]);for(let a of o){let l=a.readdirSync();for(let f of l){(!r||r(f))&&(yield s?f:f.fullpath());let c=f;if(f.isSymbolicLink()){if(!(i&&(c=f.realpathSync())))continue;c.isUnknown()&&c.lstatSync()}c.shouldWalk(o,h)&&o.add(c)}}}stream(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0});(!r||r(t))&&o.write(s?t:t.fullpath());let a=new Set,l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=(b,w,v=!1)=>{if(b)return o.emit("error",b);if(i&&!v){let E=[];for(let y of w)y.isSymbolicLink()&&E.push(y.realpath().then(S=>S?.isUnknown()?S.lstat():S));if(E.length){Promise.all(E).then(()=>m(null,w,!0));return}}for(let E of w)E&&(!r||r(E))&&(o.write(s?E:E.fullpath())||(d=!0));f--;for(let E of w){let y=E.realpathCached()||E;y.shouldWalk(a,h)&&l.push(y)}d&&!o.flowing?o.once("drain",c):p||c()},p=!0;u.readdirCB(m,!0),p=!1}};return c(),o}streamSync(t=this.cwd,e={}){typeof t=="string"?t=this.cwd.resolve(t):t instanceof A||(e=t,t=this.cwd);let{withFileTypes:s=!0,follow:i=!1,filter:r,walkFilter:h}=e,o=new bs.Minipass({objectMode:!0}),a=new Set;(!r||r(t))&&o.write(s?t:t.fullpath());let l=[t],f=0,c=()=>{let d=!1;for(;!d;){let u=l.shift();if(!u){f===0&&o.end();return}f++,a.add(u);let m=u.readdirSync();for(let p of m)(!r||r(p))&&(o.write(s?p:p.fullpath())||(d=!0));f--;for(let p of m){let b=p;if(p.isSymbolicLink()){if(!(i&&(b=p.realpathSync())))continue;b.isUnknown()&&b.lstatSync()}b.shouldWalk(a,h)&&l.push(b)}}d&&!o.flowing&&o.once("drain",c)};return c(),o}chdir(t=this.cwd){let e=this.cwd;this.cwd=typeof t=="string"?this.cwd.resolve(t):t,this.cwd[ks](e)}};_.PathScurryBase=vt;var Et=class extends vt{sep="\\";constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,Yt.win32,"\\",{...e,nocase:s}),this.nocase=s;for(let i=this.cwd;i;i=i.parent)i.nocase=this.nocase}parseRootPath(t){return Yt.win32.parse(t).root.toUpperCase()}newRoot(t){return new yt(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")||t.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(t)}};_.PathScurryWin32=Et;var _t=class extends vt{sep="/";constructor(t=process.cwd(),e={}){let{nocase:s=!1}=e;super(t,Yt.posix,"/",{...e,nocase:s}),this.nocase=s}parseRootPath(t){return"/"}newRoot(t){return new St(this.rootPath,G,void 0,this.roots,this.nocase,this.childrenCache(),{fs:t})}isAbsolute(t){return t.startsWith("/")}};_.PathScurryPosix=_t;var Zt=class extends _t{constructor(t=process.cwd(),e={}){let{nocase:s=!0}=e;super(t,{...e,nocase:s})}};_.PathScurryDarwin=Zt;_.Path=process.platform==="win32"?yt:St;_.PathScurry=process.platform==="win32"?Et:process.platform==="darwin"?Zt:_t});var Re=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.Pattern=void 0;var xr=H(),Tr=n=>n.length>=1,Cr=n=>n.length>=1,Rr=Symbol.for("nodejs.util.inspect.custom"),Ce=class n{#t;#s;#n;length;#r;#h;#S;#w;#c;#o;#f=!0;constructor(t,e,s,i){if(!Tr(t))throw new TypeError("empty pattern list");if(!Cr(e))throw new TypeError("empty glob list");if(e.length!==t.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=t.length,s<0||s>=this.length)throw new TypeError("index out of range");if(this.#t=t,this.#s=e,this.#n=s,this.#r=i,this.#n===0){if(this.isUNC()){let[r,h,o,a,...l]=this.#t,[f,c,d,u,...m]=this.#s;l[0]===""&&(l.shift(),m.shift());let p=[r,h,o,a,""].join("/"),b=[f,c,d,u,""].join("/");this.#t=[p,...l],this.#s=[b,...m],this.length=this.#t.length}else if(this.isDrive()||this.isAbsolute()){let[r,...h]=this.#t,[o,...a]=this.#s;h[0]===""&&(h.shift(),a.shift());let l=r+"/",f=o+"/";this.#t=[l,...h],this.#s=[f,...a],this.length=this.#t.length}}}[Rr](){return"Pattern <"+this.#s.slice(this.#n).join("/")+">"}pattern(){return this.#t[this.#n]}isString(){return typeof this.#t[this.#n]=="string"}isGlobstar(){return this.#t[this.#n]===xr.GLOBSTAR}isRegExp(){return this.#t[this.#n]instanceof RegExp}globString(){return this.#S=this.#S||(this.#n===0?this.isAbsolute()?this.#s[0]+this.#s.slice(1).join("/"):this.#s.join("/"):this.#s.slice(this.#n).join("/"))}hasMore(){return this.length>this.#n+1}rest(){return this.#h!==void 0?this.#h:this.hasMore()?(this.#h=new n(this.#t,this.#s,this.#n+1,this.#r),this.#h.#o=this.#o,this.#h.#c=this.#c,this.#h.#w=this.#w,this.#h):this.#h=null}isUNC(){let t=this.#t;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#n===0&&t[0]===""&&t[1]===""&&typeof t[2]=="string"&&!!t[2]&&typeof t[3]=="string"&&!!t[3]}isDrive(){let t=this.#t;return this.#w!==void 0?this.#w:this.#w=this.#r==="win32"&&this.#n===0&&this.length>1&&typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0])}isAbsolute(){let t=this.#t;return this.#o!==void 0?this.#o:this.#o=t[0]===""&&t.length>1||this.isDrive()||this.isUNC()}root(){let t=this.#t[0];return typeof t=="string"&&this.isAbsolute()&&this.#n===0?t:""}checkFollowGlobstar(){return!(this.#n===0||!this.isGlobstar()||!this.#f)}markFollowGlobstar(){return this.#n===0||!this.isGlobstar()||!this.#f?!1:(this.#f=!1,!0)}};te.Pattern=Ce});var ke=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.Ignore=void 0;var Ps=H(),Ar=Re(),kr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Ae=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(t,{nobrace:e,nocase:s,noext:i,noglobstar:r,platform:h=kr}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=h,this.mmopts={dot:!0,nobrace:e,nocase:s,noext:i,noglobstar:r,optimizationLevel:2,platform:h,nocomment:!0,nonegate:!0};for(let o of t)this.add(o)}add(t){let e=new Ps.Minimatch(t,this.mmopts);for(let s=0;s{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.Processor=z.SubWalks=z.MatchRecord=z.HasWalkedCache=void 0;var Ds=H(),se=class n{store;constructor(t=new Map){this.store=t}copy(){return new n(new Map(this.store))}hasWalked(t,e){return this.store.get(t.fullpath())?.has(e.globString())}storeWalked(t,e){let s=t.fullpath(),i=this.store.get(s);i?i.add(e.globString()):this.store.set(s,new Set([e.globString()]))}};z.HasWalkedCache=se;var ie=class{store=new Map;add(t,e,s){let i=(e?2:0)|(s?1:0),r=this.store.get(t);this.store.set(t,r===void 0?i:i&r)}entries(){return[...this.store.entries()].map(([t,e])=>[t,!!(e&2),!!(e&1)])}};z.MatchRecord=ie;var re=class{store=new Map;add(t,e){if(!t.canReaddir())return;let s=this.store.get(t);s?s.find(i=>i.globString()===e.globString())||s.push(e):this.store.set(t,[e])}get(t){let e=this.store.get(t);if(!e)throw new Error("attempting to walk unknown path");return e}entries(){return this.keys().map(t=>[t,this.store.get(t)])}keys(){return[...this.store.keys()].filter(t=>t.canReaddir())}};z.SubWalks=re;var Me=class n{hasWalkedCache;matches=new ie;subwalks=new re;patterns;follow;dot;opts;constructor(t,e){this.opts=t,this.follow=!!t.follow,this.dot=!!t.dot,this.hasWalkedCache=e?e.copy():new se}processPatterns(t,e){this.patterns=e;let s=e.map(i=>[t,i]);for(let[i,r]of s){this.hasWalkedCache.storeWalked(i,r);let h=r.root(),o=r.isAbsolute()&&this.opts.absolute!==!1;if(h){i=i.resolve(h==="/"&&this.opts.root!==void 0?this.opts.root:h);let c=r.rest();if(c)r=c;else{this.matches.add(i,!0,!1);continue}}if(i.isENOENT())continue;let a,l,f=!1;for(;typeof(a=r.pattern())=="string"&&(l=r.rest());)i=i.resolve(a),r=l,f=!0;if(a=r.pattern(),l=r.rest(),f){if(this.hasWalkedCache.hasWalked(i,r))continue;this.hasWalkedCache.storeWalked(i,r)}if(typeof a=="string"){let c=a===".."||a===""||a===".";this.matches.add(i.resolve(a),o,c);continue}else if(a===Ds.GLOBSTAR){(!i.isSymbolicLink()||this.follow||r.checkFollowGlobstar())&&this.subwalks.add(i,r);let c=l?.pattern(),d=l?.rest();if(!l||(c===""||c===".")&&!d)this.matches.add(i,o,c===""||c===".");else if(c===".."){let u=i.parent||i;d?this.hasWalkedCache.hasWalked(u,d)||this.subwalks.add(u,d):this.matches.add(u,o,!0)}}else a instanceof RegExp&&this.subwalks.add(i,r)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(t,e){let s=this.subwalks.get(t),i=this.child();for(let r of e)for(let h of s){let o=h.isAbsolute(),a=h.pattern(),l=h.rest();a===Ds.GLOBSTAR?i.testGlobstar(r,h,l,o):a instanceof RegExp?i.testRegExp(r,a,l,o):i.testString(r,a,l,o)}return i}testGlobstar(t,e,s,i){if((this.dot||!t.name.startsWith("."))&&(e.hasMore()||this.matches.add(t,i,!1),t.canReaddir()&&(this.follow||!t.isSymbolicLink()?this.subwalks.add(t,e):t.isSymbolicLink()&&(s&&e.checkFollowGlobstar()?this.subwalks.add(t,s):e.markFollowGlobstar()&&this.subwalks.add(t,e)))),s){let r=s.pattern();if(typeof r=="string"&&r!==".."&&r!==""&&r!==".")this.testString(t,r,s.rest(),i);else if(r===".."){let h=t.parent||t;this.subwalks.add(h,s)}else r instanceof RegExp&&this.testRegExp(t,r,s.rest(),i)}}testRegExp(t,e,s,i){e.test(t.name)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}testString(t,e,s,i){t.isNamed(e)&&(s?this.subwalks.add(t,s):this.matches.add(t,i,!1))}};z.Processor=Me});var Ls=R(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.GlobStream=X.GlobWalker=X.GlobUtil=void 0;var Mr=Oe(),js=ke(),Ns=Fs(),Pr=(n,t)=>typeof n=="string"?new js.Ignore([n],t):Array.isArray(n)?new js.Ignore(n,t):n,Ot=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#t=[];#s;#n;signal;maxDepth;includeChildMatches;constructor(t,e,s){if(this.patterns=t,this.path=e,this.opts=s,this.#n=!s.posix&&s.platform==="win32"?"\\":"/",this.includeChildMatches=s.includeChildMatches!==!1,(s.ignore||!this.includeChildMatches)&&(this.#s=Pr(s.ignore??[],s),!this.includeChildMatches&&typeof this.#s.add!="function")){let i="cannot ignore child matches, ignore lacks add() method.";throw new Error(i)}this.maxDepth=s.maxDepth||1/0,s.signal&&(this.signal=s.signal,this.signal.addEventListener("abort",()=>{this.#t.length=0}))}#r(t){return this.seen.has(t)||!!this.#s?.ignored?.(t)}#h(t){return!!this.#s?.childrenIgnored?.(t)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let t;for(;!this.paused&&(t=this.#t.shift());)t()}onResume(t){this.signal?.aborted||(this.paused?this.#t.push(t):t())}async matchCheck(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||await t.realpath(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?await t.lstat():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=await r.realpath();h&&(h.isUnknown()||this.opts.stat)&&await h.lstat()}return this.matchCheckTest(r,e)}matchCheckTest(t,e){return t&&(this.maxDepth===1/0||t.depth()<=this.maxDepth)&&(!e||t.canReaddir())&&(!this.opts.nodir||!t.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!t.isSymbolicLink()||!t.realpathCached()?.isDirectory())&&!this.#r(t)?t:void 0}matchCheckSync(t,e){if(e&&this.opts.nodir)return;let s;if(this.opts.realpath){if(s=t.realpathCached()||t.realpathSync(),!s)return;t=s}let r=t.isUnknown()||this.opts.stat?t.lstatSync():t;if(this.opts.follow&&this.opts.nodir&&r?.isSymbolicLink()){let h=r.realpathSync();h&&(h?.isUnknown()||this.opts.stat)&&h.lstatSync()}return this.matchCheckTest(r,e)}matchFinish(t,e){if(this.#r(t))return;if(!this.includeChildMatches&&this.#s?.add){let r=`${t.relativePosix()}/**`;this.#s.add(r)}let s=this.opts.absolute===void 0?e:this.opts.absolute;this.seen.add(t);let i=this.opts.mark&&t.isDirectory()?this.#n:"";if(this.opts.withFileTypes)this.matchEmit(t);else if(s){let r=this.opts.posix?t.fullpathPosix():t.fullpath();this.matchEmit(r+i)}else{let r=this.opts.posix?t.relativePosix():t.relative(),h=this.opts.dotRelative&&!r.startsWith(".."+this.#n)?"."+this.#n:"";this.matchEmit(r?h+r+i:"."+i)}}async match(t,e,s){let i=await this.matchCheck(t,s);i&&this.matchFinish(i,e)}matchSync(t,e,s){let i=this.matchCheckSync(t,s);i&&this.matchFinish(i,e)}walkCB(t,e,s){this.signal?.aborted&&s(),this.walkCB2(t,e,new Ns.Processor(this.opts),s)}walkCB2(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirCached();o.calledReaddir()?this.walkCB3(o,a,s,h):o.readdirCB((l,f)=>this.walkCB3(o,f,s,h),!0)}h()}walkCB3(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||(r++,this.match(o,a,l).then(()=>h()));for(let[o,a]of s.subwalks.entries())r++,this.walkCB2(o,a,s.child(),h);h()}walkCBSync(t,e,s){this.signal?.aborted&&s(),this.walkCB2Sync(t,e,new Ns.Processor(this.opts),s)}walkCB2Sync(t,e,s,i){if(this.#h(t))return i();if(this.signal?.aborted&&i(),this.paused){this.onResume(()=>this.walkCB2Sync(t,e,s,i));return}s.processPatterns(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let o of s.subwalkTargets()){if(this.maxDepth!==1/0&&o.depth()>=this.maxDepth)continue;r++;let a=o.readdirSync();this.walkCB3Sync(o,a,s,h)}h()}walkCB3Sync(t,e,s,i){s=s.filterEntries(t,e);let r=1,h=()=>{--r===0&&i()};for(let[o,a,l]of s.matches.entries())this.#r(o)||this.matchSync(o,a,l);for(let[o,a]of s.subwalks.entries())r++,this.walkCB2Sync(o,a,s.child(),h);h()}};X.GlobUtil=Ot;var Pe=class extends Ot{matches=new Set;constructor(t,e,s){super(t,e,s)}matchEmit(t){this.matches.add(t)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((t,e)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?e(this.signal.reason):t(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}};X.GlobWalker=Pe;var De=class extends Ot{results;constructor(t,e,s){super(t,e,s),this.results=new Mr.Minipass({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(t){this.results.write(t),this.results.flowing||this.pause()}stream(){let t=this.path;return t.isUnknown()?t.lstat().then(()=>{this.walkCB(t,this.patterns,()=>this.results.end())}):this.walkCB(t,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};X.GlobStream=De});var je=R(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.Glob=void 0;var Dr=H(),Fr=__nccwpck_require__(136),ne=Ms(),jr=Re(),he=Ls(),Nr=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Fe=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(t,e){if(!e)throw new TypeError("glob options required");if(this.withFileTypes=!!e.withFileTypes,this.signal=e.signal,this.follow=!!e.follow,this.dot=!!e.dot,this.dotRelative=!!e.dotRelative,this.nodir=!!e.nodir,this.mark=!!e.mark,e.cwd?(e.cwd instanceof URL||e.cwd.startsWith("file://"))&&(e.cwd=(0,Fr.fileURLToPath)(e.cwd)):this.cwd="",this.cwd=e.cwd||"",this.root=e.root,this.magicalBraces=!!e.magicalBraces,this.nobrace=!!e.nobrace,this.noext=!!e.noext,this.realpath=!!e.realpath,this.absolute=e.absolute,this.includeChildMatches=e.includeChildMatches!==!1,this.noglobstar=!!e.noglobstar,this.matchBase=!!e.matchBase,this.maxDepth=typeof e.maxDepth=="number"?e.maxDepth:1/0,this.stat=!!e.stat,this.ignore=e.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof t=="string"&&(t=[t]),this.windowsPathsNoEscape=!!e.windowsPathsNoEscape||e.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(t=t.map(a=>a.replace(/\\/g,"/"))),this.matchBase){if(e.noglobstar)throw new TypeError("base matching requires globstar");t=t.map(a=>a.includes("/")?a:`./**/${a}`)}if(this.pattern=t,this.platform=e.platform||Nr,this.opts={...e,platform:this.platform},e.scurry){if(this.scurry=e.scurry,e.nocase!==void 0&&e.nocase!==e.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let a=e.platform==="win32"?ne.PathScurryWin32:e.platform==="darwin"?ne.PathScurryDarwin:e.platform?ne.PathScurryPosix:ne.PathScurry;this.scurry=new a(this.cwd,{nocase:e.nocase,fs:e.fs})}this.nocase=this.scurry.nocase;let s=this.platform==="darwin"||this.platform==="win32",i={braceExpandMax:1e4,...e,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:s,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},r=this.pattern.map(a=>new Dr.Minimatch(a,i)),[h,o]=r.reduce((a,l)=>(a[0].push(...l.set),a[1].push(...l.globParts),a),[[],[]]);this.patterns=h.map((a,l)=>{let f=o[l];if(!f)throw new Error("invalid pattern object");return new jr.Pattern(a,f,0,this.platform)})}async walk(){return[...await new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new he.GlobWalker(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new he.GlobStream(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};oe.Glob=Fe});var Ne=R(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.hasMagic=void 0;var Lr=H(),Wr=(n,t={})=>{Array.isArray(n)||(n=[n]);for(let e of n)if(new Lr.Minimatch(e,t).hasMagic())return!0;return!1};ae.hasMagic=Wr});Object.defineProperty(exports, "__esModule", ({value:!0}));exports.glob=exports.sync=exports.iterate=exports.iterateSync=exports.stream=exports.streamSync=exports.Ignore=exports.hasMagic=exports.Glob=exports.unescape=exports.escape=void 0;exports.globStreamSync=xt;exports.globStream=Le;exports.globSync=We;exports.globIterateSync=Tt;exports.globIterate=Be;var Ws=H(),tt=je(),Br=Ne(),Is=H();Object.defineProperty(exports, "escape", ({enumerable:!0,get:function(){return Is.escape}}));Object.defineProperty(exports, "unescape", ({enumerable:!0,get:function(){return Is.unescape}}));var Ir=je();Object.defineProperty(exports, "Glob", ({enumerable:!0,get:function(){return Ir.Glob}}));var Gr=Ne();Object.defineProperty(exports, "hasMagic", ({enumerable:!0,get:function(){return Gr.hasMagic}}));var zr=ke();Object.defineProperty(exports, "Ignore", ({enumerable:!0,get:function(){return zr.Ignore}}));function xt(n,t={}){return new tt.Glob(n,t).streamSync()}function Le(n,t={}){return new tt.Glob(n,t).stream()}function We(n,t={}){return new tt.Glob(n,t).walkSync()}async function Bs(n,t={}){return new tt.Glob(n,t).walk()}function Tt(n,t={}){return new tt.Glob(n,t).iterateSync()}function Be(n,t={}){return new tt.Glob(n,t).iterate()}exports.streamSync=xt;exports.stream=Object.assign(Le,{sync:xt});exports.iterateSync=Tt;exports.iterate=Object.assign(Be,{sync:Tt});exports.sync=Object.assign(We,{stream:xt,iterate:Tt});exports.glob=Object.assign(Bs,{glob:Bs,globSync:We,sync:exports.sync,globStream:Le,stream:exports.stream,globStreamSync:xt,streamSync:exports.streamSync,globIterate:Be,iterate:exports.iterate,globIterateSync:Tt,iterateSync:exports.iterateSync,Glob:tt.Glob,hasMagic:Br.hasMagic,escape:Ws.escape,unescape:Ws.unescape});exports.glob.glob=exports.glob; +//# sourceMappingURL=index.min.js.map + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ // no module.id needed +/******/ // no module.loaded needed +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; +/******/ +/************************************************************************/ +/******/ +/******/ // startup +/******/ // Load entry module and return exports +/******/ // This entry module is referenced by other modules so it can't be inlined +/******/ var __webpack_exports__ = __nccwpck_require__(809); +/******/ module.exports = __webpack_exports__; +/******/ +/******/ })() +; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 2974f0e..9734b90 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,20 +1,18 @@ { "name": "inprod-run-changesets", - "version": "1.0.0", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "inprod-run-changesets", - "version": "1.0.0", + "version": "1.0.1", "license": "Apache-2.0", "dependencies": { - "@actions/core": "^1.10.1", - "@actions/github": "^6.0.0", - "glob": "^13.0.4", - "js-yaml": "^4.1.1" + "@actions/core": "^1.10.1" }, "devDependencies": { + "@inprod.io/run-changesets": "^1.1.1", "@vercel/ncc": "^0.38.1", "jest": "^30.2.0" }, @@ -41,21 +39,6 @@ "@actions/io": "^1.0.1" } }, - "node_modules/@actions/github": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@actions/github/-/github-6.0.1.tgz", - "integrity": "sha512-xbZVcaqD4XnQAe35qSQqskb3SqIAfRyLBrHMd/8TuL7hJSz2QtbDwnNM8zWx4zO5l2fnGtseNE3MbEvD7BxVMw==", - "license": "MIT", - "dependencies": { - "@actions/http-client": "^2.2.0", - "@octokit/core": "^5.0.1", - "@octokit/plugin-paginate-rest": "^9.2.2", - "@octokit/plugin-rest-endpoint-methods": "^10.4.0", - "@octokit/request": "^8.4.1", - "@octokit/request-error": "^5.1.1", - "undici": "^5.28.5" - } - }, "node_modules/@actions/http-client": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.3.tgz", @@ -103,7 +86,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -612,6 +594,23 @@ "node": ">=14" } }, + "node_modules/@inprod.io/run-changesets": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@inprod.io/run-changesets/-/run-changesets-1.1.1.tgz", + "integrity": "sha512-OuJL8lDxgs0qeb+kRRbUUvx5p5qOwZwl4gENEK3P3MJ19mcE7LiwszTW7nvV/ES74CyDAzX+l3VXx/CjILPHPg==", + "dev": true, + "license": "GPL-3.0", + "dependencies": { + "glob": "^13.0.6", + "js-yaml": "^4.3.0" + }, + "bin": { + "run-changesets": "src/index.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -1158,165 +1157,6 @@ "@tybys/wasm-util": "^0.10.0" } }, - "node_modules/@octokit/auth-token": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-4.0.0.tgz", - "integrity": "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==", - "license": "MIT", - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/core": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.2.tgz", - "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", - "license": "MIT", - "peer": true, - "dependencies": { - "@octokit/auth-token": "^4.0.0", - "@octokit/graphql": "^7.1.0", - "@octokit/request": "^8.4.1", - "@octokit/request-error": "^5.1.1", - "@octokit/types": "^13.0.0", - "before-after-hook": "^2.2.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/endpoint": { - "version": "9.0.6", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz", - "integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==", - "license": "MIT", - "dependencies": { - "@octokit/types": "^13.1.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/graphql": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-7.1.1.tgz", - "integrity": "sha512-3mkDltSfcDUoa176nlGoA32RGjeWjl3K7F/BwHwRMJUW/IteSa4bnSV8p2ThNkcIcZU2umkZWxwETSSCJf2Q7g==", - "license": "MIT", - "dependencies": { - "@octokit/request": "^8.4.1", - "@octokit/types": "^13.0.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/openapi-types": { - "version": "24.2.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-24.2.0.tgz", - "integrity": "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==", - "license": "MIT" - }, - "node_modules/@octokit/plugin-paginate-rest": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-9.2.2.tgz", - "integrity": "sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ==", - "license": "MIT", - "dependencies": { - "@octokit/types": "^12.6.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "@octokit/core": "5" - } - }, - "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/openapi-types": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", - "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==", - "license": "MIT" - }, - "node_modules/@octokit/plugin-paginate-rest/node_modules/@octokit/types": { - "version": "12.6.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", - "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^20.0.0" - } - }, - "node_modules/@octokit/plugin-rest-endpoint-methods": { - "version": "10.4.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-10.4.1.tgz", - "integrity": "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg==", - "license": "MIT", - "dependencies": { - "@octokit/types": "^12.6.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "@octokit/core": "5" - } - }, - "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/openapi-types": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-20.0.0.tgz", - "integrity": "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA==", - "license": "MIT" - }, - "node_modules/@octokit/plugin-rest-endpoint-methods/node_modules/@octokit/types": { - "version": "12.6.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-12.6.0.tgz", - "integrity": "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^20.0.0" - } - }, - "node_modules/@octokit/request": { - "version": "8.4.1", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz", - "integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==", - "license": "MIT", - "dependencies": { - "@octokit/endpoint": "^9.0.6", - "@octokit/request-error": "^5.1.1", - "@octokit/types": "^13.1.0", - "universal-user-agent": "^6.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/request-error": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz", - "integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==", - "license": "MIT", - "dependencies": { - "@octokit/types": "^13.1.0", - "deprecation": "^2.0.0", - "once": "^1.4.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@octokit/types": { - "version": "13.10.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-13.10.0.tgz", - "integrity": "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^24.2.0" - } - }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", @@ -1834,6 +1674,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, "license": "Python-2.0" }, "node_modules/babel-jest": { @@ -1952,16 +1793,11 @@ "baseline-browser-mapping": "dist/cli.js" } }, - "node_modules/before-after-hook": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", - "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==", - "license": "Apache-2.0" - }, "node_modules/brace-expansion": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.2.tgz", - "integrity": "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw==", + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" @@ -1970,40 +1806,14 @@ "node": "20 || >=22" } }, - "node_modules/brace-expansion/node_modules/@isaacs/cliui": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz", - "integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==", - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/brace-expansion/node_modules/balanced-match": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.2.tgz", - "integrity": "sha512-x0K50QvKQ97fdEz2kPehIerj+YTeptKF9hyYkKf6egnwmMWAkADiO0QCzSp0R5xN8FTZgYaBfSaue46Ej62nMg==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, "license": "MIT", - "dependencies": { - "jackspeak": "^4.2.3" - }, "engines": { - "node": "20 || >=22" - } - }, - "node_modules/brace-expansion/node_modules/jackspeak": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz", - "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^9.0.0" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": "18 || 20 || >=22" } }, "node_modules/braces": { @@ -2039,7 +1849,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -2350,12 +2159,6 @@ "node": ">=0.10.0" } }, - "node_modules/deprecation": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", - "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==", - "license": "ISC" - }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -2630,17 +2433,18 @@ } }, "node_modules/glob": { - "version": "13.0.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.4.tgz", - "integrity": "sha512-KACie1EOs9BIOMtenFaxwmYODWA3/fTfGSUnLhMJpXRntu1g+uL/Xvub5f8SCTppvo9q62Qy4LeOoUiaL54G5A==", + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^10.2.1", - "minipass": "^7.1.2", - "path-scurry": "^2.0.0" + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -3644,9 +3448,20 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], "license": "MIT", "dependencies": { "argparse": "^2.0.1" @@ -3799,25 +3614,27 @@ } }, "node_modules/minimatch": { - "version": "10.2.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.1.tgz", - "integrity": "sha512-MClCe8IL5nRRmawL6ib/eT4oLyeKMGCghibcDWK+J0hh0Q8kqSdia6BvbRMVk6mPa6WqUa5uR2oxt6C5jd533A==", + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.2" + "brace-expansion": "^5.0.5" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "license": "ISC", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, + "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" } @@ -3893,6 +3710,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" @@ -4026,25 +3844,27 @@ } }, "node_modules/path-scurry": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.1.tgz", - "integrity": "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.2.6", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.6.tgz", - "integrity": "sha512-ESL2CrkS/2wTPfuend7Zhkzo2u0daGJ/A2VucJOgQ/C48S/zB8MMeMHSGKYpXhIjbPxfuezITkaBH1wqv00DDQ==", + "version": "11.5.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.2.tgz", + "integrity": "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==", + "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": "20 || >=22" @@ -4618,12 +4438,6 @@ "dev": true, "license": "MIT" }, - "node_modules/universal-user-agent": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", - "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==", - "license": "ISC" - }, "node_modules/unrs-resolver": { "version": "1.11.1", "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz", @@ -4830,6 +4644,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, "license": "ISC" }, "node_modules/write-file-atomic": { diff --git a/package.json b/package.json index faa4baa..1a4fa04 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "GitHub Action to run InProd changesets against Genesys Cloud environments", "main": "dist/index.js", "scripts": { - "build": "ncc build src/index.js -o dist", + "build": "ncc build src/index.js -o dist && ncc build node_modules/@inprod.io/run-changesets/src/index.js -o dist/run-changesets", "test": "jest --verbose", "test:coverage": "jest --verbose --coverage" }, @@ -25,12 +25,10 @@ "node": ">=20.0.0" }, "dependencies": { - "@actions/core": "^1.10.1", - "@actions/github": "^6.0.0", - "glob": "^13.0.4", - "js-yaml": "^4.1.1" + "@actions/core": "^1.10.1" }, "devDependencies": { + "@inprod.io/run-changesets": "^1.1.1", "@vercel/ncc": "^0.38.1", "jest": "^30.2.0" } diff --git a/src/index.js b/src/index.js index 12be99e..8dbc27a 100644 --- a/src/index.js +++ b/src/index.js @@ -1,585 +1,82 @@ const core = require('@actions/core'); const fs = require('fs'); const path = require('path'); -const { globSync } = require('glob'); -const yaml = require('js-yaml'); +const { execFileSync } = require('child_process'); -async function pollTask(baseUrl, apiKey, taskId, label, pollingTimeoutSeconds) { - const pollInterval = 5; // seconds - const pollUrl = `${baseUrl}/api/v1/task-status/${taskId}/`; - let elapsed = 0; - - core.info(`${label} dispatched as background task (task_id: ${taskId})`); - core.info(`Polling for completion (interval: ${pollInterval}s, timeout: ${pollingTimeoutSeconds}s)...`); - - while (elapsed < pollingTimeoutSeconds) { - await new Promise(resolve => setTimeout(resolve, pollInterval * 1000)); - elapsed += pollInterval; - - try { - const pollResponse = await fetch(pollUrl, { - method: 'GET', - headers: { - 'Authorization': `Api-Key ${apiKey}`, - 'Content-Type': 'application/json' - } - }); - - if (!pollResponse.ok) { - const errorBody = await pollResponse.text(); - throw new Error( - `Poll failed with status ${pollResponse.status}: ${errorBody || pollResponse.statusText}` - ); - } - - const pollData = await pollResponse.json(); - core.debug(`Poll response: ${JSON.stringify(pollData)}`); - - const status = pollData.status; - core.info(` ${label} status: ${status} (${elapsed}s elapsed)`); - - if (status === 'SUCCESS') { - core.info(`${label} completed successfully`); - return { status: 'SUCCESS', result: pollData.result || {} }; - } else if (status === 'FAILURE') { - const error = pollData.error || 'Unknown error'; - return { status: 'FAILURE', error }; - } else if (status === 'REVOKED') { - return { status: 'REVOKED' }; - } - // PENDING, STARTED, RETRY — continue polling - } catch (e) { - if (e.message && (e.message.includes('Poll failed'))) { - throw e; - } - core.warning(`Error during polling: ${e.message}. Retrying...`); - core.debug(`Poll error details: ${e.stack}`); - } - } - - return { status: 'TIMEOUT' }; -} - -function buildUrl(baseUrl, endpoint, environment) { - const envParam = environment ? `?environment=${encodeURIComponent(environment)}` : ''; - return `${baseUrl}${endpoint}${envParam}`; -} - -function injectYamlVariables(content, changesetVariables) { - const doc = yaml.load(content); - - // Determine mask_value for each injected variable based on existing entries - const existingVars = Array.isArray(doc.variable) ? doc.variable : []; - const injectedVars = Object.entries(changesetVariables).map(([name, value]) => { - // Check if this variable exists in the changeset - const existingEntries = existingVars.filter(v => v.name === name); - // If any existing entry has mask_value: true, preserve that; otherwise use false - const maskValue = existingEntries.some(v => v.mask_value === true) ? true : false; - return { - environment: null, - mask_value: maskValue, - name, - value, - }; - }); - - // Remove all existing entries for variables we're overriding - const overrideNames = new Set(Object.keys(changesetVariables)); - const keptVars = existingVars.filter(v => !overrideNames.has(v.name)); - - doc.variable = [...keptVars, ...injectedVars]; - - return yaml.dump(doc, { lineWidth: -1, noRefs: true }); -} - -function injectJsonVariables(content, changesetVariables) { - const doc = JSON.parse(content); - - // Determine mask_value for each injected variable based on existing entries - const existingVars = Array.isArray(doc.variable) ? doc.variable : []; - const injectedVars = Object.entries(changesetVariables).map(([name, value]) => { - // Check if this variable exists in the changeset - const existingEntries = existingVars.filter(v => v.name === name); - // If any existing entry has mask_value: true, preserve that; otherwise use false - const maskValue = existingEntries.some(v => v.mask_value === true) ? true : false; - return { - environment: null, - mask_value: maskValue, - name, - value, - }; - }); - - // Remove all existing entries for variables we're overriding - const overrideNames = new Set(Object.keys(changesetVariables)); - const keptVars = existingVars.filter(v => !overrideNames.has(v.name)); - - doc.variable = [...keptVars, ...injectedVars]; - - return JSON.stringify(doc, null, 2); -} - -function getFileFormat(filePath) { - const ext = path.extname(filePath).toLowerCase(); - if (ext === '.json') return 'json'; - return 'yaml'; // .yaml, .yml, or any other extension defaults to yaml -} - -function isGlobPattern(pattern) { - return /[*?[\]{}]/.test(pattern); -} - -function resolveFiles(changesetFile) { - if (!changesetFile || changesetFile.trim() === '') { - throw new Error('changeset_file is required'); - } - - if (isGlobPattern(changesetFile)) { - // Normalize to forward slashes for cross-platform glob compatibility - const normalizedPattern = changesetFile.replace(/\\/g, '/'); - const matches = globSync(normalizedPattern, { nodir: true }); - if (matches.length === 0) { - throw new Error(`No files matched the pattern: ${changesetFile}`); - } - const filePaths = matches - .map(f => path.resolve(f)) - .sort((a, b) => path.basename(a).localeCompare(path.basename(b))); - core.info(`Matched ${filePaths.length} file(s) for pattern: ${changesetFile}`); - filePaths.forEach((f, i) => core.info(` [${i + 1}] ${path.basename(f)}`)); - return filePaths; - } - - const filePath = path.resolve(changesetFile); - if (!fs.existsSync(filePath)) { - throw new Error(`Changeset file not found: ${filePath}`); - } - return [filePath]; -} - -// Validate a single changeset file. Returns { taskId, status, result } or throws. -async function validateFile(filePath, options) { - const { apiKey, baseUrl, environment, pollingTimeoutSeconds, changesetVariables } = options; - const content = fs.readFileSync(filePath, 'utf8'); - const format = getFileFormat(filePath); - const endpoint = format === 'json' - ? '/api/v1/change-set/change-set/validate_json/' - : '/api/v1/change-set/change-set/validate_yaml/'; - const validateUrl = buildUrl(baseUrl, endpoint, environment); - - core.debug(`Validate URL: ${validateUrl} (format: ${format})`); - - // Build request body and content type based on file format - let body, contentType; - if (format === 'json') { - contentType = 'application/json'; - body = changesetVariables ? injectJsonVariables(content, changesetVariables) : content; - } else { - contentType = 'application/yaml'; - body = changesetVariables ? injectYamlVariables(content, changesetVariables) : content; - } - - core.debug(`Sending validation request to: ${validateUrl}`); - let validateResponse; - try { - validateResponse = await fetch(validateUrl, { - method: 'POST', - headers: { - 'Authorization': `Api-Key ${apiKey}`, - 'Content-Type': contentType - }, - body - }); - core.debug(`API response status: ${validateResponse.status}`); - } catch (error) { - core.error(`Network error connecting to InProd API: ${error.message}`); - core.debug(`Full error details: ${error.stack}`); - throw new Error(`Failed to connect to InProd API at ${validateUrl}: ${error.message}`); - } - - if (!validateResponse.ok) { - const errorBody = await validateResponse.text(); - throw new Error( - `Validation request failed with status ${validateResponse.status}: ${errorBody || validateResponse.statusText}` - ); - } - - const validateData = await validateResponse.json(); - core.debug(`Validate response: ${JSON.stringify(validateData)}`); - - let validateTaskId; - try { - validateTaskId = validateData.data.attributes.task_id; - } catch (e) { - throw new Error( - `Failed to extract task_id from validation response. Response: ${JSON.stringify(validateData)}` - ); - } - - if (!validateTaskId || validateTaskId.trim() === '') { - throw new Error('Validation API returned an empty task_id'); - } - - const validateResult = await pollTask(baseUrl, apiKey, validateTaskId, 'Validation', pollingTimeoutSeconds); - - if (validateResult.status === 'TIMEOUT') { - return { taskId: validateTaskId, status: 'TIMEOUT', result: {}, error: `Validation did not complete within ${pollingTimeoutSeconds} seconds` }; - } - if (validateResult.status === 'FAILURE') { - return { status: 'FAILURE', result: {}, error: `Validation failed: ${validateResult.error}` }; - } - if (validateResult.status === 'REVOKED') { - return { status: 'REVOKED', result: {}, error: 'Validation task was cancelled' }; - } - - const isValid = validateResult.result.is_valid; - if (!isValid) { - const validationErrors = JSON.stringify(validateResult.result.validation_results || [], null, 2); - core.error(`Validation errors:\n${validationErrors}`); - return { status: 'FAILURE', result: validateResult.result, error: 'Changeset validation failed. See validation errors above.' }; - } - - core.info(`✓ Validation passed`); - if (validateResult.result.changeset_name) { - core.info(` Changeset: ${validateResult.result.changeset_name}`); - } - if (validateResult.result.environment) { - core.info(` Environment: ${JSON.stringify(validateResult.result.environment)}`); - } - - return { status: 'SUCCESS', result: validateResult.result }; -} - -// Execute a single changeset file. Returns { taskId, status, result } or throws. -async function executeFile(filePath, options) { - const { apiKey, baseUrl, environment, pollingTimeoutSeconds, changesetVariables } = options; - const content = fs.readFileSync(filePath, 'utf8'); - const format = getFileFormat(filePath); - const endpoint = format === 'json' - ? '/api/v1/change-set/change-set/execute_json/' - : '/api/v1/change-set/change-set/execute_yaml/'; - const executeUrl = buildUrl(baseUrl, endpoint, environment); - - core.debug(`Execute URL: ${executeUrl} (format: ${format})`); - - // Build request body and content type based on file format - let body, contentType; - if (format === 'json') { - contentType = 'application/json'; - body = changesetVariables ? injectJsonVariables(content, changesetVariables) : content; - } else { - contentType = 'application/yaml'; - body = changesetVariables ? injectYamlVariables(content, changesetVariables) : content; - } - - core.debug(`Sending API request to: ${executeUrl}`); - let executeResponse; - try { - executeResponse = await fetch(executeUrl, { - method: 'POST', - headers: { - 'Authorization': `Api-Key ${apiKey}`, - 'Content-Type': contentType - }, - body - }); - core.debug(`API response status: ${executeResponse.status}`); - } catch (error) { - core.error(`Network error connecting to InProd API: ${error.message}`); - core.debug(`Full error details: ${error.stack}`); - throw new Error(`Failed to connect to InProd API at ${executeUrl}: ${error.message}`); - } - - if (!executeResponse.ok) { - const errorBody = await executeResponse.text(); - throw new Error( - `API request failed with status ${executeResponse.status}: ${errorBody || executeResponse.statusText}` - ); - } - - const executeData = await executeResponse.json(); - core.debug(`Execute response: ${JSON.stringify(executeData)}`); - - let taskId; - try { - taskId = executeData.data.attributes.task_id; - } catch (e) { - throw new Error( - `Failed to extract task_id from API response. Response: ${JSON.stringify(executeData)}` - ); - } - - if (!taskId || taskId.trim() === '') { - throw new Error('API returned an empty task_id'); - } - - core.info(`✓ Changeset submitted successfully`); - - const pollResult = await pollTask(baseUrl, apiKey, taskId, 'Execution', pollingTimeoutSeconds); - - if (pollResult.status === 'SUCCESS') { - core.info(`✓ Changeset executed successfully`); - return { status: 'SUCCESS', result: pollResult.result }; - } else if (pollResult.status === 'FAILURE') { - core.error(`✗ Task failed: ${pollResult.error}`); - return { status: 'FAILURE', result: {}, error: `Changeset execution failed: ${pollResult.error}` }; - } else if (pollResult.status === 'REVOKED') { - core.warning(`⚠ Task was cancelled/revoked`); - return { status: 'REVOKED', result: {}, error: 'Changeset execution was cancelled' }; - } else if (pollResult.status === 'TIMEOUT') { - return { status: 'TIMEOUT', result: {}, error: `Changeset execution did not complete within ${pollingTimeoutSeconds} seconds` }; - } - - return { status: pollResult.status, result: {} }; -} - -// Process a single file through the full flow (validate + execute). -// Returns { file, status, result }. -async function processSingleFile(filePath, options) { - const { validateBeforeExecute, validateOnly } = options; - const fileName = path.basename(filePath); - - core.info(`Read changeset from file: ${fileName}`); - - // Step 1: Validate (if needed) - if (validateOnly || validateBeforeExecute) { - core.info('Validating changeset...'); - const valResult = await validateFile(filePath, options); - - if (valResult.status !== 'SUCCESS') { - return { file: filePath, status: valResult.status, result: valResult.result, error: valResult.error }; - } - - if (validateOnly) { - return { file: filePath, status: 'SUCCESS', result: valResult.result }; - } - } - - // Step 2: Execute - core.info('Submitting changeset for execution...'); - const execResult = await executeFile(filePath, options); - - if (execResult.error) { - return { file: filePath, status: execResult.status, result: execResult.result, error: execResult.error }; - } - - if (execResult.result.run_id) { - core.info(`Run ID: ${execResult.result.run_id}`); - } - if (execResult.result.changeset_name) { - core.info(`Changeset: ${execResult.result.changeset_name}`); - } - if (execResult.result.environment) { - core.info(`Environment: ${JSON.stringify(execResult.result.environment)}`); - } - - return { file: filePath, status: execResult.status, result: execResult.result }; -} - -const STATUS_PRIORITY = { FAILURE: 0, TIMEOUT: 1, REVOKED: 2, SUBMITTED: 3, SUCCESS: 4 }; - -function worstStatus(results) { - return results.reduce((worst, r) => { - return (STATUS_PRIORITY[r.status] ?? 99) < (STATUS_PRIORITY[worst] ?? 99) ? r.status : worst; - }, 'SUCCESS'); -} +// This file is a pure adapter: it translates GitHub Actions inputs into the INPROD_* +// environment variables the run-changesets CLI (@inprod.io/run-changesets) already reads, +// spawns it, and translates the result files it already writes back into Action outputs. +// No changeset logic lives here — that all lives in run-changesets, referenced unmodified. async function run() { try { - // Get inputs (fall back to environment variables for api_key and base_url) const apiKey = core.getInput('api_key') || process.env.INPROD_API_KEY || ''; - const baseUrl = (core.getInput('base_url') || process.env.INPROD_BASE_URL || '').replace(/\/$/, ''); - const changesetFile = core.getInput('changeset_file', { required: true }); - const environment = core.getInput('environment'); - const validateBeforeExecute = core.getInput('validate_before_execute') !== 'false'; - const validateOnly = core.getInput('validate_only') === 'true'; - const pollingTimeoutMinutes = parseInt(core.getInput('polling_timeout_minutes'), 10) || 10; - const pollingTimeoutSeconds = pollingTimeoutMinutes * 60; - const executionStrategy = core.getInput('execution_strategy') || 'per_file'; - const failFast = core.getInput('fail_fast') === 'true'; - const changesetVariablesInput = core.getInput('changeset_variables'); - - // Parse changeset variables from KEY=VALUE format - let changesetVariables = null; - if (changesetVariablesInput && changesetVariablesInput.trim()) { - changesetVariables = {}; - const lines = changesetVariablesInput.trim().split('\n'); - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) continue; // Skip empty lines and comments - const [key, ...valueParts] = trimmed.split('='); - if (!key || valueParts.length === 0) { - throw new Error(`Invalid changeset_variables format. Expected KEY=VALUE on each line, got: ${trimmed}`); - } - changesetVariables[key.trim()] = valueParts.join('=').trim(); // Handle values with = in them - } - core.debug(`Parsed changeset variables: ${JSON.stringify(Object.keys(changesetVariables))} (values masked)`); - } - - // Mask sensitive values in logs + const baseUrl = core.getInput('base_url') || process.env.INPROD_BASE_URL || ''; core.setSecret(apiKey); - // Validate inputs - if (!apiKey || apiKey.trim() === '') { - throw new Error('api_key is required and cannot be empty'); - } - if (!baseUrl || baseUrl.trim() === '') { - throw new Error('base_url is required and cannot be empty'); - } - - // Validate URL format - try { - new URL(baseUrl); - } catch (e) { - throw new Error(`Invalid base_url format: ${baseUrl}`); - } - - // Resolve changeset files - const filePaths = resolveFiles(changesetFile); - - const options = { - apiKey, baseUrl, environment, validateBeforeExecute, validateOnly, - pollingTimeoutSeconds, changesetVariables, + const env = { + ...process.env, + INPROD_API_KEY: apiKey, + INPROD_BASE_URL: baseUrl, + INPROD_CHANGESET_FILE: core.getInput('changeset_file', { required: true }), + INPROD_ENVIRONMENT: core.getInput('environment'), + INPROD_VALIDATE_BEFORE_EXECUTE: core.getInput('validate_before_execute'), + INPROD_VALIDATE_ONLY: core.getInput('validate_only'), + INPROD_POLLING_TIMEOUT_MINUTES: core.getInput('polling_timeout_minutes'), + INPROD_EXECUTION_STRATEGY: core.getInput('execution_strategy'), + INPROD_FAIL_FAST: core.getInput('fail_fast'), + INPROD_CHANGESET_VARIABLES: core.getInput('changeset_variables'), + INPROD_FILES: core.getInput('inprod_files') || process.env.INPROD_FILES || '', }; - - core.info(`InProd Run Changesets Action v1`); - core.info(`Base URL: ${baseUrl}`); - if (environment) { - core.info(`Target environment: ${environment}`); + if (core.isDebug()) { + env.INPROD_DEBUG = 'true'; } - core.info(`Files to process: ${filePaths.length}`); - core.info(`Execution strategy: ${executionStrategy}`); - core.info(`Fail fast: ${failFast}`); - core.info(`Validate before execute: ${validateBeforeExecute}`); - core.info(`Validate only: ${validateOnly}`); - core.info(`Polling timeout: ${pollingTimeoutMinutes} minutes (${pollingTimeoutSeconds} seconds)`); - if (changesetVariables) { - core.info(`Changeset variables: ${Object.keys(changesetVariables).length} variable(s) provided`); - } - - const results = []; - - if (executionStrategy === 'validate_first' && !validateOnly && validateBeforeExecute) { - // Phase 1: Validate all files - for (let i = 0; i < filePaths.length; i++) { - const filePath = filePaths[i]; - const fileName = path.basename(filePath); - core.info(`\n--- Validating [${i + 1}/${filePaths.length}]: ${fileName} ---`); - try { - const valResult = await validateFile(filePath, options); - if (valResult.status !== 'SUCCESS') { - results.push({ file: filePath, taskId: valResult.taskId, status: valResult.status, result: valResult.result, error: valResult.error }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed validation.`); - break; - } - continue; - } - } catch (error) { - results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed validation.`); - break; - } - continue; - } - } - - // If any validation failed, stop before executing - const validationFailures = results.filter(r => r.status !== 'SUCCESS'); - if (validationFailures.length > 0) { - // Set outputs and fail - core.setOutput('status', 'FAILURE'); - const resultArray = results.map(r => ({ - file: path.basename(r.file), - status: r.status, - result: r.result || {}, - error: r.error || null, - })); - core.setOutput('result', JSON.stringify(resultArray)); - const msg = validationFailures.length === 1 - ? validationFailures[0].error - : `${validationFailures.length} of ${filePaths.length} changeset(s) failed validation. See result output for details.`; - throw new Error(msg); - } - core.info(`\n✓ All ${filePaths.length} file(s) passed validation. Starting execution...`); + const entryPoint = path.join(__dirname, 'run-changesets', 'index.js'); - // Phase 2: Execute all files (skip re-validation) - const executeOptions = { ...options, validateBeforeExecute: false, validateOnly: false }; - for (let i = 0; i < filePaths.length; i++) { - const filePath = filePaths[i]; - const fileName = path.basename(filePath); - core.info(`\n--- Executing [${i + 1}/${filePaths.length}]: ${fileName} ---`); - try { - const fileResult = await processSingleFile(filePath, executeOptions); - results.push(fileResult); - if (fileResult.error && failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } catch (error) { - results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } - } - } else { - // per_file strategy: full flow for each file sequentially - for (let i = 0; i < filePaths.length; i++) { - const filePath = filePaths[i]; - const fileName = path.basename(filePath); - core.info(`\n--- Processing [${i + 1}/${filePaths.length}]: ${fileName} ---`); - try { - const fileResult = await processSingleFile(filePath, options); - results.push(fileResult); - if (fileResult.error && failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } catch (error) { - results.push({ file: filePath, status: 'FAILURE', result: {}, error: error.message }); - if (failFast) { - core.error(`Stopping: fail_fast is enabled and ${fileName} failed.`); - break; - } - } - } + let spawnError = null; + try { + // stdio: 'inherit' streams run-changesets's own console output directly into the + // Action's job log in real time, exactly as it does when run as a CLI. + execFileSync(process.execPath, [entryPoint], { env, stdio: 'inherit' }); + } catch (err) { + spawnError = err; // non-zero exit — run-changesets already logged its own error above } - // Set aggregate outputs - const aggregateStatus = worstStatus(results); - core.setOutput('status', aggregateStatus); - - const resultArray = results.map(r => ({ - file: path.basename(r.file), - status: r.status, - result: r.result || {}, - error: r.error || null, - })); - core.setOutput('result', JSON.stringify(resultArray)); - - core.info(`\nAction completed with status: ${aggregateStatus}`); - - // Fail the action if any file had a non-success status - if (aggregateStatus === 'FAILURE' || aggregateStatus === 'TIMEOUT' || aggregateStatus === 'REVOKED') { - const failedFiles = results.filter(r => r.status !== 'SUCCESS' && r.status !== 'SUBMITTED'); - const msg = failedFiles.length === 1 - ? failedFiles[0].error - : `${failedFiles.length} of ${results.length} changeset(s) failed. See result output for details.`; - throw new Error(msg); + const resultPath = path.join(process.cwd(), 'inprod-result.json'); + const statusPath = path.join(process.cwd(), 'inprod-results.env'); + + if (fs.existsSync(resultPath) && fs.existsSync(statusPath)) { + const resultArray = JSON.parse(fs.readFileSync(resultPath, 'utf8')); + const status = fs.readFileSync(statusPath, 'utf8').match(/INPROD_STATUS=(\w+)/)[1]; + fs.unlinkSync(resultPath); + fs.unlinkSync(statusPath); + + core.setOutput('status', status); + core.setOutput('result', JSON.stringify(resultArray)); + + if (spawnError) { + const failedFiles = resultArray.filter(r => r.status !== 'SUCCESS' && r.status !== 'SUBMITTED'); + const msg = failedFiles.length === 1 + ? failedFiles[0].error + : `${failedFiles.length} of ${resultArray.length} changeset(s) failed. See result output for details.`; + core.setFailed(msg); + process.exit(1); + } + } else if (spawnError) { + // run-changesets failed before it could write result files (e.g. bad input, missing + // changeset file) — see the job log above (streamed via stdio: 'inherit') for the reason. + core.setFailed(`run-changesets exited with code ${spawnError.status ?? 1}. See the job log above for details.`); + process.exit(1); } - } catch (error) { core.error(`Action failed: ${error.message}`); - core.debug(`Error stack: ${error.stack}`); core.setFailed(error.message); process.exit(1); } } -module.exports = { run, pollTask, buildUrl, isGlobPattern, resolveFiles, worstStatus, getFileFormat, injectYamlVariables, injectJsonVariables }; +module.exports = { run }; /* istanbul ignore next */ if (require.main === module) { diff --git a/src/index.test.js b/src/index.test.js index 8bd5194..fb686be 100644 --- a/src/index.test.js +++ b/src/index.test.js @@ -1,15 +1,16 @@ -const fs = require('fs'); -const path = require('path'); +// This action is a pure adapter over the run-changesets CLI (@inprod.io/run-changesets): +// it maps GitHub Actions inputs to the INPROD_* env vars the CLI reads, spawns it, and maps +// the result files it writes back into Action outputs. All changeset logic (validation, +// execution, polling, etc.) lives in that dependency and is tested there, not here. -// Mock process.exit to prevent Jest from dying const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {}); -// Mock @actions/core const mockCore = { getInput: jest.fn(), setOutput: jest.fn(), setSecret: jest.fn(), setFailed: jest.fn(), + isDebug: jest.fn(), info: jest.fn(), error: jest.fn(), warning: jest.fn(), @@ -17,1864 +18,251 @@ const mockCore = { }; jest.mock('@actions/core', () => mockCore); -// Mock global fetch -const mockFetch = jest.fn(); -global.fetch = mockFetch; +const mockExecFileSync = jest.fn(); +jest.mock('child_process', () => ({ execFileSync: mockExecFileSync })); -const { run, pollTask, buildUrl, isGlobPattern, resolveFiles, worstStatus, getFileFormat, injectYamlVariables, injectJsonVariables } = require('./index'); +const mockFs = { + existsSync: jest.fn(), + readFileSync: jest.fn(), + unlinkSync: jest.fn(), +}; +jest.mock('fs', () => mockFs); -// Helpers -function mockInputs(inputs) { - mockCore.getInput.mockImplementation((name) => inputs[name] || ''); -} +const { run } = require('./index'); -function mockFetchResponse(status, body, ok = true) { - return { - ok, - status, - statusText: ok ? 'OK' : 'Error', - json: jest.fn().mockResolvedValue(body), - text: jest.fn().mockResolvedValue(typeof body === 'string' ? body : JSON.stringify(body)), - }; +function mockInputs(inputs) { + mockCore.getInput.mockImplementation((name) => inputs[name] ?? ''); } -function validationTaskResponse(taskId = 'val-task-123') { - return { - data: { - attributes: { - title: 'Validation in progress', - task_id: taskId, - } - } - }; -} +const DEFAULT_INPUTS = { + api_key: 'test-api-key', + base_url: 'https://your-company.inprod.io', + changeset_file: 'changesets/test.yaml', + environment: '', + validate_before_execute: 'true', + validate_only: 'false', + polling_timeout_minutes: '10', + execution_strategy: 'per_file', + fail_fast: 'false', + changeset_variables: '', + inprod_files: '', +}; -function executeTaskResponse(taskId = 'exec-task-456', runId = 42) { +function resultFiles({ status = 'SUCCESS', results = [] } = {}) { return { - data: { - attributes: { - title: 'Processing...', - run_id: runId, - successful: null, - task_id: taskId, - } - } + 'inprod-result.json': JSON.stringify(results), + 'inprod-results.env': `INPROD_STATUS=${status}\n`, }; } -function successPollResponse(result = {}) { - return { status: 'SUCCESS', result }; -} - -function failurePollResponse(error = 'Something went wrong') { - return { status: 'FAILURE', error }; -} - -function pendingPollResponse() { - return { status: 'PENDING' }; -} - -function startedPollResponse() { - return { status: 'STARTED' }; -} - -function revokedPollResponse() { - return { status: 'REVOKED' }; +function mockResultFiles(files) { + mockFs.existsSync.mockImplementation((p) => Object.keys(files).some((name) => p.endsWith(name))); + mockFs.readFileSync.mockImplementation((p) => { + const match = Object.entries(files).find(([name]) => p.endsWith(name)); + return match[1]; + }); } -const SAMPLE_CHANGESET = `name: Test Queue -environment: Development -enforcing: true -run_type: stop -action: - - action: gencloud-create - object_type: RoutingQueue - data: - name: Test Queue -variable: []`; - -const SAMPLE_CHANGESET_FILE = path.join(__dirname, '__test_changeset_sample__.yaml'); -const SAMPLE_BASENAME = '__test_changeset_sample__.yaml'; - -// Additional files for glob testing -const GLOB_FILE_01 = path.join(__dirname, '__test_01_queues__.yaml'); -const GLOB_FILE_02 = path.join(__dirname, '__test_02_flows__.yaml'); -const GLOB_FILE_03 = path.join(__dirname, '__test_03_webchat__.yaml'); - -// Helper to build expected result array for a single file -function singleResultArray(status, result, error = null) { - return JSON.stringify([{ - file: SAMPLE_BASENAME, - status, - result: result || {}, - error, - }]); +function mockNoResultFiles() { + mockFs.existsSync.mockReturnValue(false); } -beforeAll(() => { - fs.writeFileSync(SAMPLE_CHANGESET_FILE, SAMPLE_CHANGESET); - fs.writeFileSync(GLOB_FILE_01, SAMPLE_CHANGESET); - fs.writeFileSync(GLOB_FILE_02, SAMPLE_CHANGESET); - fs.writeFileSync(GLOB_FILE_03, SAMPLE_CHANGESET); -}); - -afterAll(() => { - [SAMPLE_CHANGESET_FILE, GLOB_FILE_01, GLOB_FILE_02, GLOB_FILE_03].forEach(f => { - if (fs.existsSync(f)) fs.unlinkSync(f); - }); -}); - beforeEach(() => { jest.clearAllMocks(); - jest.useFakeTimers(); - mockExit.mockClear(); -}); - -afterEach(() => { - jest.useRealTimers(); -}); - -// ─── buildUrl ─────────────────────────────────────────────────────────────── - -describe('buildUrl', () => { - test('builds URL without environment parameter', () => { - const url = buildUrl('https://test.inprod.io', '/api/v1/change-set/change-set/execute_yaml/', ''); - expect(url).toBe('https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/'); - }); - - test('builds URL without environment parameter when undefined', () => { - const url = buildUrl('https://test.inprod.io', '/api/v1/change-set/change-set/execute_yaml/', undefined); - expect(url).toBe('https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/'); - }); - - test('appends environment name as query parameter', () => { - const url = buildUrl('https://test.inprod.io', '/api/v1/change-set/change-set/execute_yaml/', 'Production'); - expect(url).toBe('https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/?environment=Production'); - }); - - test('appends environment ID as query parameter', () => { - const url = buildUrl('https://test.inprod.io', '/api/v1/change-set/change-set/validate_yaml/', '3'); - expect(url).toBe('https://test.inprod.io/api/v1/change-set/change-set/validate_yaml/?environment=3'); - }); - - test('URL-encodes environment names with spaces', () => { - const url = buildUrl('https://test.inprod.io', '/api/v1/change-set/change-set/execute_yaml/', 'My Env'); - expect(url).toBe('https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/?environment=My%20Env'); - }); -}); - -// ─── isGlobPattern ────────────────────────────────────────────────────────── - -describe('isGlobPattern', () => { - test('returns false for plain file paths', () => { - expect(isGlobPattern('changesets/deploy-queue.yaml')).toBe(false); - expect(isGlobPattern('/absolute/path/file.yaml')).toBe(false); - expect(isGlobPattern('file.yaml')).toBe(false); - }); - - test('returns true for glob patterns', () => { - expect(isGlobPattern('changesets/*.yaml')).toBe(true); - expect(isGlobPattern('changesets/**/*.yaml')).toBe(true); - expect(isGlobPattern('changesets/deploy-?.yaml')).toBe(true); - expect(isGlobPattern('changesets/{a,b}.yaml')).toBe(true); - expect(isGlobPattern('changesets/[01]*.yaml')).toBe(true); - }); -}); - -// ─── resolveFiles ─────────────────────────────────────────────────────────── - -describe('resolveFiles', () => { - test('throws when changeset_file is empty', () => { - expect(() => resolveFiles('')).toThrow('changeset_file is required'); - }); - - test('throws when plain file path does not exist', () => { - expect(() => resolveFiles('/nonexistent/file.yaml')).toThrow('Changeset file not found'); - }); - - test('resolves a single plain file path', () => { - const files = resolveFiles(SAMPLE_CHANGESET_FILE); - expect(files).toEqual([path.resolve(SAMPLE_CHANGESET_FILE)]); - }); - - test('resolves glob pattern and sorts by basename', () => { - const pattern = path.join(__dirname, '__test_0*__.yaml'); - const files = resolveFiles(pattern); - expect(files.length).toBe(3); - expect(path.basename(files[0])).toBe('__test_01_queues__.yaml'); - expect(path.basename(files[1])).toBe('__test_02_flows__.yaml'); - expect(path.basename(files[2])).toBe('__test_03_webchat__.yaml'); - }); - - test('throws when glob pattern matches no files', () => { - expect(() => resolveFiles(path.join(__dirname, '__nonexistent_glob_*__.yaml'))).toThrow('No files matched the pattern'); - }); -}); - -// ─── worstStatus ──────────────────────────────────────────────────────────── - -describe('worstStatus', () => { - test('returns SUCCESS when all succeed', () => { - expect(worstStatus([{ status: 'SUCCESS' }, { status: 'SUCCESS' }])).toBe('SUCCESS'); - }); - - test('returns FAILURE when any fails', () => { - expect(worstStatus([{ status: 'SUCCESS' }, { status: 'FAILURE' }])).toBe('FAILURE'); - }); - - test('FAILURE beats TIMEOUT', () => { - expect(worstStatus([{ status: 'TIMEOUT' }, { status: 'FAILURE' }])).toBe('FAILURE'); - }); - - test('TIMEOUT beats REVOKED', () => { - expect(worstStatus([{ status: 'REVOKED' }, { status: 'TIMEOUT' }])).toBe('TIMEOUT'); - }); - - test('REVOKED beats SUBMITTED', () => { - expect(worstStatus([{ status: 'SUBMITTED' }, { status: 'REVOKED' }])).toBe('REVOKED'); - }); - - test('SUBMITTED beats SUCCESS', () => { - expect(worstStatus([{ status: 'SUCCESS' }, { status: 'SUBMITTED' }])).toBe('SUBMITTED'); - }); - - test('returns SUCCESS for empty results', () => { - expect(worstStatus([])).toBe('SUCCESS'); - }); -}); - -// ─── pollTask ─────────────────────────────────────────────────────────────── - -describe('pollTask', () => { - // Helper to advance timers past the poll interval - async function advancePoll() { - await jest.advanceTimersByTimeAsync(5000); - } - - test('returns SUCCESS when task completes successfully', async () => { - const result = { run_id: 1, successful: true }; - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(result))); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60); - await advancePoll(); - const outcome = await promise; - - expect(outcome).toEqual({ status: 'SUCCESS', result }); - expect(mockFetch).toHaveBeenCalledWith( - 'https://test.inprod.io/api/v1/task-status/task-1/', - expect.objectContaining({ method: 'GET' }) - ); - }); - - test('returns FAILURE when task fails', async () => { - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, failurePollResponse('Boom'))); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60); - await advancePoll(); - const outcome = await promise; - - expect(outcome).toEqual({ status: 'FAILURE', error: 'Boom' }); - }); - - test('returns FAILURE with default error message', async () => { - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, { status: 'FAILURE' })); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60); - await advancePoll(); - const outcome = await promise; - - expect(outcome).toEqual({ status: 'FAILURE', error: 'Unknown error' }); - }); - - test('returns REVOKED when task is cancelled', async () => { - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, revokedPollResponse())); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60); - await advancePoll(); - const outcome = await promise; - - expect(outcome).toEqual({ status: 'REVOKED' }); - }); - - test('continues polling on PENDING then returns SUCCESS', async () => { - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, pendingPollResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, startedPollResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse({ run_id: 5 }))); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60); - await advancePoll(); // PENDING - await advancePoll(); // STARTED - await advancePoll(); // SUCCESS - const outcome = await promise; - - expect(outcome).toEqual({ status: 'SUCCESS', result: { run_id: 5 } }); - expect(mockFetch).toHaveBeenCalledTimes(3); - }); - - test('returns TIMEOUT when polling exceeds timeout', async () => { - // Timeout of 10s, poll interval 5s = 2 polls max - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, pendingPollResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, pendingPollResponse())); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 10); - await advancePoll(); // 5s — PENDING - await advancePoll(); // 10s — PENDING, now >= timeout - const outcome = await promise; - - expect(outcome).toEqual({ status: 'TIMEOUT' }); - }); - - test('throws on non-ok HTTP response from poll', async () => { - jest.useRealTimers(); - mockFetch.mockResolvedValueOnce(mockFetchResponse(500, 'Internal Server Error', false)); - - // Use a very short timeout so the real timer resolves quickly - // pollInterval is 5s but we mock setTimeout behavior via real timers here - const originalSetTimeout = globalThis.setTimeout; - jest.spyOn(globalThis, 'setTimeout').mockImplementation((fn) => originalSetTimeout(fn, 0)); - - await expect( - pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60) - ).rejects.toThrow('Poll failed with status 500'); - - globalThis.setTimeout.mockRestore(); - jest.useFakeTimers(); - }); - - test('retries on transient network errors', async () => { - mockFetch - .mockRejectedValueOnce(new Error('Network error')) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse({ run_id: 7 }))); - - const promise = pollTask('https://test.inprod.io', 'key', 'task-1', 'Execution', 60); - await advancePoll(); // Network error — retry - await advancePoll(); // SUCCESS - const outcome = await promise; - - expect(outcome).toEqual({ status: 'SUCCESS', result: { run_id: 7 } }); - expect(mockCore.warning).toHaveBeenCalledWith(expect.stringContaining('Network error')); - }); - - test('sends correct authorization header', async () => { - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, successPollResponse({}))); - - const promise = pollTask('https://test.inprod.io', 'my-secret-key', 'task-1', 'Test', 60); - await advancePoll(); - await promise; - - expect(mockFetch).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ - headers: expect.objectContaining({ - 'Authorization': 'Api-Key my-secret-key' - }) - }) - ); - }); + mockCore.isDebug.mockReturnValue(false); + mockInputs(DEFAULT_INPUTS); }); -// ─── run() — Input Validation ─────────────────────────────────────────────── - -describe('run — input validation', () => { - test('fails when api_key is empty', async () => { - mockInputs({ api_key: '', base_url: 'https://test.inprod.io', changeset_file: SAMPLE_CHANGESET_FILE }); +describe('run() — env var mapping', () => { + test('maps Action inputs to the INPROD_* env vars run-changesets reads', async () => { + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith('api_key is required and cannot be empty'); - expect(mockExit).toHaveBeenCalledWith(1); - }); - - test('fails when base_url is empty', async () => { - mockInputs({ api_key: 'key', base_url: '', changeset_file: SAMPLE_CHANGESET_FILE }); - - await run(); - - expect(mockCore.setFailed).toHaveBeenCalledWith('base_url is required and cannot be empty'); + expect(mockExecFileSync).toHaveBeenCalledTimes(1); + const [, , options] = mockExecFileSync.mock.calls[0]; + expect(options.env).toMatchObject({ + INPROD_API_KEY: 'test-api-key', + INPROD_BASE_URL: 'https://your-company.inprod.io', + INPROD_CHANGESET_FILE: 'changesets/test.yaml', + INPROD_ENVIRONMENT: '', + INPROD_VALIDATE_BEFORE_EXECUTE: 'true', + INPROD_VALIDATE_ONLY: 'false', + INPROD_POLLING_TIMEOUT_MINUTES: '10', + INPROD_EXECUTION_STRATEGY: 'per_file', + INPROD_FAIL_FAST: 'false', + INPROD_CHANGESET_VARIABLES: '', + INPROD_FILES: '', + }); }); - test('fails when base_url is invalid', async () => { - mockInputs({ api_key: 'key', base_url: 'not-a-url', changeset_file: SAMPLE_CHANGESET_FILE }); + test('passes inprod_files through as INPROD_FILES', async () => { + mockInputs({ ...DEFAULT_INPUTS, inprod_files: 'CERT=./certs/server.pem' }); + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith('Invalid base_url format: not-a-url'); + const [, , options] = mockExecFileSync.mock.calls[0]; + expect(options.env.INPROD_FILES).toBe('CERT=./certs/server.pem'); }); - test('fails when changeset_file is not provided', async () => { - mockInputs({ api_key: 'key', base_url: 'https://test.inprod.io' }); + test('sets INPROD_DEBUG when the Action runs in debug mode', async () => { + mockCore.isDebug.mockReturnValue(true); + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith('changeset_file is required'); + const [, , options] = mockExecFileSync.mock.calls[0]; + expect(options.env.INPROD_DEBUG).toBe('true'); }); - test('fails when changeset_file does not exist', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: '/nonexistent/path/file.yaml', - }); + test('omits INPROD_DEBUG when not in debug mode', async () => { + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith(expect.stringContaining('Changeset file not found')); + const [, , options] = mockExecFileSync.mock.calls[0]; + expect(options.env.INPROD_DEBUG).toBeUndefined(); }); - test('falls back to INPROD_API_KEY env var when api_key input is empty', async () => { + test('falls back to INPROD_API_KEY/INPROD_BASE_URL env vars when inputs are empty', async () => { + mockInputs({ ...DEFAULT_INPUTS, api_key: '', base_url: '' }); process.env.INPROD_API_KEY = 'env-api-key'; process.env.INPROD_BASE_URL = 'https://env.inprod.io'; - mockInputs({ api_key: '', base_url: '', changeset_file: SAMPLE_CHANGESET_FILE, validate_before_execute: 'false' }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setSecret).toHaveBeenCalledWith('env-api-key'); - expect(mockFetch).toHaveBeenCalledWith( - expect.stringContaining('https://env.inprod.io'), - expect.objectContaining({ - headers: expect.objectContaining({ 'Authorization': 'Api-Key env-api-key' }) - }) - ); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - delete process.env.INPROD_API_KEY; - delete process.env.INPROD_BASE_URL; - }); - - test('falls back to INPROD_BASE_URL env var when base_url input is empty', async () => { - process.env.INPROD_BASE_URL = 'https://env-only.inprod.io'; - mockInputs({ api_key: 'key', base_url: '', changeset_file: SAMPLE_CHANGESET_FILE, validate_before_execute: 'false' }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockFetch).toHaveBeenCalledWith( - expect.stringContaining('https://env-only.inprod.io'), - expect.any(Object) - ); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - delete process.env.INPROD_BASE_URL; - }); - - test('input takes precedence over env var', async () => { - process.env.INPROD_API_KEY = 'env-key'; - process.env.INPROD_BASE_URL = 'https://env.inprod.io'; - mockInputs({ api_key: 'input-key', base_url: 'https://input.inprod.io', changeset_file: SAMPLE_CHANGESET_FILE, validate_before_execute: 'false' }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); + await run(); - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; + const [, , options] = mockExecFileSync.mock.calls[0]; + expect(options.env.INPROD_API_KEY).toBe('env-api-key'); + expect(options.env.INPROD_BASE_URL).toBe('https://env.inprod.io'); - expect(mockCore.setSecret).toHaveBeenCalledWith('input-key'); - expect(mockFetch).toHaveBeenCalledWith( - expect.stringContaining('https://input.inprod.io'), - expect.objectContaining({ - headers: expect.objectContaining({ 'Authorization': 'Api-Key input-key' }) - }) - ); - expect(mockCore.setFailed).not.toHaveBeenCalled(); delete process.env.INPROD_API_KEY; delete process.env.INPROD_BASE_URL; }); - test('fails when api_key not provided via input or env var', async () => { - delete process.env.INPROD_API_KEY; - mockInputs({ api_key: '', base_url: 'https://test.inprod.io', changeset_file: SAMPLE_CHANGESET_FILE }); + test('masks the api_key as a secret', async () => { + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith('api_key is required and cannot be empty'); + expect(mockCore.setSecret).toHaveBeenCalledWith('test-api-key'); }); - test('fails when base_url not provided via input or env var', async () => { - delete process.env.INPROD_BASE_URL; - mockInputs({ api_key: 'key', base_url: '', changeset_file: SAMPLE_CHANGESET_FILE }); + test('spawns the current node binary against the resolved run-changesets entry point, with output streamed live', async () => { + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles()); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith('base_url is required and cannot be empty'); + const [command, args, options] = mockExecFileSync.mock.calls[0]; + expect(command).toBe(process.execPath); + expect(args).toHaveLength(1); + expect(args[0]).toMatch(/run-changesets/); + expect(options.stdio).toBe('inherit'); }); +}); - test('masks api_key in logs', async () => { - mockInputs({ api_key: 'secret-key', base_url: 'https://test.inprod.io', changeset_file: SAMPLE_CHANGESET_FILE }); - // Will fail on fetch but that's fine — we're checking setSecret was called - mockFetch.mockRejectedValueOnce(new Error('fetch error')); +describe('run() — success', () => { + test('maps result files to Action outputs and deletes them', async () => { + mockExecFileSync.mockImplementation(() => {}); + mockResultFiles(resultFiles({ + status: 'SUCCESS', + results: [{ file: 'test.yaml', status: 'SUCCESS', result: { run_id: 42 }, error: null }], + })); await run(); - expect(mockCore.setSecret).toHaveBeenCalledWith('secret-key'); - }); - - test('removes trailing slash from base_url to prevent double slashes in API URLs', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io/', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false' - }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Verify the API was called with a URL that doesn't have double slashes (like //api/v1...) - expect(mockFetch).toHaveBeenCalledWith( - expect.stringContaining('https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/'), - expect.any(Object) + expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); + expect(mockCore.setOutput).toHaveBeenCalledWith( + 'result', + JSON.stringify([{ file: 'test.yaml', status: 'SUCCESS', result: { run_id: 42 }, error: null }]) ); - // Ensure no double slashes in the URL path - const callUrl = mockFetch.mock.calls[0][0]; - expect(callUrl).not.toMatch(/inprod\.io\/\//); + expect(mockFs.unlinkSync).toHaveBeenCalledTimes(2); expect(mockCore.setFailed).not.toHaveBeenCalled(); + expect(mockExit).not.toHaveBeenCalled(); }); }); -// ─── run() — Changeset File Resolution ─────────────────────────────────── - -describe('run — changeset file resolution', () => { - test('reads changeset_file and sends content in yaml payload', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', +describe('run() — per-file failure (run-changesets exits non-zero, result files present)', () => { + test('reports the single failing file\'s error', async () => { + mockExecFileSync.mockImplementation(() => { + const err = new Error('Command failed'); + err.status = 1; + throw err; }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - const callArgs = mockFetch.mock.calls[0]; // First call is execute - // YAML files are sent as application/yaml with raw content - expect(callArgs[1].headers['Content-Type']).toBe('application/yaml'); - expect(callArgs[1].body).toBe(SAMPLE_CHANGESET); - expect(mockCore.info).toHaveBeenCalledWith(expect.stringContaining('Read changeset from file')); - }); -}); - -// ─── run() — Execute without validation ───────────────────────────────────── - -describe('run — execute without validation', () => { - const baseInputs = { - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', - }; - - test('submits and waits for successful execution', async () => { - mockInputs({ ...baseInputs, polling_timeout_minutes: '1' }); - - const execResult = { run_id: 42, successful: true, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-1', 42))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - expect(mockCore.setOutput).toHaveBeenCalledWith('result', singleResultArray('SUCCESS', execResult)); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - }); - - test('fails when execution API returns non-ok status', async () => { - mockInputs({ ...baseInputs }); - mockFetch.mockResolvedValueOnce(mockFetchResponse(403, 'Forbidden', false)); - - await run(); - - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('API request failed with status 403') - ); - }); - - test('fails when execution response has no task_id', async () => { - mockInputs({ ...baseInputs }); - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, { data: { attributes: {} } })); - - await run(); - - expect(mockCore.setFailed).toHaveBeenCalledWith('API returned an empty task_id'); - }); - - test('fails when execution response structure is unexpected', async () => { - mockInputs({ ...baseInputs }); - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, { unexpected: true })); + mockResultFiles(resultFiles({ + status: 'FAILURE', + results: [{ file: 'test.yaml', status: 'FAILURE', result: {}, error: 'Validation failed: bad config' }], + })); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('Failed to extract task_id from API response') - ); - }); - - test('fails when execution poll returns FAILURE', async () => { - mockInputs({ ...baseInputs, polling_timeout_minutes: '1' }); - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-3'))) - .mockResolvedValueOnce(mockFetchResponse(200, failurePollResponse('Exec failed'))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith('Changeset execution failed: Exec failed'); expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); + expect(mockCore.setFailed).toHaveBeenCalledWith('Validation failed: bad config'); + expect(mockExit).toHaveBeenCalledWith(1); }); - test('fails when execution poll returns REVOKED', async () => { - mockInputs({ ...baseInputs, polling_timeout_minutes: '1' }); - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-4'))) - .mockResolvedValueOnce(mockFetchResponse(200, revokedPollResponse())); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith('Changeset execution was cancelled'); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'REVOKED'); - }); - - test('fails when execution poll times out', async () => { - mockInputs({ ...baseInputs, polling_timeout_minutes: '1' }); - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-5'))); - - // Fill all polling slots with PENDING (60s / 5s = 12 polls) - for (let i = 0; i < 12; i++) { - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, pendingPollResponse())); - } + test('reports an aggregate message when multiple files fail', async () => { + mockExecFileSync.mockImplementation(() => { + const err = new Error('Command failed'); + err.status = 1; + throw err; + }); + mockResultFiles(resultFiles({ + status: 'FAILURE', + results: [ + { file: 'a.yaml', status: 'FAILURE', result: {}, error: 'bad a' }, + { file: 'b.yaml', status: 'FAILURE', result: {}, error: 'bad b' }, + { file: 'c.yaml', status: 'SUCCESS', result: {}, error: null }, + ], + })); - const promise = run(); - for (let i = 0; i < 12; i++) { - await jest.advanceTimersByTimeAsync(5000); - } - await promise; + await run(); expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('did not complete within 60 seconds') - ); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'TIMEOUT'); - }); - - test('appends environment query parameter to execute URL', async () => { - mockInputs({ ...baseInputs, environment: 'Production' }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockFetch).toHaveBeenCalledWith( - 'https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/?environment=Production', - expect.any(Object) - ); - }); - - test('sends correct headers on execute for yaml files', async () => { - mockInputs({ ...baseInputs }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockFetch).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ - method: 'POST', - headers: { - 'Authorization': 'Api-Key key', - 'Content-Type': 'application/yaml', - }, - }) + '2 of 3 changeset(s) failed. See result output for details.' ); + expect(mockExit).toHaveBeenCalledWith(1); }); }); -// ─── run() — Validate before execute ──────────────────────────────────────── - -describe('run — validate before execute', () => { - const baseInputs = { - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'true', - }; - - test('validates then executes on success', async () => { - mockInputs(baseInputs); - - const validResult = { is_valid: true, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - // validate_yaml POST - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-1'))) - // poll validation - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // execute_yaml POST - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('e-1'))) - // poll execution - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); // validation poll - await jest.advanceTimersByTimeAsync(5000); // execution poll - await promise; - - // Should have called validate then execute - expect(mockFetch).toHaveBeenCalledTimes(4); - expect(mockFetch).toHaveBeenNthCalledWith(1, - 'https://test.inprod.io/api/v1/change-set/change-set/validate_yaml/', - expect.objectContaining({ method: 'POST' }) - ); - expect(mockFetch).toHaveBeenNthCalledWith(3, - 'https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/', - expect.objectContaining({ method: 'POST' }) - ); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - }); - - test('fails without executing when validation returns is_valid: false', async () => { - mockInputs(baseInputs); - - const invalidResult = { - is_valid: false, - validation_results: [{ action_id: 1, errors: { name: [{ msg: ['Required'] }] } }], - changeset_name: 'Test', - }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-2'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(invalidResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith('Changeset validation failed. See validation errors above.'); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); - // Should NOT have called execute - expect(mockFetch).toHaveBeenCalledTimes(2); - }); - - test('fails when validation API returns non-ok status', async () => { - mockInputs(baseInputs); - mockFetch.mockResolvedValueOnce(mockFetchResponse(401, 'Unauthorized', false)); +describe('run() — hard failure (run-changesets exits non-zero, no result files)', () => { + test('fails with a generic exit-code message and does not set status/result outputs', async () => { + mockExecFileSync.mockImplementation(() => { + const err = new Error('Command failed'); + err.status = 1; + throw err; + }); + mockNoResultFiles(); await run(); + expect(mockCore.setOutput).not.toHaveBeenCalled(); expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('Validation request failed with status 401') + 'run-changesets exited with code 1. See the job log above for details.' ); - // Should NOT have called execute - expect(mockFetch).toHaveBeenCalledTimes(1); - }); - - test('fails when validation response has no task_id', async () => { - mockInputs(baseInputs); - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, { data: { attributes: {} } })); - - await run(); - - expect(mockCore.setFailed).toHaveBeenCalledWith('Validation API returned an empty task_id'); + expect(mockExit).toHaveBeenCalledWith(1); }); - test('fails when validation response structure is unexpected', async () => { - mockInputs(baseInputs); - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, { bad: 'data' })); + test('required changeset_file input missing fails before spawning', async () => { + mockCore.getInput.mockImplementation((name, opts) => { + if (name === 'changeset_file' && opts?.required) { + throw new Error('Input required and not supplied: changeset_file'); + } + return DEFAULT_INPUTS[name] ?? ''; + }); await run(); - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('Failed to extract task_id from validation response') - ); - }); - - test('fails when validation poll returns FAILURE', async () => { - mockInputs(baseInputs); - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-3'))) - .mockResolvedValueOnce(mockFetchResponse(200, failurePollResponse('Val error'))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith('Validation failed: Val error'); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); - }); - - test('fails when validation poll returns REVOKED', async () => { - mockInputs(baseInputs); - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-4'))) - .mockResolvedValueOnce(mockFetchResponse(200, revokedPollResponse())); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith('Validation task was cancelled'); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'REVOKED'); - }); - - test('fails when validation poll times out', async () => { - mockInputs({ ...baseInputs, polling_timeout_minutes: '1' }); - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-5'))); - for (let i = 0; i < 12; i++) { - mockFetch.mockResolvedValueOnce(mockFetchResponse(200, pendingPollResponse())); - } - - const promise = run(); - for (let i = 0; i < 12; i++) { - await jest.advanceTimersByTimeAsync(5000); - } - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('Validation did not complete within 60 seconds') - ); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'TIMEOUT'); - }); - - test('appends environment to both validate and execute URLs', async () => { - mockInputs({ ...baseInputs, environment: 'UAT' }); - - const validResult = { is_valid: true }; - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-6'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('e-6'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); // validation poll - await jest.advanceTimersByTimeAsync(5000); // execution poll - await promise; - - expect(mockFetch).toHaveBeenNthCalledWith(1, - 'https://test.inprod.io/api/v1/change-set/change-set/validate_yaml/?environment=UAT', - expect.any(Object) - ); - expect(mockFetch).toHaveBeenNthCalledWith(3, - 'https://test.inprod.io/api/v1/change-set/change-set/execute_yaml/?environment=UAT', - expect.any(Object) - ); + expect(mockExecFileSync).not.toHaveBeenCalled(); + expect(mockCore.setFailed).toHaveBeenCalledWith('Input required and not supplied: changeset_file'); + expect(mockExit).toHaveBeenCalledWith(1); }); }); - -// ─── run() — Validate only ───────────────────────────────────────────────── - -describe('run — validate only', () => { - const baseInputs = { - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_only: 'true', - }; - - test('validates and returns without executing', async () => { - mockInputs(baseInputs); - - const validResult = { is_valid: true, changeset_name: 'Test Q', environment: { id: 2, name: 'UAT' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-10'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - expect(mockCore.setOutput).toHaveBeenCalledWith('result', singleResultArray('SUCCESS', validResult)); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - // Should NOT have called execute - expect(mockFetch).toHaveBeenCalledTimes(2); // validate POST + poll GET - }); - - test('fails when validation finds errors', async () => { - mockInputs(baseInputs); - - const invalidResult = { is_valid: false, validation_results: [{ errors: {} }] }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-11'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(invalidResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith('Changeset validation failed. See validation errors above.'); - expect(mockFetch).toHaveBeenCalledTimes(2); - }); -}); - -// ─── run() — Execute with validation + wait (full flow) ──────────────────── - -describe('run — full flow (validate + execute + wait)', () => { - test('validates, executes, polls, and succeeds', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'true', - polling_timeout_minutes: '1', - environment: 'Production', - }); - - const validResult = { is_valid: true, changeset_name: 'Full Test' }; - const execResult = { run_id: 99, successful: true, changeset_name: 'Full Test', environment: { id: 3, name: 'Production' } }; - - mockFetch - // 1. validate POST - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-full'))) - // 2. validation poll → SUCCESS - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // 3. execute POST - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('e-full', 99))) - // 4. execution poll → PENDING - .mockResolvedValueOnce(mockFetchResponse(200, pendingPollResponse())) - // 5. execution poll → SUCCESS - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); // validation poll - await jest.advanceTimersByTimeAsync(5000); // execution poll — PENDING - await jest.advanceTimersByTimeAsync(5000); // execution poll — SUCCESS - await promise; - - expect(mockFetch).toHaveBeenCalledTimes(5); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - expect(mockCore.setOutput).toHaveBeenCalledWith('result', singleResultArray('SUCCESS', execResult)); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - - // Verify environment was passed to both endpoints - expect(mockFetch).toHaveBeenNthCalledWith(1, - expect.stringContaining('?environment=Production'), - expect.any(Object) - ); - expect(mockFetch).toHaveBeenNthCalledWith(3, - expect.stringContaining('?environment=Production'), - expect.any(Object) - ); - }); -}); - -// ─── run() — Polling timeout default ──────────────────────────────────────── - -describe('run — polling timeout defaults', () => { - test('defaults to 10 minutes when polling_timeout_minutes not provided', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', - }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.info).toHaveBeenCalledWith( - expect.stringContaining('10 minutes (600 seconds)') - ); - }); - - test('respects custom polling_timeout_minutes', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', - polling_timeout_minutes: '30', - }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.info).toHaveBeenCalledWith( - expect.stringContaining('30 minutes (1800 seconds)') - ); - }); -}); - -// ─── run() — Output logging ──────────────────────────────────────────────── - -describe('run — output logging', () => { - test('logs run_id, changeset_name, and environment on success', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', - polling_timeout_minutes: '1', - }); - - const execResult = { run_id: 55, changeset_name: 'My CS', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-log', 55))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockCore.info).toHaveBeenCalledWith('Run ID: 55'); - expect(mockCore.info).toHaveBeenCalledWith('Changeset: My CS'); - expect(mockCore.info).toHaveBeenCalledWith(expect.stringContaining('"name":"Dev"')); - }); - - test('result output is always an array', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', - }); - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-arr'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - const resultCall = mockCore.setOutput.mock.calls.find(c => c[0] === 'result'); - const parsed = JSON.parse(resultCall[1]); - expect(Array.isArray(parsed)).toBe(true); - expect(parsed).toHaveLength(1); - expect(parsed[0].file).toBe(SAMPLE_BASENAME); - expect(parsed[0].status).toBe('SUCCESS'); - }); -}); - -// ─── run() — Multi-file execution (per_file strategy) ────────────────────── - -describe('run — multi-file (per_file strategy)', () => { - const globPattern = path.join(__dirname, '__test_0*__.yaml'); - const baseInputs = { - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: globPattern, - validate_before_execute: 'false', - }; - - test('processes multiple files sequentially and produces result array', async () => { - mockInputs(baseInputs); - - // 3 files matched: 01, 02, 03 - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(15000); // 3 polls - await promise; - - expect(mockFetch).toHaveBeenCalledTimes(6); // 3 executes + 3 polls - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - - // Verify result array - const resultCall = mockCore.setOutput.mock.calls.find(c => c[0] === 'result'); - const parsed = JSON.parse(resultCall[1]); - expect(parsed).toHaveLength(3); - expect(parsed[0].file).toBe('__test_01_queues__.yaml'); - expect(parsed[1].file).toBe('__test_02_flows__.yaml'); - expect(parsed[2].file).toBe('__test_03_webchat__.yaml'); - }); - - test('continues on failure when fail_fast is false (default)', async () => { - mockInputs({ ...baseInputs, fail_fast: 'false' }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - // File 1: execute + poll - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - // File 2: execute fails - .mockResolvedValueOnce(mockFetchResponse(403, 'Forbidden', false)) - // File 3: execute + poll - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); // File 1 poll - await jest.advanceTimersByTimeAsync(5000); // File 3 poll - await promise; - - expect(mockFetch).toHaveBeenCalledTimes(5); // 3 executes + 2 polls - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); - expect(mockCore.setFailed).toHaveBeenCalled(); - - const resultCall = mockCore.setOutput.mock.calls.find(c => c[0] === 'result'); - const parsed = JSON.parse(resultCall[1]); - expect(parsed).toHaveLength(3); - expect(parsed[0].status).toBe('SUCCESS'); - expect(parsed[1].status).toBe('FAILURE'); - expect(parsed[1].error).toContain('403'); - expect(parsed[2].status).toBe('SUCCESS'); - }); - - test('stops on first failure when fail_fast is true', async () => { - mockInputs({ ...baseInputs, fail_fast: 'true' }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - // File 1: execute + poll - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - // File 2: execute fails - .mockResolvedValueOnce(mockFetchResponse(403, 'Forbidden', false)); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); // File 1 poll - await promise; - - expect(mockFetch).toHaveBeenCalledTimes(3); // 2 executes + 1 poll - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); - expect(mockCore.setFailed).toHaveBeenCalled(); - - const resultCall = mockCore.setOutput.mock.calls.find(c => c[0] === 'result'); - const parsed = JSON.parse(resultCall[1]); - expect(parsed).toHaveLength(2); // only 2 processed - expect(parsed[0].status).toBe('SUCCESS'); - expect(parsed[1].status).toBe('FAILURE'); - }); - - test('reports multiple failures in aggregate message', async () => { - mockInputs({ ...baseInputs, fail_fast: 'false' }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - // File 1: execute fails - .mockResolvedValueOnce(mockFetchResponse(403, 'Forbidden', false)) - // File 2: execute fails - .mockResolvedValueOnce(mockFetchResponse(403, 'Forbidden', false)) - // File 3: execute + poll - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); // File 3 poll - await promise; - - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('2 of 3 changeset(s) failed') - ); - }); - - test('logs file count in action output', async () => { - mockInputs(baseInputs); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(15000); // 3 polls - await promise; - - expect(mockCore.info).toHaveBeenCalledWith('Files to process: 3'); - }); - - test('fails when glob pattern matches no files', async () => { - mockInputs({ - ...baseInputs, - changeset_file: path.join(__dirname, '__no_match_glob_*__.yaml'), - }); - - await run(); - - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('No files matched the pattern') - ); - }); -}); - -// ─── run() — Multi-file execution (validate_first strategy) ──────────────── - -describe('run — multi-file (validate_first strategy)', () => { - const globPattern = path.join(__dirname, '__test_0*__.yaml'); - const baseInputs = { - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: globPattern, - validate_before_execute: 'true', - execution_strategy: 'validate_first', - }; - - test('validates all files first then executes all', async () => { - mockInputs(baseInputs); - - const validResult = { is_valid: true }; - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - // Validate file 1 - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // Validate file 2 - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // Validate file 3 - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // Execute file 1 - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('e-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - // Execute file 2 - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('e-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - // Execute file 3 - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('e-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - // wait for all operations - for (let i = 0; i < 6; i++) { - await jest.advanceTimersByTimeAsync(5000); - } - await promise; - - expect(mockFetch).toHaveBeenCalledTimes(12); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - }); - - test('does not execute any files when validation fails', async () => { - mockInputs(baseInputs); - - const validResult = { is_valid: true }; - const invalidResult = { is_valid: false, validation_results: [{ errors: {} }] }; - mockFetch - // Validate file 1 — passes - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // Validate file 2 — fails - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(invalidResult))) - // Validate file 3 — passes (still attempted since fail_fast is false) - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await jest.advanceTimersByTimeAsync(5000); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // 6 fetch calls (3 validate + 3 polls), NO execute calls - expect(mockFetch).toHaveBeenCalledTimes(6); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); - expect(mockCore.setFailed).toHaveBeenCalled(); - }); - - test('stops validation on first failure when fail_fast is true', async () => { - mockInputs({ ...baseInputs, fail_fast: 'true' }); - - const validResult = { is_valid: true }; - const invalidResult = { is_valid: false, validation_results: [{ errors: {} }] }; - mockFetch - // Validate file 1 — passes - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))) - // Validate file 2 — fails - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(invalidResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Only 4 fetch calls (2 validate + 2 polls), stopped after file 2 - expect(mockFetch).toHaveBeenCalledTimes(4); - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'FAILURE'); - expect(mockCore.setFailed).toHaveBeenCalled(); - }); -}); -// ─── Changeset Variables ─────────────────────────────────────────────────── - -describe('run — changeset variables', () => { - const baseInputs = { - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_CHANGESET_FILE, - validate_before_execute: 'false', - }; - - test('injects changeset variables into yaml file body', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: 'DATABASE_PASSWORD=secret123\nAPI_TOKEN=token456' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - const callArgs = mockFetch.mock.calls[0]; - expect(callArgs[1].headers['Content-Type']).toBe('application/yaml'); - // Variables should be injected into the YAML body - const body = callArgs[1].body; - expect(body).toContain('DATABASE_PASSWORD'); - expect(body).toContain('secret123'); - expect(body).toContain('API_TOKEN'); - expect(body).toContain('token456'); - expect(body).toContain('mask_value: false'); - }); - - test('fails with invalid changeset_variables format', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: 'INVALID_FORMAT_NO_EQUALS' - }); - - await run(); - - expect(mockCore.setFailed).toHaveBeenCalledWith( - expect.stringContaining('Invalid changeset_variables format') - ); - }); - - test('handles empty changeset_variables gracefully', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: '' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Should succeed without variables - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - }); - - test('handles whitespace-only changeset_variables gracefully', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: ' ' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Should succeed without variables - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - }); - - test('logs variable count but not values', async () => { - const variables = { SECRET1: 'value1', SECRET2: 'value2' }; - mockInputs({ - ...baseInputs, - changeset_variables: 'SECRET1=value1\nSECRET2=value2' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Should log variable count - expect(mockCore.info).toHaveBeenCalledWith( - expect.stringContaining('Changeset variables: 2 variable(s) provided') - ); - - // Should NOT log variable values - expect(mockCore.info).not.toHaveBeenCalledWith( - expect.stringContaining('value1') - ); - expect(mockCore.info).not.toHaveBeenCalledWith( - expect.stringContaining('value2') - ); - }); - - test('injects variables into each yaml file when multiple files provided', async () => { - const globPattern = path.join(__dirname, '__test_0*__.yaml'); - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: globPattern, - validate_before_execute: 'false', - changeset_variables: 'DB_PASSWORD=secret\nAPI_KEY=key123' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - // File 1 - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-01'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - // File 2 - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-02'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))) - // File 3 - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse('t-03'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(15000); - await promise; - - // Each YAML file should have variables injected - const postCalls = mockFetch.mock.calls.filter(call => call[1].method === 'POST'); - expect(postCalls.length).toBe(3); - postCalls.forEach(call => { - expect(call[1].headers['Content-Type']).toBe('application/yaml'); - expect(call[1].body).toContain('DB_PASSWORD'); - expect(call[1].body).toContain('secret'); - expect(call[1].body).toContain('API_KEY'); - expect(call[1].body).toContain('key123'); - }); - }); - - test('handles changeset variables with values containing equals signs', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: 'CONNECTION_STRING=user=admin;password=secret123;host=db.local' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Variables parsing still works (used for JSON files), verify no crash - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - }); - - test('skips null lines and comments in changeset variables', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: ` - # This is a comment - API_KEY=secret123 - - # Another comment - DB_PASSWORD=dbpass456 - ` - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Variables parsing still works, verify no crash - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - }); - - test('trims whitespace from keys and values', async () => { - mockInputs({ - ...baseInputs, - changeset_variables: ' API_KEY = secret123 \n DB_USER = admin ' - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - // Variables parsing still works, verify no crash - expect(mockCore.setOutput).toHaveBeenCalledWith('status', 'SUCCESS'); - }); -}); - -// ─── getFileFormat ────────────────────────────────────────────────────────── - -describe('getFileFormat', () => { - test('returns yaml for .yaml files', () => { - expect(getFileFormat('changeset.yaml')).toBe('yaml'); - }); - - test('returns yaml for .yml files', () => { - expect(getFileFormat('changeset.yml')).toBe('yaml'); - }); - - test('returns json for .json files', () => { - expect(getFileFormat('changeset.json')).toBe('json'); - }); - - test('returns yaml for unknown extensions (default)', () => { - expect(getFileFormat('changeset.txt')).toBe('yaml'); - expect(getFileFormat('changeset')).toBe('yaml'); - }); - - test('is case insensitive', () => { - expect(getFileFormat('changeset.JSON')).toBe('json'); - expect(getFileFormat('changeset.YAML')).toBe('yaml'); - expect(getFileFormat('changeset.YML')).toBe('yaml'); - }); -}); - -// ─── injectYamlVariables ──────────────────────────────────────────────────── - -describe('injectYamlVariables', () => { - const baseYaml = `name: Test Queue -environment: Development -variable: -- environment: null - mask_value: false - name: existing_var - value: old_value -- environment: Dev - mask_value: true - name: existing_var - value: dev_value -action: - - action: gencloud-create - object_type: RoutingQueue`; - - test('injects new variables with mask_value: false by default', () => { - const result = injectYamlVariables(baseYaml, { NEW_VAR: 'new_value' }); - expect(result).toContain('name: NEW_VAR'); - expect(result).toContain('value: new_value'); - expect(result).toContain('mask_value: false'); - }); - - test('when overriding variable with mask_value: true in existing entry, preserves true', () => { - const result = injectYamlVariables(baseYaml, { existing_var: 'replaced_value' }); - // Should have exactly one entry for existing_var (the injected one) - const matches = result.match(/name: existing_var/g); - expect(matches).toHaveLength(1); - expect(result).toContain('value: replaced_value'); - expect(result).toContain('mask_value: true'); - expect(result).not.toContain('old_value'); - expect(result).not.toContain('dev_value'); - }); - - test('preserves existing variables that are not overridden', () => { - const yamlWithMultiple = `name: Test -variable: -- environment: null - mask_value: false - name: keep_this - value: kept -- environment: null - mask_value: false - name: replace_this - value: old`; - const result = injectYamlVariables(yamlWithMultiple, { replace_this: 'new' }); - expect(result).toContain('name: keep_this'); - expect(result).toContain('value: kept'); - expect(result).toContain('name: replace_this'); - expect(result).toContain('value: new'); - expect(result).not.toContain('value: old'); - }); - - test('sets environment to null for injected variables and removes all others', () => { - const result = injectYamlVariables(baseYaml, { existing_var: 'val' }); - // Parse back to verify structure - const yaml = require('js-yaml'); - const doc = yaml.load(result); - const injected = doc.variable.find(v => v.name === 'existing_var'); - expect(injected.environment).toBeNull(); - // Should have exactly one entry for existing_var - const allExisting = doc.variable.filter(v => v.name === 'existing_var'); - expect(allExisting).toHaveLength(1); - }); - - test('handles yaml with empty variable array', () => { - const yamlEmpty = `name: Test\nvariable: []`; - const result = injectYamlVariables(yamlEmpty, { NEW_VAR: 'value' }); - expect(result).toContain('name: NEW_VAR'); - expect(result).toContain('value: value'); - }); - - test('handles yaml with no variable field', () => { - const yamlNoVar = `name: Test\nenvironment: Dev`; - const result = injectYamlVariables(yamlNoVar, { NEW_VAR: 'value' }); - expect(result).toContain('name: NEW_VAR'); - expect(result).toContain('value: value'); - }); - - test('injects multiple variables at once, preserving mask_value from existing', () => { - const result = injectYamlVariables(baseYaml, { VAR_A: 'aaa', existing_var: 'bbb' }); - const yaml = require('js-yaml'); - const doc = yaml.load(result); - const varA = doc.variable.find(v => v.name === 'VAR_A'); - const varB = doc.variable.find(v => v.name === 'existing_var'); - // VAR_A is new, should have false (no existing entries with true) - expect(varA).toEqual({ environment: null, mask_value: false, name: 'VAR_A', value: 'aaa' }); - // existing_var has entries with mask_value: true, should preserve it - expect(varB.environment).toBeNull(); - expect(varB.mask_value).toBe(true); - expect(varB.value).toBe('bbb'); - }); -}); - -// ─── run() — JSON file format ────────────────────────────────────────────── - -describe('run — JSON file format', () => { - const SAMPLE_JSON_CHANGESET_OBJ = { - name: 'Test Queue', - environment: 'Development', - variable: [ - { environment: null, mask_value: false, name: 'DogsName', value: 'global value' }, - { environment: 1, mask_value: false, name: 'DogsName', value: 'dev value' }, - ], - action: [{ action: 'gencloud-create', object_type: 'RoutingQueue', data: { name: 'Test Queue' } }] - }; - const SAMPLE_JSON_CHANGESET = JSON.stringify(SAMPLE_JSON_CHANGESET_OBJ, null, 2); - const SAMPLE_JSON_FILE = path.join(__dirname, '__test_changeset_sample__.json'); - - beforeAll(() => { - fs.writeFileSync(SAMPLE_JSON_FILE, SAMPLE_JSON_CHANGESET); - }); - - afterAll(() => { - if (fs.existsSync(SAMPLE_JSON_FILE)) fs.unlinkSync(SAMPLE_JSON_FILE); - }); - - test('uses application/json content type and validate_json endpoint for .json files', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_JSON_FILE, - validate_only: 'true', - }); - - const validResult = { is_valid: true, changeset_name: 'Test' }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, validationTaskResponse('v-json'))) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(validResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockFetch).toHaveBeenNthCalledWith(1, - 'https://test.inprod.io/api/v1/change-set/change-set/validate_json/', - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ 'Content-Type': 'application/json' }), - }) - ); - // Body should be raw JSON changeset content (not wrapped) - const body = mockFetch.mock.calls[0][1].body; - expect(body).toBe(SAMPLE_JSON_CHANGESET); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - }); - - test('uses execute_json endpoint for .json files', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_JSON_FILE, - validate_before_execute: 'false', - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - expect(mockFetch).toHaveBeenNthCalledWith(1, - 'https://test.inprod.io/api/v1/change-set/change-set/execute_json/', - expect.objectContaining({ - method: 'POST', - headers: expect.objectContaining({ 'Content-Type': 'application/json' }), - }) - ); - // Body should be raw JSON changeset content (not wrapped) - const body = mockFetch.mock.calls[0][1].body; - expect(body).toBe(SAMPLE_JSON_CHANGESET); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - }); - - test('injects variables into JSON changeset body for .json files', async () => { - mockInputs({ - api_key: 'key', - base_url: 'https://test.inprod.io', - changeset_file: SAMPLE_JSON_FILE, - validate_before_execute: 'false', - changeset_variables: 'DogsName=overridden\nNewVar=newval', - }); - - const execResult = { run_id: 42, changeset_name: 'Test', environment: { id: 1, name: 'Dev' } }; - mockFetch - .mockResolvedValueOnce(mockFetchResponse(200, executeTaskResponse())) - .mockResolvedValueOnce(mockFetchResponse(200, successPollResponse(execResult))); - - const promise = run(); - await jest.advanceTimersByTimeAsync(5000); - await promise; - - const body = JSON.parse(mockFetch.mock.calls[0][1].body); - // Should NOT have a wrapper changeset/variables field - expect(body.changeset).toBeUndefined(); - expect(body.variables).toBeUndefined(); - // All existing DogsName entries should be removed, replaced with one injected entry - const dogsEntries = body.variable.filter(v => v.name === 'DogsName'); - expect(dogsEntries).toHaveLength(1); - expect(dogsEntries[0]).toEqual({ environment: null, mask_value: false, name: 'DogsName', value: 'overridden' }); - // New variable should be added - const newVarEntry = body.variable.find(v => v.name === 'NewVar'); - expect(newVarEntry).toEqual({ environment: null, mask_value: false, name: 'NewVar', value: 'newval' }); - expect(mockCore.setFailed).not.toHaveBeenCalled(); - }); -}); - -// ─── injectJsonVariables ──────────────────────────────────────────────────── - -describe('injectJsonVariables', () => { - const baseJson = JSON.stringify({ - name: 'Test Queue', - variable: [ - { environment: null, mask_value: false, name: 'existing_var', value: 'old_value' }, - { environment: 1, mask_value: false, name: 'existing_var', value: 'dev_value' }, - { environment: null, mask_value: true, name: 'keep_var', value: 'kept' }, - ], - action: [{ action: 'gencloud-create' }] - }, null, 2); - - test('injects new variables with mask_value: false by default', () => { - const result = JSON.parse(injectJsonVariables(baseJson, { NEW_VAR: 'new_value' })); - const injected = result.variable.find(v => v.name === 'NEW_VAR'); - expect(injected).toEqual({ environment: null, mask_value: false, name: 'NEW_VAR', value: 'new_value' }); - }); - - test('when overriding variable with only mask_value: false entries, uses false', () => { - const result = JSON.parse(injectJsonVariables(baseJson, { existing_var: 'replaced_value' })); - const matches = result.variable.filter(v => v.name === 'existing_var'); - expect(matches).toHaveLength(1); - expect(matches[0].value).toBe('replaced_value'); - expect(matches[0].mask_value).toBe(false); - expect(matches[0].environment).toBeNull(); - }); - - test('when overriding variable with mask_value: true in existing entry, preserves true', () => { - const result = JSON.parse(injectJsonVariables(baseJson, { keep_var: 'new_value' })); - const matches = result.variable.filter(v => v.name === 'keep_var'); - expect(matches).toHaveLength(1); - expect(matches[0].value).toBe('new_value'); - expect(matches[0].mask_value).toBe(true); - expect(matches[0].environment).toBeNull(); - }); - - test('preserves existing variables that are not overridden', () => { - const result = JSON.parse(injectJsonVariables(baseJson, { existing_var: 'new' })); - const kept = result.variable.find(v => v.name === 'keep_var'); - expect(kept).toEqual({ environment: null, mask_value: true, name: 'keep_var', value: 'kept' }); - }); - - test('handles JSON with empty variable array', () => { - const jsonEmpty = JSON.stringify({ name: 'Test', variable: [] }); - const result = JSON.parse(injectJsonVariables(jsonEmpty, { NEW_VAR: 'value' })); - expect(result.variable).toHaveLength(1); - expect(result.variable[0].name).toBe('NEW_VAR'); - }); - - test('handles JSON with no variable field', () => { - const jsonNoVar = JSON.stringify({ name: 'Test', environment: 'Dev' }); - const result = JSON.parse(injectJsonVariables(jsonNoVar, { NEW_VAR: 'value' })); - expect(result.variable).toHaveLength(1); - expect(result.variable[0].name).toBe('NEW_VAR'); - }); - - test('injects multiple variables at once, preserving mask_value from existing', () => { - const result = JSON.parse(injectJsonVariables(baseJson, { VAR_A: 'aaa', keep_var: 'bbb' })); - const varA = result.variable.find(v => v.name === 'VAR_A'); - const varB = result.variable.find(v => v.name === 'keep_var'); - // VAR_A is new, should have false (no existing entries with true) - expect(varA).toEqual({ environment: null, mask_value: false, name: 'VAR_A', value: 'aaa' }); - // keep_var exists with mask_value: true, should preserve it - expect(varB).toEqual({ environment: null, mask_value: true, name: 'keep_var', value: 'bbb' }); - }); - - test('preserves other JSON fields', () => { - const result = JSON.parse(injectJsonVariables(baseJson, { NEW_VAR: 'val' })); - expect(result.name).toBe('Test Queue'); - expect(result.action).toEqual([{ action: 'gencloud-create' }]); - }); -}); \ No newline at end of file