From fad17ae15029a41904afa8c14b7202deaea616d6 Mon Sep 17 00:00:00 2001 From: Kyle Smith Date: Wed, 2 Dec 2026 14:43:16 -0600 Subject: [PATCH] Add merge drivers to staging-auto-merge and a maintain-staging reusable workflow Co-Authored-By: Claude Opus 5.5 --- .github/workflows/maintain-staging.yml | 56 + README.md | 71 +- staging-auto-merge/action.yml | 9 + staging-auto-merge/dist/index.js | 7537 ++++++++++++++++- staging-auto-merge/drivers/railsschema | 22 + staging-auto-merge/package-lock.json | 18 +- staging-auto-merge/package.json | 3 +- staging-auto-merge/src/index.js | 16 +- staging-auto-merge/src/merge-drivers.js | 115 + staging-auto-merge/src/staging-auto-merge.js | 40 +- .../tests/merge-drivers.test.js | 213 + 11 files changed, 7814 insertions(+), 286 deletions(-) create mode 100644 .github/workflows/maintain-staging.yml create mode 100755 staging-auto-merge/drivers/railsschema create mode 100644 staging-auto-merge/src/merge-drivers.js create mode 100644 staging-auto-merge/tests/merge-drivers.test.js diff --git a/.github/workflows/maintain-staging.yml b/.github/workflows/maintain-staging.yml new file mode 100644 index 0000000..536b3c5 --- /dev/null +++ b/.github/workflows/maintain-staging.yml @@ -0,0 +1,56 @@ +name: Maintain Staging + +# Rebuilds the staging branch from the primary branch plus every open pull request labeled "Staging". Call it on +# pull_request events (labeled, unlabeled, closed, synchronize); it runs only when the event can change staging. +# A pull request that won't merge loses the label and gets a comment listing the conflicts. + +on: + workflow_call: + inputs: + primary-branch: + description: Branch the staging branch is rebuilt from. + type: string + default: main + + merge-drivers: + description: > + Git merge drivers for staging-auto-merge, as a YAML list. See its `merge-drivers` input. Pass `[]` for + none. + type: string + default: railsschema + + runner: + description: Runner to use + type: string + default: ubuntu-latest + + secrets: + deploy-key: + description: > + SSH deploy key with write access. A push made with the default GITHUB_TOKEN doesn't trigger other + workflows, so pushing with this key is what lets the push to staging start a deploy. + required: true + +jobs: + rebuild: + name: Rebuild Staging + if: contains(github.event.pull_request.labels.*.name, 'Staging') || github.event.label.name == 'Staging' || (github.event.action == 'closed' && github.event.pull_request.merged) + runs-on: ${{ inputs.runner }} + timeout-minutes: 5 + concurrency: + group: maintain-staging + permissions: + contents: write + issues: read # finds closed pull requests that still carry the Staging label + pull-requests: write # comments on and unlabels pull requests that won't merge + steps: + - uses: actions/checkout@v7 + with: + ref: staging + fetch-depth: 0 + ssh-key: ${{ secrets.deploy-key }} + + - uses: RoleModel/actions/staging-auto-merge@v3 + with: + primary-branch: ${{ inputs.primary-branch }} + merge-drivers: ${{ inputs.merge-drivers }} diff --git a/README.md b/README.md index a340f3d..2c79db4 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ Example: ## staging-auto-merge -Use this action to maintain a `staging` branch with the changes from all open PRs labeled `Staging`. This is recommended to be used with a workflow that auto-deploys the `staging` branch. +Use this action to maintain a `staging` branch with the changes from all open PRs labeled `Staging`. This is recommended to be used with a workflow that auto-deploys the `staging` branch. Most apps should call the [Maintain Staging reusable workflow](#maintain-staging-reusable-workflow), which wraps this action. If a PR cannot be merged cleanly, the action comments on the PR with conflict details and removes the `Staging` label. @@ -49,6 +49,34 @@ Inputs: - `github-token`: GitHub token used to list/update pull requests. Default: `${{ github.token }}` - `primary-branch`: Branch used as the reset base before staged merges. Default: `main` +- `merge-drivers`: [Git merge drivers](https://git-scm.com/docs/gitattributes#_defining_a_custom_merge_driver) to use while merging, as a YAML list. Default: none + +### Merge drivers + +A merge driver resolves conflicts git can't, such as two PRs that each bump the same version line. Each entry in `merge-drivers` is either the name of a built-in driver or a mapping for a custom one. You can list several and mix both kinds. + +Built-in drivers: + +- `railsschema`: for `db/schema.rb`. Two PRs that each add a migration both change the `define(version: …)` line. This sets that line to the newest version, then merges the rest of the file as git normally would, so a real schema conflict still fails. + +A custom driver is a mapping with: + +- `name`: letters, numbers, `-` and `_`; can't be a built-in driver's name +- `files`: a [gitattributes pattern](https://git-scm.com/docs/gitattributes#_description) or a list of them +- `script`: the driver itself, run with bash unless it starts with a `#!`. Git calls it with the base, ours, and theirs versions of the file, the conflict marker size, and the file's path. It writes the result to ours (`$2`) and exits non-zero to leave a conflict. + +A built-in driver given as a mapping takes `files` to apply it to other files. + +```yaml +merge-drivers: | + - name: railsschema + files: [db/schema.rb, db/animals_schema.rb] + - name: lockfile + files: [Gemfile.lock, yarn.lock] + script: exec bin/merge-lockfile "$@" # a script committed in the app +``` + +The action registers drivers in `.git/info/attributes` and the checkout's git config, so nothing is committed to `staging`. Example: @@ -83,8 +111,49 @@ jobs: - name: Rebuild staging branch uses: RoleModel/actions/staging-auto-merge@v3 + with: + merge-drivers: railsschema ``` +## Maintain Staging (reusable workflow) + +`.github/workflows/maintain-staging.yml` is a `workflow_call` reusable workflow that runs `staging-auto-merge` with the trigger filter, checkout, and concurrency it needs. Runs happen one at a time. + +```yaml +# .github/workflows/maintain-staging.yml +name: Maintain Staging Branch + +on: + pull_request: + types: [labeled, unlabeled, closed, synchronize] + +jobs: + staging: + uses: RoleModel/actions/.github/workflows/maintain-staging.yml@v3 + permissions: + contents: write + issues: read + pull-requests: write + with: + primary-branch: main + secrets: + deploy-key: ${{ secrets.AUTOMATED_COMMITS_KEY }} +``` + +The caller must grant every permission the reusable job declares; if it grants less, the run fails at startup with no logs. + +Inputs: + +- `primary-branch`: Branch the staging branch is rebuilt from. Default: `main` +- `merge-drivers`: Passed to `staging-auto-merge`; see [Merge drivers](#merge-drivers). Pass `[]` for none. Default: `railsschema` +- `runner`: Runner to use. Default: `ubuntu-latest` + +Secrets: + +- `deploy-key`*: SSH deploy key with write access. A push with the default `GITHUB_TOKEN` doesn't trigger other workflows, so pushing with this key is what lets the push to `staging` start a deploy. + +The repository needs a `staging` branch and a `Staging` label. + ## Release (reusable workflow) `.github/workflows/release.yml` is a `workflow_call` reusable workflow that cuts a release end to end: version bump, changelog entry, version commit and tag, GitHub release, and publishing to RubyGems and/or npm with trusted publishing. Call it from a workflow with two triggers: diff --git a/staging-auto-merge/action.yml b/staging-auto-merge/action.yml index 6b86630..d3c6374 100644 --- a/staging-auto-merge/action.yml +++ b/staging-auto-merge/action.yml @@ -12,6 +12,15 @@ inputs: required: false default: main + merge-drivers: + description: > + Git merge drivers to use while merging pull requests, as a YAML list. + Each entry is the name of a built-in driver (railsschema) or a mapping + with name, files (a pattern or list of patterns) and script (a custom + driver, called with base, ours, theirs, marker size and path). Default: none. + required: false + default: '' + runs: using: node24 main: dist/index.js diff --git a/staging-auto-merge/dist/index.js b/staging-auto-merge/dist/index.js index 60a1bdb..660d4ef 100644 --- a/staging-auto-merge/dist/index.js +++ b/staging-auto-merge/dist/index.js @@ -27,6 +27,11 @@ import require$$6 from "string_decoder"; import require$$0$9 from "diagnostics_channel"; import require$$2$3 from "child_process"; import require$$6$1 from "timers"; +import { mkdir, writeFile, chmod, appendFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import require$$0$a from "process"; var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; @@ -397,7 +402,7 @@ TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { connectOptions.headers = connectOptions.headers || {}; connectOptions.headers["Proxy-Authorization"] = "Basic " + new Buffer(connectOptions.proxyAuth).toString("base64"); } - debug("making CONNECT request"); + debug$1("making CONNECT request"); var connectReq = self2.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; connectReq.once("response", onResponse); @@ -417,7 +422,7 @@ TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { - debug( + debug$1( "tunneling socket could not be established, statusCode=%d", res.statusCode ); @@ -429,7 +434,7 @@ TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { return; } if (head.length > 0) { - debug("got illegal response body from proxy"); + debug$1("got illegal response body from proxy"); socket.destroy(); var error = new Error("got illegal response body from proxy"); error.code = "ECONNRESET"; @@ -437,13 +442,13 @@ TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { self2.removeSocket(placeholder); return; } - debug("tunneling connection has established"); + debug$1("tunneling connection has established"); self2.sockets[self2.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError2(cause) { connectReq.removeAllListeners(); - debug( + debug$1( "tunneling socket could not be established, cause=%s\n", cause.message, cause.stack @@ -505,9 +510,9 @@ function mergeOptions(target) { } return target; } -var debug; +var debug$1; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { + debug$1 = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === "string") { args[0] = "TUNNEL: " + args[0]; @@ -517,10 +522,10 @@ if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { console.error.apply(console, args); }; } else { - debug = function() { + debug$1 = function() { }; } -tunnel$2.debug = debug; +tunnel$2.debug = debug$1; var tunnel$1 = tunnel$2; var undici = {}; var symbols$4 = { @@ -769,7 +774,7 @@ let RequestRetryError$1 = class RequestRetryError extends UndiciError$2 { this.headers = headers2; } }; -var errors$1 = { +var errors$6 = { HTTPParserError: HTTPParserError$1, UndiciError: UndiciError$2, HeadersTimeoutError: HeadersTimeoutError$1, @@ -903,10 +908,10 @@ const { kDestroyed: kDestroyed$1, kBodyUsed: kBodyUsed$1 } = symbols$4; const { IncomingMessage } = require$$2$1; const stream$1 = require$$0$5; const net$2 = require$$0$4; -const { InvalidArgumentError: InvalidArgumentError$l } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$l } = errors$6; const { Blob: Blob$2 } = require$$7; const nodeUtil = require$$0$2; -const { stringify } = require$$8; +const { stringify: stringify$8 } = require$$8; const { headerNameLowerCasedRecord } = constants$5; const [nodeMajor, nodeMinor] = process.versions.node.split(".").map((v) => Number(v)); function nop$1() { @@ -921,7 +926,7 @@ function buildURL$2(url, queryParams) { if (url.includes("?") || url.includes("#")) { throw new Error('Query params cannot be passed when url already contains "?" or "#".'); } - const stringified = stringify(queryParams); + const stringified = stringify$8(queryParams); if (stringified) { url += "?" + stringified; } @@ -3688,9 +3693,9 @@ function requireUtil$4() { let policy = ""; if (policyHeader.length > 0) { for (let i = policyHeader.length; i !== 0; i--) { - const token2 = policyHeader[i - 1].trim(); - if (referrerPolicyTokens.has(token2)) { - policy = token2; + const token = policyHeader[i - 1].trim(); + if (referrerPolicyTokens.has(token)) { + policy = token; break; } } @@ -3885,9 +3890,9 @@ function requireUtil$4() { function parseMetadata(metadata) { const result = []; let empty = true; - for (const token2 of metadata.split(" ")) { + for (const token of metadata.split(" ")) { empty = false; - const parsedToken = parseHashWithOptions.exec(token2); + const parsedToken = parseHashWithOptions.exec(token); if (parsedToken === null || parsedToken.groups === void 0 || parsedToken.groups.algo === void 0) { continue; } @@ -4333,7 +4338,7 @@ function requireWebidl() { }); } const method = V?.[Symbol.iterator]?.(); - const seq = []; + const seq2 = []; if (method === void 0 || typeof method.next !== "function") { throw webidl.errors.exception({ header: "Sequence", @@ -4345,9 +4350,9 @@ function requireWebidl() { if (done) { break; } - seq.push(converter(value)); + seq2.push(converter(value)); } - return seq; + return seq2; }; }; webidl.recordConverter = function(keyConverter, valueConverter) { @@ -4747,10 +4752,10 @@ function requireDataURL() { if (/[^+/0-9A-Za-z]/.test(data)) { return "failure"; } - const binary = atob2(data); - const bytes = new Uint8Array(binary.length); - for (let byte = 0; byte < binary.length; byte++) { - bytes[byte] = binary.charCodeAt(byte); + const binary2 = atob2(data); + const bytes = new Uint8Array(binary2.length); + for (let byte = 0; byte < binary2.length; byte++) { + bytes[byte] = binary2.charCodeAt(byte); } return bytes; } @@ -5568,7 +5573,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r const { InvalidArgumentError: InvalidArgumentError$k, NotSupportedError: NotSupportedError$1 -} = errors$1; +} = errors$6; const assert$8 = require$$0$3; const { kHTTP2BuildRequest: kHTTP2BuildRequest$1, kHTTP2CopyHeaders: kHTTP2CopyHeaders$1, kHTTP1BuildRequest: kHTTP1BuildRequest$1 } = symbols$4; const util$h = util$j; @@ -5946,7 +5951,7 @@ const { ClientDestroyedError: ClientDestroyedError$1, ClientClosedError: ClientClosedError2, InvalidArgumentError: InvalidArgumentError$j -} = errors$1; +} = errors$6; const { kDestroy: kDestroy$4, kClose: kClose$6, kDispatch: kDispatch$3, kInterceptors: kInterceptors$5 } = symbols$4; const kDestroyed = Symbol("destroyed"); const kClosed = Symbol("closed"); @@ -6100,7 +6105,7 @@ var dispatcherBase = DispatcherBase$4; const net$1 = require$$0$4; const assert$7 = require$$0$3; const util$g = util$j; -const { InvalidArgumentError: InvalidArgumentError$i, ConnectTimeoutError: ConnectTimeoutError2 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$i, ConnectTimeoutError: ConnectTimeoutError2 } = errors$6; let tls; let SessionCache; if (commonjsGlobal.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { @@ -6587,7 +6592,7 @@ function requireConstants$2() { const util$f = util$j; const { kBodyUsed } = symbols$4; const assert$6 = require$$0$3; -const { InvalidArgumentError: InvalidArgumentError$h } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$h } = errors$6; const EE = require$$4$1; const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]; const kBody$1 = Symbol("body"); @@ -6779,7 +6784,7 @@ const { HTTPParserError: HTTPParserError2, ResponseExceededMaxSizeError: ResponseExceededMaxSizeError2, ClientDestroyedError: ClientDestroyedError2 -} = errors$1; +} = errors$6; const buildConnector$3 = connect$2; const { kUrl: kUrl$3, @@ -7201,7 +7206,7 @@ let currentBufferPtr = null; const TIMEOUT_HEADERS = 1; const TIMEOUT_BODY = 2; const TIMEOUT_IDLE = 3; -class Parser { +let Parser$1 = class Parser { constructor(client2, socket, { exports: exports$1 }) { assert$5(Number.isFinite(client2[kMaxHeadersSize]) && client2[kMaxHeadersSize] > 0); this.llhttp = exports$1; @@ -7549,16 +7554,16 @@ class Parser { resume(client2); } } -} -function onParserTimeout(parser) { - const { socket, timeoutType, client: client2 } = parser; +}; +function onParserTimeout(parser2) { + const { socket, timeoutType, client: client2 } = parser2; if (timeoutType === TIMEOUT_HEADERS) { if (!socket[kWriting] || socket.writableNeedDrain || client2[kRunning$3] > 1) { - assert$5(!parser.paused, "cannot be paused while waiting for headers"); + assert$5(!parser2.paused, "cannot be paused while waiting for headers"); util$e.destroy(socket, new HeadersTimeoutError2()); } } else if (timeoutType === TIMEOUT_BODY) { - if (!parser.paused) { + if (!parser2.paused) { util$e.destroy(socket, new BodyTimeoutError2()); } } else if (timeoutType === TIMEOUT_IDLE) { @@ -7567,17 +7572,17 @@ function onParserTimeout(parser) { } } function onSocketReadable() { - const { [kParser]: parser } = this; - if (parser) { - parser.readMore(); + const { [kParser]: parser2 } = this; + if (parser2) { + parser2.readMore(); } } function onSocketError(err) { - const { [kClient$1]: client2, [kParser]: parser } = this; + const { [kClient$1]: client2, [kParser]: parser2 } = this; assert$5(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID"); if (client2[kHTTPConnVersion] !== "h2") { - if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) { - parser.onMessageComplete(); + if (err.code === "ECONNRESET" && parser2.statusCode && !parser2.shouldKeepAlive) { + parser2.onMessageComplete(); return; } } @@ -7596,20 +7601,20 @@ function onError(client2, err) { } } function onSocketEnd() { - const { [kParser]: parser, [kClient$1]: client2 } = this; + const { [kParser]: parser2, [kClient$1]: client2 } = this; if (client2[kHTTPConnVersion] !== "h2") { - if (parser.statusCode && !parser.shouldKeepAlive) { - parser.onMessageComplete(); + if (parser2.statusCode && !parser2.shouldKeepAlive) { + parser2.onMessageComplete(); return; } } util$e.destroy(this, new SocketError$2("other side closed", util$e.getSocketInfo(this))); } function onSocketClose() { - const { [kClient$1]: client2, [kParser]: parser } = this; - if (client2[kHTTPConnVersion] === "h1" && parser) { - if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - parser.onMessageComplete(); + const { [kClient$1]: client2, [kParser]: parser2 } = this; + if (client2[kHTTPConnVersion] === "h1" && parser2) { + if (!this[kError] && parser2.statusCode && !parser2.shouldKeepAlive) { + parser2.onMessageComplete(); } this[kParser].destroy(); this[kParser] = null; @@ -7714,7 +7719,7 @@ async function connect$1(client2) { socket[kWriting] = false; socket[kReset] = false; socket[kBlocking] = false; - socket[kParser] = new Parser(client2, socket, llhttpInstance); + socket[kParser] = new Parser$1(client2, socket, llhttpInstance); } socket[kCounter] = 0; socket[kMaxRequests] = client2[kMaxRequests]; @@ -8692,7 +8697,7 @@ const { const Client$3 = client; const { InvalidArgumentError: InvalidArgumentError$f -} = errors$1; +} = errors$6; const util$d = util$j; const { kUrl: kUrl$1, kInterceptors: kInterceptors$3 } = symbols$4; const buildConnector$2 = connect$2; @@ -8768,7 +8773,7 @@ var pool = Pool$5; const { BalancedPoolMissingUpstreamError: BalancedPoolMissingUpstreamError2, InvalidArgumentError: InvalidArgumentError$e -} = errors$1; +} = errors$6; const { PoolBase: PoolBase2, kClients: kClients$2, @@ -8928,7 +8933,7 @@ var dispatcherWeakref = function() { FinalizationRegistry: commonjsGlobal.FinalizationRegistry || CompatFinalizer }; }; -const { InvalidArgumentError: InvalidArgumentError$d } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$d } = errors$6; const { kClients: kClients$1, kRunning, kClose: kClose$3, kDestroy: kDestroy$1, kDispatch, kInterceptors: kInterceptors$1 } = symbols$4; const DispatcherBase$1 = dispatcherBase; const Pool$3 = pool; @@ -9043,7 +9048,7 @@ var api$1 = {}; var apiRequest = { exports: {} }; const assert$4 = require$$0$3; const { Readable: Readable$2 } = require$$0$5; -const { RequestAbortedError: RequestAbortedError$7, NotSupportedError: NotSupportedError2, InvalidArgumentError: InvalidArgumentError$c } = errors$1; +const { RequestAbortedError: RequestAbortedError$7, NotSupportedError: NotSupportedError2, InvalidArgumentError: InvalidArgumentError$c } = errors$6; const util$b = util$j; const { ReadableStreamFrom, toUSVString: toUSVString$1 } = util$j; let Blob$1; @@ -9289,7 +9294,7 @@ function consumeFinish(consume2, err) { const assert$3 = require$$0$3; const { ResponseStatusCodeError: ResponseStatusCodeError2 -} = errors$1; +} = errors$6; const { toUSVString } = util$j; async function getResolveErrorBodyCallback$2({ callback, body: body2, contentType, statusCode, statusMessage, headers: headers2 }) { assert$3(body2); @@ -9324,7 +9329,7 @@ async function getResolveErrorBodyCallback$2({ callback, body: body2, contentTyp } var util$a = { getResolveErrorBodyCallback: getResolveErrorBodyCallback$2 }; const { addAbortListener } = util$j; -const { RequestAbortedError: RequestAbortedError$6 } = errors$1; +const { RequestAbortedError: RequestAbortedError$6 } = errors$6; const kListener = Symbol("kListener"); const kSignal = Symbol("kSignal"); function abort(self2) { @@ -9370,7 +9375,7 @@ const Readable$1 = readable; const { InvalidArgumentError: InvalidArgumentError$b, RequestAbortedError: RequestAbortedError$5 -} = errors$1; +} = errors$6; const util$9 = util$j; const { getResolveErrorBodyCallback: getResolveErrorBodyCallback$1 } = util$a; const { AsyncResource: AsyncResource$4 } = require$$4$2; @@ -9519,7 +9524,7 @@ const { InvalidArgumentError: InvalidArgumentError$a, InvalidReturnValueError: InvalidReturnValueError$1, RequestAbortedError: RequestAbortedError$4 -} = errors$1; +} = errors$6; const util$8 = util$j; const { getResolveErrorBodyCallback } = util$a; const { AsyncResource: AsyncResource$3 } = require$$4$2; @@ -9690,7 +9695,7 @@ const { InvalidArgumentError: InvalidArgumentError$9, InvalidReturnValueError: InvalidReturnValueError2, RequestAbortedError: RequestAbortedError$3 -} = errors$1; +} = errors$6; const util$7 = util$j; const { AsyncResource: AsyncResource$2 } = require$$4$2; const { addSignal: addSignal$2, removeSignal: removeSignal$2 } = abortSignal; @@ -9872,7 +9877,7 @@ function pipeline(opts, handler2) { } } var apiPipeline = pipeline; -const { InvalidArgumentError: InvalidArgumentError$8, RequestAbortedError: RequestAbortedError$2, SocketError: SocketError$1 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$8, RequestAbortedError: RequestAbortedError$2, SocketError: SocketError$1 } = errors$6; const { AsyncResource: AsyncResource$1 } = require$$4$2; const util$6 = util$j; const { addSignal: addSignal$1, removeSignal: removeSignal$1 } = abortSignal; @@ -9956,7 +9961,7 @@ function upgrade(opts, callback) { } var apiUpgrade = upgrade; const { AsyncResource } = require$$4$2; -const { InvalidArgumentError: InvalidArgumentError$7, RequestAbortedError: RequestAbortedError$1, SocketError: SocketError2 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$7, RequestAbortedError: RequestAbortedError$1, SocketError: SocketError2 } = errors$6; const util$5 = util$j; const { addSignal, removeSignal } = abortSignal; class ConnectHandler extends AsyncResource { @@ -10040,7 +10045,7 @@ api$1.stream = apiStream; api$1.pipeline = apiPipeline; api$1.upgrade = apiUpgrade; api$1.connect = apiConnect; -const { UndiciError: UndiciError$1 } = errors$1; +const { UndiciError: UndiciError$1 } = errors$6; let MockNotMatchedError$1 = class MockNotMatchedError extends UndiciError$1 { constructor(message) { super(message); @@ -10342,7 +10347,7 @@ const { kContentLength, kMockDispatch } = mockSymbols; -const { InvalidArgumentError: InvalidArgumentError$6 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$6 } = errors$6; const { buildURL } = util$j; class MockScope { constructor(mockDispatch2) { @@ -10501,7 +10506,7 @@ const { } = mockSymbols; const { MockInterceptor: MockInterceptor$1 } = mockInterceptor; const Symbols$1 = symbols$4; -const { InvalidArgumentError: InvalidArgumentError$5 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$5 } = errors$6; let MockClient$2 = class MockClient extends Client$1 { constructor(origin, opts) { super(origin, opts); @@ -10547,7 +10552,7 @@ const { } = mockSymbols; const { MockInterceptor: MockInterceptor2 } = mockInterceptor; const Symbols = symbols$4; -const { InvalidArgumentError: InvalidArgumentError$4 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$4 } = errors$6; let MockPool$2 = class MockPool extends Pool$2 { constructor(origin, opts) { super(origin, opts); @@ -10651,7 +10656,7 @@ const { const MockClient$1 = mockClient; const MockPool$1 = mockPool; const { matchValue, buildMockOptions } = mockUtils; -const { InvalidArgumentError: InvalidArgumentError$3, UndiciError: UndiciError2 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$3, UndiciError: UndiciError2 } = errors$6; const Dispatcher$1 = dispatcher; const Pluralizer2 = pluralizer; const PendingInterceptorsFormatter2 = pendingInterceptorsFormatter; @@ -10772,7 +10777,7 @@ const { URL: URL$1 } = require$$1$4; const Agent$2 = agent; const Pool$1 = pool; const DispatcherBase2 = dispatcherBase; -const { InvalidArgumentError: InvalidArgumentError$2, RequestAbortedError: RequestAbortedError2 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$2, RequestAbortedError: RequestAbortedError2 } = errors$6; const buildConnector$1 = connect$2; const kAgent = Symbol("proxy agent"); const kClient = Symbol("proxy client"); @@ -10914,7 +10919,7 @@ function throwIfProxyAuthIsSent(headers2) { var proxyAgent = ProxyAgent$1; const assert = require$$0$3; const { kRetryHandlerDefaultRetry } = symbols$4; -const { RequestRetryError: RequestRetryError2 } = errors$1; +const { RequestRetryError: RequestRetryError2 } = errors$6; const { isDisturbed, parseHeaders, parseRangeHeader } = util$j; function calculateRetryAfterHeader(retryAfter) { const current = Date.now(); @@ -11174,7 +11179,7 @@ let RetryHandler$1 = class RetryHandler { }; var RetryHandler_1 = RetryHandler$1; const globalDispatcher = Symbol.for("undici.globalDispatcher.1"); -const { InvalidArgumentError: InvalidArgumentError$1 } = errors$1; +const { InvalidArgumentError: InvalidArgumentError$1 } = errors$6; const Agent$1 = agent; if (getGlobalDispatcher$1() === void 0) { setGlobalDispatcher$1(new Agent$1()); @@ -14032,7 +14037,7 @@ function requireUtil$3() { const { serializeAMimeType, parseMIMEType } = requireDataURL(); const { types } = require$$0$2; const { StringDecoder } = require$$6; - const { btoa } = require$$7; + const { btoa: btoa2 } = require$$7; const staticPropertyDescriptors = { enumerable: true, writable: false, @@ -14124,9 +14129,9 @@ function requireUtil$3() { dataURL2 += ";base64,"; const decoder = new StringDecoder("latin1"); for (const chunk of bytes) { - dataURL2 += btoa(decoder.write(chunk)); + dataURL2 += btoa2(decoder.write(chunk)); } - dataURL2 += btoa(decoder.end()); + dataURL2 += btoa2(decoder.end()); return dataURL2; } case "Text": { @@ -15298,10 +15303,10 @@ function requireUtil$1() { }; return util$2; } -var parse$1; +var parse$3; var hasRequiredParse; function requireParse() { - if (hasRequiredParse) return parse$1; + if (hasRequiredParse) return parse$3; hasRequiredParse = 1; const { maxNameValuePairSize, maxAttributeValueSize } = requireConstants$1(); const { isCTLExcludingHtab } = requireUtil$1(); @@ -15432,11 +15437,11 @@ function requireParse() { } return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList); } - parse$1 = { + parse$3 = { parseSetCookie, parseUnparsedAttributes }; - return parse$1; + return parse$3; } var cookies; var hasRequiredCookies; @@ -16704,12 +16709,12 @@ function requireWebsocket() { */ #onConnectionEstablished(response2) { this[kResponse] = response2; - const parser = new ByteParser(this); - parser.on("drain", function onParserDrain() { + const parser2 = new ByteParser(this); + parser2.on("drain", function onParserDrain() { this.ws[kResponse].socket.resume(); }); response2.socket.ws = this; - this[kByteParser] = parser; + this[kByteParser] = parser2; this[kReadyState] = states.OPEN; const extensions = response2.headersList.get("sec-websocket-extensions"); if (extensions !== null) { @@ -16809,12 +16814,12 @@ function requireWebsocket() { } const Client2 = client; const Dispatcher2 = dispatcher; -const errors = errors$1; +const errors$5 = errors$6; const Pool2 = pool; const BalancedPool2 = balancedPool; const Agent2 = agent; const util = util$j; -const { InvalidArgumentError: InvalidArgumentError2 } = errors; +const { InvalidArgumentError: InvalidArgumentError2 } = errors$5; const api = api$1; const buildConnector = connect$2; const MockClient2 = mockClient; @@ -16846,7 +16851,7 @@ undici.DecoratorHandler = DecoratorHandler2; undici.RedirectHandler = RedirectHandler2; undici.createRedirectInterceptor = createRedirectInterceptor; undici.buildConnector = buildConnector; -undici.errors = errors; +undici.errors = errors$5; function makeDispatcher(fn) { return (url, opts, handler2) => { if (typeof opts === "function") { @@ -17604,8 +17609,8 @@ class BasicCredentialHandler { } auth$1.BasicCredentialHandler = BasicCredentialHandler; class BearerCredentialHandler { - constructor(token2) { - this.token = token2; + constructor(token) { + this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 @@ -17627,8 +17632,8 @@ class BearerCredentialHandler { } auth$1.BearerCredentialHandler = BearerCredentialHandler; class PersonalAccessTokenCredentialHandler { - constructor(token2) { - this.token = token2; + constructor(token) { + this.token = token; } // currently implements pre-authorization // TODO: support preAuth = false where it hooks on 401 @@ -17694,11 +17699,11 @@ function requireOidcUtils() { return new http_client_1.HttpClient("actions/oidc-client", [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } static getRequestToken() { - const token2 = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]; - if (!token2) { + const token = process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]; + if (!token) { throw new Error("Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable"); } - return token2; + return token; } static getIDTokenUrl() { const runtimeUrl = process.env["ACTIONS_ID_TOKEN_REQUEST_URL"]; @@ -17783,7 +17788,7 @@ function requireSummary() { exports$1.summary = exports$1.markdownSummary = exports$1.SUMMARY_DOCS_URL = exports$1.SUMMARY_ENV_VAR = void 0; const os_12 = require$$0; const fs_12 = require$$1; - const { access, appendFile, writeFile } = fs_12.promises; + const { access, appendFile: appendFile2, writeFile: writeFile2 } = fs_12.promises; exports$1.SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; exports$1.SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; class Summary { @@ -17841,7 +17846,7 @@ function requireSummary() { return __awaiter2(this, void 0, void 0, function* () { const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; + const writeFunc = overwrite ? writeFile2 : appendFile2; yield writeFunc(filePath, this._buffer, { encoding: "utf8" }); return this.emptyBuffer(); }); @@ -19571,13 +19576,13 @@ Object.defineProperty(utils, "__esModule", { value: true }); utils.getApiBaseUrl = utils.getProxyFetch = utils.getProxyAgentDispatcher = utils.getProxyAgent = utils.getAuthString = void 0; const httpClient = __importStar$1(lib); const undici_1 = undici; -function getAuthString(token2, options) { - if (!token2 && !options.auth) { +function getAuthString(token, options) { + if (!token && !options.auth) { throw new Error("Parameter token or opts.auth is required"); - } else if (token2 && options.auth) { + } else if (token && options.auth) { throw new Error("Parameters token and opts.auth may not both be specified"); } - return typeof options.auth === "string" ? options.auth : `token ${token2}`; + return typeof options.auth === "string" ? options.auth : `token ${token}`; } utils.getAuthString = getAuthString; function getProxyAgent(destinationUrl) { @@ -19730,7 +19735,7 @@ Hook.Collection = HookCollection.bind(); beforeAfterHook.exports = Hook; beforeAfterHook.exports.Hook = Hook; beforeAfterHook.exports.Singular = Hook.Singular; -var Collection = beforeAfterHook.exports.Collection = Hook.Collection; +var Collection$5 = beforeAfterHook.exports.Collection = Hook.Collection; const VERSION$5 = "9.0.6"; const userAgent = `octokit-endpoint.js/${VERSION$5} ${getUserAgent()}`; const DEFAULTS = { @@ -19786,7 +19791,7 @@ function removeUndefinedProperties(obj) { } return obj; } -function merge(defaults, route, options) { +function merge$5(defaults, route, options) { if (typeof route === "string") { let [method, url] = route.split(" "); options = Object.assign(url ? { method, url } : { url: method }, options); @@ -19970,7 +19975,7 @@ function expand(template, context2) { return template.replace(/\/$/, ""); } } -function parse(options) { +function parse$2(options) { let method = options.method.toUpperCase(); let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); let headers2 = Object.assign({}, options.headers); @@ -20034,16 +20039,16 @@ function parse(options) { ); } function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); + return parse$2(merge$5(defaults, route, options)); } function withDefaults$2(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); + const DEFAULTS2 = merge$5(oldDefaults, newDefaults); const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); return Object.assign(endpoint2, { DEFAULTS: DEFAULTS2, defaults: withDefaults$2.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse + merge: merge$5.bind(null, DEFAULTS2), + parse: parse$2 }); } const endpoint = withDefaults$2(null, DEFAULTS); @@ -20188,7 +20193,7 @@ function getBufferResponse(response2) { return response2.arrayBuffer(); } function fetchWrapper(requestOptions) { - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const log2 = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false; if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); @@ -20223,7 +20228,7 @@ function fetchWrapper(requestOptions) { if ("deprecation" in headers2) { const matches = headers2.link && headers2.link.match(/<([^<>]+)>; rel="deprecation"/); const deprecationLink = matches && matches.pop(); - log.warn( + log2.warn( `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers2.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` ); } @@ -20454,43 +20459,43 @@ function withCustomRequest(customRequest) { const REGEX_IS_INSTALLATION_LEGACY = /^v1\./; const REGEX_IS_INSTALLATION = /^ghs_/; const REGEX_IS_USER_TO_SERVER = /^ghu_/; -async function auth(token2) { - const isApp = token2.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token2) || REGEX_IS_INSTALLATION.test(token2); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token2); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType2 = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; return { type: "token", - token: token2, - tokenType + token, + tokenType: tokenType2 }; } -function withAuthorizationPrefix(token2) { - if (token2.split(/\./).length === 3) { - return `bearer ${token2}`; +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; } - return `token ${token2}`; + return `token ${token}`; } -async function hook(token2, request2, route, parameters) { +async function hook(token, request2, route, parameters) { const endpoint2 = request2.endpoint.merge( route, parameters ); - endpoint2.headers.authorization = withAuthorizationPrefix(token2); + endpoint2.headers.authorization = withAuthorizationPrefix(token); return request2(endpoint2); } -const createTokenAuth = function createTokenAuth2(token2) { - if (!token2) { +const createTokenAuth = function createTokenAuth2(token) { + if (!token) { throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } - if (typeof token2 !== "string") { + if (typeof token !== "string") { throw new Error( "[@octokit/auth-token] Token passed to createTokenAuth is not a string" ); } - token2 = token2.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token2), { - hook: hook.bind(null, token2) + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) }); }; var VERSION$2 = "5.2.2"; @@ -20561,7 +20566,7 @@ var Octokit = class { return NewOctokit; } constructor(options = {}) { - const hook2 = new Collection(); + const hook2 = new Collection$5(); const requestDefaults = { baseUrl: request.endpoint.DEFAULTS.baseUrl, headers: {}, @@ -22670,7 +22675,7 @@ const handler = { set(target, methodName, value) { return target.cache[methodName] = value; }, - get({ octokit: octokit2, scope, cache: cache2 }, methodName) { + get({ octokit, scope, cache: cache2 }, methodName) { if (cache2[methodName]) { return cache2[methodName]; } @@ -22681,27 +22686,27 @@ const handler = { const { endpointDefaults, decorations } = method; if (decorations) { cache2[methodName] = decorate( - octokit2, + octokit, scope, methodName, endpointDefaults, decorations ); } else { - cache2[methodName] = octokit2.request.defaults(endpointDefaults); + cache2[methodName] = octokit.request.defaults(endpointDefaults); } return cache2[methodName]; } }; -function endpointsToMethods(octokit2) { +function endpointsToMethods(octokit) { const newMethods = {}; for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit: octokit2, scope, cache: {} }, handler); + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); } return newMethods; } -function decorate(octokit2, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit2.request.defaults(defaults); +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); function withDecorations(...args) { let options = requestWithDefaults.endpoint.merge(...args); if (decorations.mapToData) { @@ -22713,12 +22718,12 @@ function decorate(octokit2, scope, methodName, defaults, decorations) { } if (decorations.renamed) { const [newScope, newMethodName] = decorations.renamed; - octokit2.log.warn( + octokit.log.warn( `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` ); } if (decorations.deprecated) { - octokit2.log.warn(decorations.deprecated); + octokit.log.warn(decorations.deprecated); } if (decorations.renamedParameters) { const options2 = requestWithDefaults.endpoint.merge(...args); @@ -22726,7 +22731,7 @@ function decorate(octokit2, scope, methodName, defaults, decorations) { decorations.renamedParameters )) { if (name in options2) { - octokit2.log.warn( + octokit.log.warn( `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` ); if (!(alias in options2)) { @@ -22741,15 +22746,15 @@ function decorate(octokit2, scope, methodName, defaults, decorations) { } return Object.assign(withDecorations, requestWithDefaults); } -function restEndpointMethods(octokit2) { - const api2 = endpointsToMethods(octokit2); +function restEndpointMethods(octokit) { + const api2 = endpointsToMethods(octokit); return { rest: api2 }; } restEndpointMethods.VERSION = VERSION$1; -function legacyRestEndpointMethods(octokit2) { - const api2 = endpointsToMethods(octokit2); +function legacyRestEndpointMethods(octokit) { + const api2 = endpointsToMethods(octokit); return { ...api2, rest: api2 @@ -22791,9 +22796,9 @@ function normalizePaginatedListResponse(response2) { response2.data.total_count = totalCount; return response2; } -function iterator(octokit2, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit2.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit2.request; +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; const method = options.method; const headers2 = options.headers; let url = options.url; @@ -22825,19 +22830,19 @@ function iterator(octokit2, route, parameters) { }) }; } -function paginate(octokit2, route, parameters, mapFn) { +function paginate(octokit, route, parameters, mapFn) { if (typeof parameters === "function") { mapFn = parameters; parameters = void 0; } return gather( - octokit2, + octokit, [], - iterator(octokit2, route, parameters)[Symbol.asyncIterator](), + iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn ); } -function gather(octokit2, results, iterator2, mapFn) { +function gather(octokit, results, iterator2, mapFn) { return iterator2.next().then((result) => { if (result.done) { return results; @@ -22852,7 +22857,7 @@ function gather(octokit2, results, iterator2, mapFn) { if (earlyExit) { return results; } - return gather(octokit2, results, iterator2, mapFn); + return gather(octokit, results, iterator2, mapFn); }); } var composePaginateRest = Object.assign(paginate, { @@ -23101,10 +23106,10 @@ function isPaginatingEndpoint(arg) { return false; } } -function paginateRest(octokit2) { +function paginateRest(octokit) { return { - paginate: Object.assign(paginate.bind(null, octokit2), { - iterator: iterator.bind(null, octokit2) + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) }) }; } @@ -23162,9 +23167,9 @@ const require$$4 = /* @__PURE__ */ getAugmentedNamespace(distWeb); } }; exports$1.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports$1.defaults); - function getOctokitOptions(token2, options) { + function getOctokitOptions(token, options) { const opts = Object.assign({}, options || {}); - const auth2 = Utils.getAuthString(token2, opts); + const auth2 = Utils.getAuthString(token, opts); if (auth2) { opts.auth = auth2; } @@ -23204,167 +23209,7145 @@ var getOctokit_1 = github.getOctokit = context = github.context = void 0; const Context2 = __importStar(context$1); const utils_1 = utils$1; var context = github.context = new Context2.Context(); -function getOctokit(token2, options, ...additionalPlugins) { +function getOctokit(token, options, ...additionalPlugins) { const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token2, options)); + return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); } getOctokit_1 = github.getOctokit = getOctokit; var execExports = requireExec(); -class StagingAutoMerge { - constructor(octokit2, primaryBranch2, repo, logger = console) { - if (!primaryBranch2) { - throw new Error("Primary branch is required."); +var composer$1 = {}; +var directives$2 = {}; +var identity$x = {}; +const ALIAS = Symbol.for("yaml.alias"); +const DOC = Symbol.for("yaml.document"); +const MAP = Symbol.for("yaml.map"); +const PAIR = Symbol.for("yaml.pair"); +const SCALAR$1 = Symbol.for("yaml.scalar"); +const SEQ = Symbol.for("yaml.seq"); +const NODE_TYPE = Symbol.for("yaml.node.type"); +const isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; +const isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; +const isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; +const isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; +const isScalar$1 = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR$1; +const isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; +function isCollection$1(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; } - if (!repo?.owner || !repo?.repo) { - throw new Error("Repository owner and name are required."); + return false; +} +function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR$1: + case SEQ: + return true; } - this.octokit = octokit2; - this.logger = logger; - this.primaryBranch = primaryBranch2; - this.repo = repo; - } - async run() { - await this.validateStagingLabel(); - await this.configureGitUser(); - await this.resetToPrimaryBranch(); - await this.mergeStagedPullRequests(); - await this.pushChanges(); - await this.cleanupClosedPullRequests(); - } - async configureGitUser() { - await this.exec('git config --global user.email "github-actions@github.com"'); - await this.exec('git config --global user.name "github-actions"'); + return false; +} +const hasAnchor = (node) => (isScalar$1(node) || isCollection$1(node)) && !!node.anchor; +identity$x.ALIAS = ALIAS; +identity$x.DOC = DOC; +identity$x.MAP = MAP; +identity$x.NODE_TYPE = NODE_TYPE; +identity$x.PAIR = PAIR; +identity$x.SCALAR = SCALAR$1; +identity$x.SEQ = SEQ; +identity$x.hasAnchor = hasAnchor; +identity$x.isAlias = isAlias; +identity$x.isCollection = isCollection$1; +identity$x.isDocument = isDocument; +identity$x.isMap = isMap; +identity$x.isNode = isNode; +identity$x.isPair = isPair; +identity$x.isScalar = isScalar$1; +identity$x.isSeq = isSeq; +var visit$6 = {}; +var identity$w = identity$x; +const BREAK$1 = Symbol("break visit"); +const SKIP$1 = Symbol("skip children"); +const REMOVE$1 = Symbol("remove node"); +function visit$5(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity$w.isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE$1) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); +} +visit$5.BREAK = BREAK$1; +visit$5.SKIP = SKIP$1; +visit$5.REMOVE = REMOVE$1; +function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (identity$w.isNode(ctrl) || identity$w.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity$w.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity$w.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node.value = null; + } + } + return ctrl; +} +async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity$w.isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE$1) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); +} +visitAsync.BREAK = BREAK$1; +visitAsync.SKIP = SKIP$1; +visitAsync.REMOVE = REMOVE$1; +async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (identity$w.isNode(ctrl) || identity$w.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity$w.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0; i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK$1) + return BREAK$1; + else if (ci === REMOVE$1) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity$w.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK$1) + return BREAK$1; + else if (ck === REMOVE$1) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK$1) + return BREAK$1; + else if (cv === REMOVE$1) + node.value = null; + } + } + return ctrl; +} +function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; +} +function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (identity$w.isMap(node)) + return visitor.Map?.(key, node, path); + if (identity$w.isSeq(node)) + return visitor.Seq?.(key, node, path); + if (identity$w.isPair(node)) + return visitor.Pair?.(key, node, path); + if (identity$w.isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (identity$w.isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; +} +function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (identity$w.isCollection(parent)) { + parent.items[key] = node; + } else if (identity$w.isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (identity$w.isDocument(parent)) { + parent.contents = node; + } else { + const pt = identity$w.isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } +} +visit$6.visit = visit$5; +visit$6.visitAsync = visitAsync; +var identity$v = identity$x; +var visit$4 = visit$6; +const escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" +}; +const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +class Directives { + constructor(yaml, tags2) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags2); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; } - async resetToPrimaryBranch() { - await this.exec("git", ["reset", "--hard", `origin/${this.primaryBranch}`]); + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; } - async validateStagingLabel() { - this.stagingLabelName = await this.findStagingLabelName(); - if (!this.stagingLabelName) { - throw new Error('Required label "Staging" was not found in this repository.'); + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError2) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError2(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError2(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError2(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError2(0, `Unknown directive ${name}`, true); + return false; } - this.logger.info("Label Name: ", this.stagingLabelName); } - async mergeStagedPullRequests() { - const pullRequests = await this.octokit.paginate(this.octokit.rest.pulls.list, { - ...this.repo, - state: "open", - sort: "created", - direction: "asc", - per_page: 100 - }); - for (const pr of pullRequests) { - if (this.hasStagingLabel(pr.labels)) { - await this.mergePullRequest(pr); + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError2) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError2(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError2(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError2("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError2(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError2(String(error)); + return null; } } + if (handle === "!") + return source; + onError2(`Could not resolve tag: ${source}`); + return null; } - async mergePullRequest(pr) { - const { title, number, head: { ref: branch } } = pr; - let execOutput = ""; - let execError = ""; - const options = { - listeners: { - stdout: (data) => { - execOutput += data.toString(); - }, - stderr: (data) => { - execError += data.toString(); + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && identity$v.isNode(doc.contents)) { + const tags2 = {}; + visit$4.visit(doc.contents, (_key, node) => { + if (identity$v.isNode(node) && node.tag) + tags2[node.tag] = true; + }); + tagNames = Object.keys(tags2); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } +} +Directives.defaultYaml = { explicit: false, version: "1.2" }; +Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; +directives$2.Directives = Directives; +var Document$4 = {}; +var Alias$4 = {}; +var anchors$3 = {}; +var identity$u = identity$x; +var visit$3 = visit$6; +function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; +} +function anchorNames(root) { + const anchors2 = /* @__PURE__ */ new Set(); + visit$3.visit(root, { + Value(_key, node) { + if (node.anchor) + anchors2.add(node.anchor); + } + }); + return anchors2; +} +function findNewAnchor(prefix, exclude) { + for (let i = 1; true; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } +} +function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (identity$u.isScalar(ref.node) || identity$u.isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; +} +anchors$3.anchorIsValid = anchorIsValid; +anchors$3.anchorNames = anchorNames; +anchors$3.createNodeAnchors = createNodeAnchors; +anchors$3.findNewAnchor = findNewAnchor; +var Node$3 = {}; +var applyReviver$3 = {}; +function applyReviver$2(reviver, obj, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length; i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver$2(reviver, val, String(i), v0); + if (v1 === void 0) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver$2(reviver, val, k, v0); + if (v1 === void 0) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver$2(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); } } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver$2(reviver, val, k, v0); + if (v1 === void 0) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key, val); +} +applyReviver$3.applyReviver = applyReviver$2; +var toJS$8 = {}; +var identity$t = identity$x; +function toJS$7(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJS$7(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !identity$t.hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; }; - try { - await this.exec("git", ["merge", `origin/${branch}`, "--squash", "--verbose"], options); - await this.exec("git", ["commit", "-m", title]); - } catch (error) { - await this.abortMerge(); - await this.createMergeConflictComment(number, execOutput, execError); - await this.removeStagingLabel(number); - } + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; } - async abortMerge() { - await this.exec("git restore --staged ."); - await this.exec("git restore ."); - await this.exec("git clean -df"); + if (typeof value === "bigint" && !ctx?.keep) + return Number(value); + return value; +} +toJS$8.toJS = toJS$7; +var applyReviver$1 = applyReviver$3; +var identity$s = identity$x; +var toJS$6 = toJS$8; +class NodeBase { + constructor(type) { + Object.defineProperty(this, identity$s.NODE_TYPE, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!identity$s.isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS$6.toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver$1.applyReviver(reviver, { "": res }, "", res) : res; + } +} +Node$3.NodeBase = NodeBase; +var anchors$2 = anchors$3; +var visit$2 = visit$6; +var identity$r = identity$x; +var Node$2 = Node$3; +var toJS$5 = toJS$8; +let Alias$3 = class Alias extends Node$2.NodeBase { + constructor(source) { + super(identity$r.ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); } - async pushChanges() { - await this.exec("git push --force"); + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit$2.visit(doc, { + Node: (_key, node) => { + if (identity$r.isAlias(node) || identity$r.hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + if (found && ctx) { + const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx; + let data = anchors2.get(found); + if (!data) { + toJS$5.toJS(found, null, ctx); + data = anchors2.get(found); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc2, found, anchors2); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + } + return found; } - async cleanupClosedPullRequests() { - const closedPullRequests = await this.octokit.paginate(this.octokit.rest.issues.listForRepo, { - ...this.repo, - state: "closed", - labels: this.stagingLabelName, - per_page: 100 - }); - for (const closedPr of closedPullRequests) { - if (closedPr.pull_request) { - this.logger.info("removing label from: ", closedPr.title); - await this.removeStagingLabel(closedPr.number); + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const source = this.resolve(ctx.doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + return ctx.anchors.get(source).res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchors$2.anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); } + if (ctx.implicitKey) + return `${src} `; } + return src; } - async exec(command2, args, options) { - return execExports.exec(command2, args, options); +}; +function getAliasCount(doc, node, anchors2) { + if (identity$r.isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors2 && source && anchors2.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (identity$r.isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors2); + if (c > count) + count = c; + } + return count; + } else if (identity$r.isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors2); + const vc = getAliasCount(doc, node.value, anchors2); + return Math.max(kc, vc); + } + return 1; +} +Alias$4.Alias = Alias$3; +var Collection$4 = {}; +var createNode$5 = {}; +var Scalar$k = {}; +var identity$q = identity$x; +var Node$1 = Node$3; +var toJS$4 = toJS$8; +const isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; +let Scalar$j = class Scalar extends Node$1.NodeBase { + constructor(value) { + super(identity$q.SCALAR); + this.value = value; } - extractFilenamesFromConflicts(logText) { - const regex = /CONFLICT \(content\): Merge conflict in\s+([^\n]+)/g; - const matches = []; - let match; - while ((match = regex.exec(logText)) !== null) { - matches.push(match[1]); + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS$4.toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } +}; +Scalar$j.BLOCK_FOLDED = "BLOCK_FOLDED"; +Scalar$j.BLOCK_LITERAL = "BLOCK_LITERAL"; +Scalar$j.PLAIN = "PLAIN"; +Scalar$j.QUOTE_DOUBLE = "QUOTE_DOUBLE"; +Scalar$j.QUOTE_SINGLE = "QUOTE_SINGLE"; +Scalar$k.Scalar = Scalar$j; +Scalar$k.isScalarValue = isScalarValue; +var Alias$2 = Alias$4; +var identity$p = identity$x; +var Scalar$i = Scalar$k; +const defaultTagPrefix = "tag:yaml.org,2002:"; +function findTagObject(value, tagName, tags2) { + if (tagName) { + const match = tags2.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags2.find((t) => t.identify?.(value) && !t.format); +} +function createNode$4(value, tagName, ctx) { + if (identity$p.isDocument(value)) + value = value.contents; + if (identity$p.isNode(value)) + return value; + if (identity$p.isPair(value)) { + const map2 = ctx.schema[identity$p.MAP].createNode?.(ctx.schema, null, ctx); + map2.items.push(value); + return map2; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema2, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias$2.Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema2.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); + } + if (!value || typeof value !== "object") { + const node2 = new Scalar$i.Scalar(value); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value instanceof Map ? schema2[identity$p.MAP] : Symbol.iterator in Object(value) ? schema2[identity$p.SEQ] : schema2[identity$p.MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar$i.Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; +} +createNode$5.createNode = createNode$4; +var createNode$3 = createNode$5; +var identity$o = identity$x; +var Node = Node$3; +function collectionFromPath(schema2, path, value) { + let v = value; + for (let i = path.length - 1; i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = /* @__PURE__ */ new Map([[k, v]]); } - return matches; } - formatCommentBody(mergeConflictMessage, consoleErrorMessage) { - const formattedConflictFiles = this.extractFilenamesFromConflicts(mergeConflictMessage).join("\n"); - let conflictMessage = `Merge Conflicts in these files: -${formattedConflictFiles}`; - if (consoleErrorMessage) { - conflictMessage += ` - -Merge Command Error: ${consoleErrorMessage}`; + return createNode$3.createNode(v, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema2, + sourceObjects: /* @__PURE__ */ new Map() + }); +} +const isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; +let Collection$3 = class Collection extends Node.NodeBase { + constructor(type, schema2) { + super(type); + Object.defineProperty(this, "schema", { + value: schema2, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema2) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema2) + copy.schema = schema2; + copy.items = copy.items.map((it) => identity$o.isNode(it) || identity$o.isPair(it) ? it.clone(schema2) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (identity$o.isCollection(node)) + node.addIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } - return conflictMessage; } - hasStagingLabel(labels) { - return labels.some((label) => label.name.toLowerCase() === this.stagingLabelName.toLowerCase()); + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (identity$o.isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } - async findStagingLabelName() { - const repoLabels = await this.octokit.paginate(this.octokit.rest.issues.listLabelsForRepo, { - owner: this.repo.owner, - repo: this.repo.repo, - per_page: 100 + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && identity$o.isScalar(node) ? node.value : node; + else + return identity$o.isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!identity$o.isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && identity$o.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; }); - return repoLabels.find((label) => label.name.toLowerCase() === "staging")?.name; } - async removeStagingLabel(issueNumber) { - if (!this.stagingLabelName) return; - try { - await this.octokit.rest.issues.removeLabel({ - owner: this.repo.owner, - repo: this.repo.repo, - issue_number: issueNumber, - name: this.stagingLabelName - }); - } catch (error) { - const status = error?.status; - if (status !== 404) { - throw error; + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return identity$o.isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (identity$o.isCollection(node)) + node.setIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } +}; +Collection$4.Collection = Collection$3; +Collection$4.collectionFromPath = collectionFromPath; +Collection$4.isEmptyPath = isEmptyPath; +var Pair$8 = {}; +var stringifyPair$2 = {}; +var stringify$7 = {}; +var stringifyComment$5 = {}; +const stringifyComment$4 = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); +function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; +} +const lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; +stringifyComment$5.indentComment = indentComment; +stringifyComment$5.lineComment = lineComment; +stringifyComment$5.stringifyComment = stringifyComment$4; +var stringifyString$5 = {}; +var foldFlowLines$2 = {}; +const FOLD_FLOW = "flow"; +const FOLD_BLOCK = "block"; +const FOLD_QUOTED = "quoted"; +function foldFlowLines$1(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch; ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text[i + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = void 0; + } else { + overflow = true; + } } } + prev = ch; } - async createMergeConflictComment(issueNumber, execOutput, execError) { - await this.octokit.rest.issues.createComment({ - owner: this.repo.owner, - repo: this.repo.repo, + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0; i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; +} +function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === " ") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== "\n"); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; +} +foldFlowLines$2.FOLD_BLOCK = FOLD_BLOCK; +foldFlowLines$2.FOLD_FLOW = FOLD_FLOW; +foldFlowLines$2.FOLD_QUOTED = FOLD_QUOTED; +foldFlowLines$2.foldFlowLines = foldFlowLines$1; +var Scalar$h = Scalar$k; +var foldFlowLines = foldFlowLines$2; +const getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth +}); +const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); +function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0; i < strLen; ++i) { + if (str[i] === "\n") { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; +} +function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i]; ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str += json.slice(start, i) + "\n\n"; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str += "\n"; + i += 2; + } + str += indent; + if (json[i + 2] === " ") + str += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); +} +function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); +} +function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); +} +let blockEndNewlines; +try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar$h.Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body2 = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body2}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value}${end}`; +} +function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar$h.Scalar.PLAIN && value.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); + const { compat, tags: tags2 } = ctx.doc.schema; + if (tags2.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); +} +function stringifyString$4(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar$h.Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar$h.Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar$h.Scalar.BLOCK_FOLDED: + case Scalar$h.Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar$h.Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar$h.Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar$h.Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; +} +stringifyString$5.stringifyString = stringifyString$4; +var anchors$1 = anchors$3; +var identity$n = identity$x; +var stringifyComment$3 = stringifyComment$5; +var stringifyString$3 = stringifyString$5; +function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment$3.stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; +} +function getTagObject(tags2, item) { + if (item.tag) { + const match = tags2.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj; + if (identity$n.isScalar(item)) { + obj = item.value; + let match = tags2.filter((t) => t.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj = item; + tagObj = tags2.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; +} +function stringifyProps(node, tagObj, { anchors: anchors$1$1, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (identity$n.isScalar(node) || identity$n.isCollection(node)) && node.anchor; + if (anchor && anchors$1.anchorIsValid(anchor)) { + anchors$1$1.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); +} +function stringify$6(item, ctx, onComment, onChompKeep) { + if (identity$n.isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (identity$n.isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = identity$n.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity$n.isScalar(node) ? stringifyString$3.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return identity$n.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} +${ctx.indent}${str}`; +} +stringify$7.createStringifyContext = createStringifyContext; +stringify$7.stringify = stringify$6; +var identity$m = identity$x; +var Scalar$g = Scalar$k; +var stringify$5 = stringify$7; +var stringifyComment$2 = stringifyComment$5; +function stringifyPair$1({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = identity$m.isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (identity$m.isCollection(key) || !identity$m.isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity$m.isCollection(key) || (identity$m.isScalar(key) ? key.type === Scalar$g.Scalar.BLOCK_FOLDED || key.type === Scalar$g.Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify$5.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += stringifyComment$2.lineComment(str, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += stringifyComment$2.lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str} +${indent}:`; + } else { + str = `${str}:`; + if (keyComment) + str += stringifyComment$2.lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (identity$m.isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && identity$m.isScalar(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity$m.isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify$5.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${stringifyComment$2.indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && identity$m.isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str += stringifyComment$2.lineComment(str, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; +} +stringifyPair$2.stringifyPair = stringifyPair$1; +var addPairToJSMap$3 = {}; +var log$2 = {}; +var node_process$2 = require$$0$a; +function debug(logLevel, ...messages) { + if (logLevel === "debug") + console.log(...messages); +} +function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + if (typeof node_process$2.emitWarning === "function") + node_process$2.emitWarning(warning); + else + console.warn(warning); + } +} +log$2.debug = debug; +log$2.warn = warn; +var merge$4 = {}; +var identity$l = identity$x; +var Scalar$f = Scalar$k; +const MERGE_KEY = "<<"; +const merge$3 = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar$f.Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY +}; +const isMergeKey = (ctx, key) => (merge$3.identify(key) || identity$l.isScalar(key) && (!key.type || key.type === Scalar$f.Scalar.PLAIN) && merge$3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge$3.tag && tag.default); +function addMergeToJSMap(ctx, map2, value) { + const source = resolveAliasValue(ctx, value); + if (identity$l.isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map2, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map2, it); + else + mergeValue(ctx, map2, source); +} +function mergeValue(ctx, map2, value) { + const source = resolveAliasValue(ctx, value); + if (!identity$l.isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value2] of srcMap) { + if (map2 instanceof Map) { + if (!map2.has(key)) + map2.set(key, value2); + } else if (map2 instanceof Set) { + map2.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map2, key)) { + Object.defineProperty(map2, key, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map2; +} +function resolveAliasValue(ctx, value) { + return ctx && identity$l.isAlias(value) ? value.resolve(ctx.doc, ctx) : value; +} +merge$4.addMergeToJSMap = addMergeToJSMap; +merge$4.isMergeKey = isMergeKey; +merge$4.merge = merge$3; +var log$1 = log$2; +var merge$2 = merge$4; +var stringify$4 = stringify$7; +var identity$k = identity$x; +var toJS$3 = toJS$8; +function addPairToJSMap$2(ctx, map2, { key, value }) { + if (identity$k.isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map2, value); + else if (merge$2.isMergeKey(ctx, key)) + merge$2.addMergeToJSMap(ctx, map2, value); + else { + const jsKey = toJS$3.toJS(key, "", ctx); + if (map2 instanceof Map) { + map2.set(jsKey, toJS$3.toJS(value, jsKey, ctx)); + } else if (map2 instanceof Set) { + map2.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS$3.toJS(value, stringKey, ctx); + if (stringKey in map2) + Object.defineProperty(map2, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map2[stringKey] = jsValue; + } + } + return map2; +} +function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (identity$k.isNode(key) && ctx?.doc) { + const strCtx = stringify$4.createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + log$1.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); +} +addPairToJSMap$3.addPairToJSMap = addPairToJSMap$2; +var createNode$2 = createNode$5; +var stringifyPair = stringifyPair$2; +var addPairToJSMap$1 = addPairToJSMap$3; +var identity$j = identity$x; +function createPair(key, value, ctx) { + const k = createNode$2.createNode(key, void 0, ctx); + const v = createNode$2.createNode(value, void 0, ctx); + return new Pair$7(k, v); +} +let Pair$7 = class Pair { + constructor(key, value = null) { + Object.defineProperty(this, identity$j.NODE_TYPE, { value: identity$j.PAIR }); + this.key = key; + this.value = value; + } + clone(schema2) { + let { key, value } = this; + if (identity$j.isNode(key)) + key = key.clone(schema2); + if (identity$j.isNode(value)) + value = value.clone(schema2); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap$1.addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } +}; +Pair$8.Pair = Pair$7; +Pair$8.createPair = createPair; +var Schema$2 = {}; +var map$6 = {}; +var YAMLMap$8 = {}; +var stringifyCollection$3 = {}; +var identity$i = identity$x; +var stringify$3 = stringify$7; +var stringifyComment$1 = stringifyComment$5; +function stringifyCollection$2(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify2(collection, ctx, options); +} +function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (identity$i.isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (identity$i.isPair(item)) { + const ik = identity$i.isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str2 = stringify$3.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str2 += stringifyComment$1.lineComment(str2, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines.push(blockItemPrefix + str2); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } else { + str = lines[0]; + for (let i = 1; i < lines.length; ++i) { + const line = lines[i]; + str += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str += "\n" + stringifyComment$1.indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; +} +function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0; i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity$i.isNode(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (identity$i.isPair(item)) { + const ik = identity$i.isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = identity$i.isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify$3.stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n")); + if (i < items.length - 1) { + str += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str += ","; + } + } + if (comment) + str += stringifyComment$1.lineComment(str, itemIndent, commentString(comment)); + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } +} +function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = stringifyComment$1.indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } +} +stringifyCollection$3.stringifyCollection = stringifyCollection$2; +var stringifyCollection$1 = stringifyCollection$3; +var addPairToJSMap = addPairToJSMap$3; +var Collection$2 = Collection$4; +var identity$h = identity$x; +var Pair$6 = Pair$8; +var Scalar$e = Scalar$k; +function findPair(items, key) { + const k = identity$h.isScalar(key) ? key.value : key; + for (const it of items) { + if (identity$h.isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (identity$h.isScalar(it.key) && it.key.value === k) + return it; + } + } + return void 0; +} +let YAMLMap$7 = class YAMLMap extends Collection$2.Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema2) { + super(identity$h.MAP, schema2); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema2, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map2 = new this(schema2); + const add2 = (key, value) => { + if (typeof replacer === "function") + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== void 0 || keepUndefined) + map2.items.push(Pair$6.createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add2(key, value); + } else if (obj && typeof obj === "object") { + for (const key of Object.keys(obj)) + add2(key, obj[key]); + } + if (typeof schema2.sortMapEntries === "function") { + map2.items.sort(schema2.sortMapEntries); + } + return map2; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (identity$h.isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair$6.Pair(pair, pair?.value); + } else + _pair = new Pair$6.Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (identity$h.isScalar(prev.value) && Scalar$e.isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && identity$h.isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair$6.Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_, ctx, Type) { + const map2 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map2); + for (const item of this.items) + addPairToJSMap.addPairToJSMap(ctx, map2, item); + return map2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!identity$h.isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection$1.stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } +}; +YAMLMap$8.YAMLMap = YAMLMap$7; +YAMLMap$8.findPair = findPair; +var identity$g = identity$x; +var YAMLMap$6 = YAMLMap$8; +const map$5 = { + collection: "map", + default: true, + nodeClass: YAMLMap$6.YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map2, onError2) { + if (!identity$g.isMap(map2)) + onError2("Expected a mapping for this tag"); + return map2; + }, + createNode: (schema2, obj, ctx) => YAMLMap$6.YAMLMap.from(schema2, obj, ctx) +}; +map$6.map = map$5; +var seq$6 = {}; +var YAMLSeq$7 = {}; +var createNode$1 = createNode$5; +var stringifyCollection = stringifyCollection$3; +var Collection$1 = Collection$4; +var identity$f = identity$x; +var Scalar$d = Scalar$k; +var toJS$2 = toJS$8; +let YAMLSeq$6 = class YAMLSeq extends Collection$1.Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema2) { + super(identity$f.SEQ, schema2); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && identity$f.isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (identity$f.isScalar(prev) && Scalar$d.isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i = 0; + for (const item of this.items) + seq2.push(toJS$2.toJS(item, String(i++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema2, obj, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema2); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq2.items.push(createNode$1.createNode(it, void 0, ctx)); + } + } + return seq2; + } +}; +function asItemIndex(key) { + let idx = identity$f.isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; +} +YAMLSeq$7.YAMLSeq = YAMLSeq$6; +var identity$e = identity$x; +var YAMLSeq$5 = YAMLSeq$7; +const seq$5 = { + collection: "seq", + default: true, + nodeClass: YAMLSeq$5.YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError2) { + if (!identity$e.isSeq(seq2)) + onError2("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema2, obj, ctx) => YAMLSeq$5.YAMLSeq.from(schema2, obj, ctx) +}; +seq$6.seq = seq$5; +var string$5 = {}; +var stringifyString$2 = stringifyString$5; +const string$4 = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString$2.stringifyString(item, ctx, onComment, onChompKeep); + } +}; +string$5.string = string$4; +var tags$1 = {}; +var _null$3 = {}; +var Scalar$c = Scalar$k; +const nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar$c.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar$c.Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +}; +_null$3.nullTag = nullTag; +var bool$4 = {}; +var Scalar$b = Scalar$k; +const boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar$b.Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } +}; +bool$4.boolTag = boolTag; +var float$6 = {}; +var stringifyNumber$6 = {}; +function stringifyNumber$5({ format, minFractionDigits, tag, value }) { + if (typeof value === "bigint") + return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n = Object.is(value, -0) ? "-0" : JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; +} +stringifyNumber$6.stringifyNumber = stringifyNumber$5; +var Scalar$a = Scalar$k; +var stringifyNumber$4 = stringifyNumber$6; +const floatNaN$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber$4.stringifyNumber +}; +const floatExp$1 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber$4.stringifyNumber(node); + } +}; +const float$5 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar$a.Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber$4.stringifyNumber +}; +float$6.float = float$5; +float$6.floatExp = floatExp$1; +float$6.floatNaN = floatNaN$1; +var int$6 = {}; +var stringifyNumber$3 = stringifyNumber$6; +const intIdentify$2 = (value) => typeof value === "bigint" || Number.isInteger(value); +const intResolve$1 = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); +function intStringify$1(node, radix, prefix) { + const { value } = node; + if (intIdentify$2(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber$3.stringifyNumber(node); +} +const intOct$1 = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt), + stringify: (node) => intStringify$1(node, 8, "0o") +}; +const int$5 = { + identify: intIdentify$2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt), + stringify: stringifyNumber$3.stringifyNumber +}; +const intHex$1 = { + identify: (value) => intIdentify$2(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt), + stringify: (node) => intStringify$1(node, 16, "0x") +}; +int$6.int = int$5; +int$6.intHex = intHex$1; +int$6.intOct = intOct$1; +var schema$8 = {}; +var map$4 = map$6; +var _null$2 = _null$3; +var seq$4 = seq$6; +var string$3 = string$5; +var bool$3 = bool$4; +var float$4 = float$6; +var int$4 = int$6; +const schema$7 = [ + map$4.map, + seq$4.seq, + string$3.string, + _null$2.nullTag, + bool$3.boolTag, + int$4.intOct, + int$4.int, + int$4.intHex, + float$4.floatNaN, + float$4.floatExp, + float$4.float +]; +schema$8.schema = schema$7; +var schema$6 = {}; +var Scalar$9 = Scalar$k; +var map$3 = map$6; +var seq$3 = seq$6; +function intIdentify$1(value) { + return typeof value === "bigint" || Number.isInteger(value); +} +const stringifyJSON = ({ value }) => JSON.stringify(value); +const jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar$9.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify$1, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } +]; +const jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str, onError2) { + onError2(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } +}; +const schema$5 = [map$3.map, seq$3.seq].concat(jsonScalars, jsonError); +schema$6.schema = schema$5; +var binary$3 = {}; +var node_buffer = require$$7; +var Scalar$8 = Scalar$k; +var stringifyString$1 = stringifyString$5; +const binary$2 = { + identify: (value) => value instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError2) { + if (typeof node_buffer.Buffer === "function") { + return node_buffer.Buffer.from(src, "base64"); + } else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } else { + onError2("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) + return ""; + const buf = value; + let str; + if (typeof node_buffer.Buffer === "function") { + str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); + } else if (typeof btoa === "function") { + let s = ""; + for (let i = 0; i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar$8.Scalar.BLOCK_LITERAL); + if (type !== Scalar$8.Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar$8.Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString$1.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } +}; +binary$3.binary = binary$2; +var omap$3 = {}; +var pairs$4 = {}; +var identity$d = identity$x; +var Pair$5 = Pair$8; +var Scalar$7 = Scalar$k; +var YAMLSeq$4 = YAMLSeq$7; +function resolvePairs(seq2, onError2) { + if (identity$d.isSeq(seq2)) { + for (let i = 0; i < seq2.items.length; ++i) { + let item = seq2.items[i]; + if (identity$d.isPair(item)) + continue; + else if (identity$d.isMap(item)) { + if (item.items.length > 1) + onError2("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair$5.Pair(new Scalar$7.Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i] = identity$d.isPair(item) ? item : new Pair$5.Pair(item); + } + } else + onError2("Expected a sequence for this tag"); + return seq2; +} +function createPairs(schema2, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq$4.YAMLSeq(schema2); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(Pair$5.createPair(key, value, ctx)); + } + return pairs2; +} +const pairs$3 = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs +}; +pairs$4.createPairs = createPairs; +pairs$4.pairs = pairs$3; +pairs$4.resolvePairs = resolvePairs; +var identity$c = identity$x; +var toJS$1 = toJS$8; +var YAMLMap$5 = YAMLMap$8; +var YAMLSeq$3 = YAMLSeq$7; +var pairs$2 = pairs$4; +class YAMLOMap extends YAMLSeq$3.YAMLSeq { + constructor() { + super(); + this.add = YAMLMap$5.YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap$5.YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap$5.YAMLMap.prototype.get.bind(this); + this.has = YAMLMap$5.YAMLMap.prototype.has.bind(this); + this.set = YAMLMap$5.YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map2 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map2); + for (const pair of this.items) { + let key, value; + if (identity$c.isPair(pair)) { + key = toJS$1.toJS(pair.key, "", ctx); + value = toJS$1.toJS(pair.value, key, ctx); + } else { + key = toJS$1.toJS(pair, "", ctx); + } + if (map2.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map2.set(key, value); + } + return map2; + } + static from(schema2, iterable, ctx) { + const pairs$12 = pairs$2.createPairs(schema2, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs$12.items; + return omap2; + } +} +YAMLOMap.tag = "tag:yaml.org,2002:omap"; +const omap$2 = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError2) { + const pairs$12 = pairs$2.resolvePairs(seq2, onError2); + const seenKeys = []; + for (const { key } of pairs$12.items) { + if (identity$c.isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError2(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs$12); + }, + createNode: (schema2, iterable, ctx) => YAMLOMap.from(schema2, iterable, ctx) +}; +omap$3.YAMLOMap = YAMLOMap; +omap$3.omap = omap$2; +var schema$4 = {}; +var bool$2 = {}; +var Scalar$6 = Scalar$k; +function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; +} +const trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar$6.Scalar(true), + stringify: boolStringify +}; +const falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar$6.Scalar(false), + stringify: boolStringify +}; +bool$2.falseTag = falseTag; +bool$2.trueTag = trueTag; +var float$3 = {}; +var Scalar$5 = Scalar$k; +var stringifyNumber$2 = stringifyNumber$6; +const floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber$2.stringifyNumber +}; +const floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber$2.stringifyNumber(node); + } +}; +const float$2 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar$5.Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber$2.stringifyNumber +}; +float$3.float = float$2; +float$3.floatExp = floatExp; +float$3.floatNaN = floatNaN; +var int$3 = {}; +var stringifyNumber$1 = stringifyNumber$6; +const intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); +function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") + offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n2 = BigInt(str); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str, radix); + return sign === "-" ? -1 * n : n; +} +function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber$1.stringifyNumber(node); +} +const intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node) => intStringify(node, 2, "0b") +}; +const intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node) => intStringify(node, 8, "0") +}; +const int$2 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber$1.stringifyNumber +}; +const intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") +}; +int$3.int = int$2; +int$3.intBin = intBin; +int$3.intHex = intHex; +int$3.intOct = intOct; +var set$3 = {}; +var identity$b = identity$x; +var Pair$4 = Pair$8; +var YAMLMap$4 = YAMLMap$8; +class YAMLSet extends YAMLMap$4.YAMLMap { + constructor(schema2) { + super(schema2); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (identity$b.isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair$4.Pair(key.key, null); + else + pair = new Pair$4.Pair(key, null); + const prev = YAMLMap$4.findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = YAMLMap$4.findPair(this.items, key); + return !keepPair && identity$b.isPair(pair) ? identity$b.isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = YAMLMap$4.findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair$4.Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema2, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema2); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set2.items.push(Pair$4.createPair(value, null, ctx)); + } + return set2; + } +} +YAMLSet.tag = "tag:yaml.org,2002:set"; +const set$2 = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema2, iterable, ctx) => YAMLSet.from(schema2, iterable, ctx), + resolve(map2, onError2) { + if (identity$b.isMap(map2)) { + if (map2.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map2); + else + onError2("Set items must all have null values"); + } else + onError2("Expected a mapping for this tag"); + return map2; + } +}; +set$3.YAMLSet = YAMLSet; +set$3.set = set$2; +var timestamp$3 = {}; +var stringifyNumber = stringifyNumber$6; +function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); + return sign === "-" ? num(-1) * res : res; +} +function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === "bigint") + num = (n) => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber.stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) { + parts.unshift(0); + } else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); +} +const intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal +}; +const floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal +}; +const timestamp$2 = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str) { + const match = str.match(timestamp$2.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 6e4 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" +}; +timestamp$3.floatTime = floatTime; +timestamp$3.intTime = intTime; +timestamp$3.timestamp = timestamp$2; +var map$2 = map$6; +var _null$1 = _null$3; +var seq$2 = seq$6; +var string$2 = string$5; +var binary$1 = binary$3; +var bool$1 = bool$2; +var float$1 = float$3; +var int$1 = int$3; +var merge$1 = merge$4; +var omap$1 = omap$3; +var pairs$1 = pairs$4; +var set$1 = set$3; +var timestamp$1 = timestamp$3; +const schema$3 = [ + map$2.map, + seq$2.seq, + string$2.string, + _null$1.nullTag, + bool$1.trueTag, + bool$1.falseTag, + int$1.intBin, + int$1.intOct, + int$1.int, + int$1.intHex, + float$1.floatNaN, + float$1.floatExp, + float$1.float, + binary$1.binary, + merge$1.merge, + omap$1.omap, + pairs$1.pairs, + set$1.set, + timestamp$1.intTime, + timestamp$1.floatTime, + timestamp$1.timestamp +]; +schema$4.schema = schema$3; +var map$1 = map$6; +var _null = _null$3; +var seq$1 = seq$6; +var string$1 = string$5; +var bool = bool$4; +var float = float$6; +var int = int$6; +var schema = schema$8; +var schema$1 = schema$6; +var binary = binary$3; +var merge = merge$4; +var omap = omap$3; +var pairs = pairs$4; +var schema$2 = schema$4; +var set = set$3; +var timestamp = timestamp$3; +const schemas = /* @__PURE__ */ new Map([ + ["core", schema.schema], + ["failsafe", [map$1.map, seq$1.seq, string$1.string]], + ["json", schema$1.schema], + ["yaml11", schema$2.schema], + ["yaml-1.1", schema$2.schema] +]); +const tagsByName = { + binary: binary.binary, + bool: bool.boolTag, + float: float.float, + floatExp: float.floatExp, + floatNaN: float.floatNaN, + floatTime: timestamp.floatTime, + int: int.int, + intHex: int.intHex, + intOct: int.intOct, + intTime: timestamp.intTime, + map: map$1.map, + merge: merge.merge, + null: _null.nullTag, + omap: omap.omap, + pairs: pairs.pairs, + seq: seq$1.seq, + set: set.set, + timestamp: timestamp.timestamp +}; +const coreKnownTags = { + "tag:yaml.org,2002:binary": binary.binary, + "tag:yaml.org,2002:merge": merge.merge, + "tag:yaml.org,2002:omap": omap.omap, + "tag:yaml.org,2002:pairs": pairs.pairs, + "tag:yaml.org,2002:set": set.set, + "tag:yaml.org,2002:timestamp": timestamp.timestamp +}; +function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice(); + } + let tags2 = schemaTags; + if (!tags2) { + if (Array.isArray(customTags)) + tags2 = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags2 = tags2.concat(tag); + } else if (typeof customTags === "function") { + tags2 = customTags(tags2.slice()); + } + if (addMergeTag) + tags2 = tags2.concat(merge.merge); + return tags2.reduce((tags3, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags3.includes(tagObj)) + tags3.push(tagObj); + return tags3; + }, []); +} +tags$1.coreKnownTags = coreKnownTags; +tags$1.getTags = getTags; +var identity$a = identity$x; +var map = map$6; +var seq = seq$6; +var string = string$5; +var tags = tags$1; +const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; +let Schema$1 = class Schema { + constructor({ compat, customTags, merge: merge2, resolveKnownTags, schema: schema2, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null; + this.name = typeof schema2 === "string" && schema2 || "core"; + this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; + this.tags = tags.getTags(customTags, this.name, merge2); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, identity$a.MAP, { value: map.map }); + Object.defineProperty(this, identity$a.SCALAR, { value: string.string }); + Object.defineProperty(this, identity$a.SEQ, { value: seq.seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } +}; +Schema$2.Schema = Schema$1; +var stringifyDocument$2 = {}; +var identity$9 = identity$x; +var stringify$2 = stringify$7; +var stringifyComment = stringifyComment$5; +function stringifyDocument$1(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push("---"); + const ctx = stringify$2.createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(stringifyComment.indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (identity$9.isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(stringifyComment.indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body2 = stringify$2.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body2 += stringifyComment.lineComment(body2, "", commentString(contentComment)); + if ((body2[0] === "|" || body2[0] === ">") && lines[lines.length - 1] === "---") { + lines[lines.length - 1] = `--- ${body2}`; + } else + lines.push(body2); + } else { + lines.push(stringify$2.stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines.push("..."); + lines.push(stringifyComment.indentComment(cs, "")); + } else { + lines.push(`... ${cs}`); + } + } else { + lines.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") + lines.push(""); + lines.push(stringifyComment.indentComment(commentString(dc), "")); + } + } + return lines.join("\n") + "\n"; +} +stringifyDocument$2.stringifyDocument = stringifyDocument$1; +var Alias$1 = Alias$4; +var Collection2 = Collection$4; +var identity$8 = identity$x; +var Pair$3 = Pair$8; +var toJS = toJS$8; +var Schema2 = Schema$2; +var stringifyDocument = stringifyDocument$2; +var anchors = anchors$3; +var applyReviver = applyReviver$3; +var createNode = createNode$5; +var directives$1 = directives$2; +let Document$3 = class Document { + constructor(value, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, identity$8.NODE_TYPE, { value: identity$8.DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new directives$1.Directives({ version }); + this.setSchema(version, options); + this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(Document.prototype, { + [identity$8.NODE_TYPE]: { value: identity$8.DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = identity$8.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchors.anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; + } + return new Alias$1.Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode.createNode(value, tag, ctx); + if (flow && identity$8.isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair$3.Pair(k, v); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (Collection2.isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return identity$8.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (Collection2.isEmptyPath(path)) + return !keepScalar && identity$8.isScalar(this.contents) ? this.contents.value : this.contents; + return identity$8.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return identity$8.isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (Collection2.isEmptyPath(path)) + return this.contents !== void 0; + return identity$8.isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) { + this.contents = Collection2.collectionFromPath(this.schema, [key], value); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (Collection2.isEmptyPath(path)) { + this.contents = value; + } else if (this.contents == null) { + this.contents = Collection2.collectionFromPath(this.schema, Array.from(path), value); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new directives$1.Directives({ version: "1.1" }); + opt = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new directives$1.Directives({ version }); + opt = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema2.Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument.stringifyDocument(this, options); + } +}; +function assertCollection(contents) { + if (identity$8.isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); +} +Document$4.Document = Document$3; +var errors$4 = {}; +class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } +} +class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } +} +class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } +} +const prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "…\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer} +`; + } +}; +errors$4.YAMLError = YAMLError; +errors$4.YAMLParseError = YAMLParseError; +errors$4.YAMLWarning = YAMLWarning; +errors$4.prettifyError = prettifyError; +var composeDoc$2 = {}; +var composeNode$2 = {}; +var composeCollection$2 = {}; +var resolveBlockMap$2 = {}; +var resolveProps$5 = {}; +function resolveProps$4(tokens, { flow, indicator, next, offset, onError: onError2, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError2(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError2(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError2(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError2(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError2(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError2(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + default: + onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError2(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; +} +resolveProps$5.resolveProps = resolveProps$4; +var utilContainsNewline$3 = {}; +function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } +} +utilContainsNewline$3.containsNewline = containsNewline; +var utilFlowIndentCheck$2 = {}; +var utilContainsNewline$2 = utilContainsNewline$3; +function flowIndentCheck(indent, fc, onError2) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline$2.containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError2(end, "BAD_INDENT", msg, true); + } + } +} +utilFlowIndentCheck$2.flowIndentCheck = flowIndentCheck; +var utilMapIncludes$2 = {}; +var identity$7 = identity$x; +function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity$7.isScalar(a) && identity$7.isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); +} +utilMapIncludes$2.mapIncludes = mapIncludes; +var Pair$2 = Pair$8; +var YAMLMap$3 = YAMLMap$8; +var resolveProps$3 = resolveProps$5; +var utilContainsNewline$1 = utilContainsNewline$3; +var utilFlowIndentCheck$1 = utilFlowIndentCheck$2; +var utilMapIncludes$1 = utilMapIncludes$2; +const startColMsg = "All mapping items must start at the same column"; +function resolveBlockMap$1({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError2, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap$3.YAMLMap; + const map2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + const keyProps = resolveProps$3.resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError: onError2, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError2(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map2.comment) + map2.comment += "\n" + keyProps.comment; + else + map2.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || utilContainsNewline$1.containsNewline(key)) { + onError2(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError2(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError2) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError2); + if (ctx.schema.compat) + utilFlowIndentCheck$1.flowIndentCheck(bm.indent, key, onError2); + ctx.atKey = false; + if (utilMapIncludes$1.mapIncludes(ctx, map2.items, keyNode)) + onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps$3.resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError: onError2, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === "block-map" && !valueProps.hasNewline) + onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError2(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError2) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError2); + if (ctx.schema.compat) + utilFlowIndentCheck$1.flowIndentCheck(bm.indent, value, onError2); + offset = valueNode.range[2]; + const pair = new Pair$2.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } else { + if (implicitKey) + onError2(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair$2.Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError2(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map2.range = [bm.offset, offset, commentEnd ?? offset]; + return map2; +} +resolveBlockMap$2.resolveBlockMap = resolveBlockMap$1; +var resolveBlockSeq$2 = {}; +var YAMLSeq$2 = YAMLSeq$7; +var resolveProps$2 = resolveProps$5; +var utilFlowIndentCheck = utilFlowIndentCheck$2; +function resolveBlockSeq$1({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError2, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq$2.YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps$2.resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError: onError2, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value?.type === "block-seq") + onError2(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError2(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value ? composeNode2(ctx, value, props, onError2) : composeEmptyNode2(ctx, props.end, start, null, props, onError2); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError2); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; +} +resolveBlockSeq$2.resolveBlockSeq = resolveBlockSeq$1; +var resolveFlowCollection$2 = {}; +var resolveEnd$6 = {}; +function resolveEnd$5(end, offset, reqSpace, onError2) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; +} +resolveEnd$6.resolveEnd = resolveEnd$5; +var identity$6 = identity$x; +var Pair$1 = Pair$8; +var YAMLMap$2 = YAMLMap$8; +var YAMLSeq$1 = YAMLSeq$7; +var resolveEnd$4 = resolveEnd$6; +var resolveProps$1 = resolveProps$5; +var utilContainsNewline = utilContainsNewline$3; +var utilMapIncludes = utilMapIncludes$2; +const blockMsg = "Block collections are not allowed within flow collections"; +const isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); +function resolveFlowCollection$1({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError2, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap$2.YAMLMap : YAMLSeq$1.YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0; i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps$1.resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError: onError2, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError2(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && utilContainsNewline.containsNewline(key)) + onError2( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i === 0) { + if (props.comma) + onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError2(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (identity$6.isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value ? composeNode2(ctx, value, props, onError2) : composeEmptyNode2(ctx, props.end, sep, null, props, onError2); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError2) : composeEmptyNode2(ctx, keyStart, start, null, props, onError2); + if (isBlock(key)) + onError2(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps$1.resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError: onError2, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError2(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError2(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) { + if ("source" in value && value.source?.[0] === ":") + onError2(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError2(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError2) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError2) : null; + if (valueNode) { + if (isBlock(value)) + onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair$1.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map2 = coll; + if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode)) + onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map2.items.push(pair); + } else { + const map2 = new YAMLMap$2.YAMLMap(ctx.schema); + map2.flow = true; + map2.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map2.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map2); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError2(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd$4.resolveEnd(ee, cePos, ctx.options.strict, onError2); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; +} +resolveFlowCollection$2.resolveFlowCollection = resolveFlowCollection$1; +var identity$5 = identity$x; +var Scalar$4 = Scalar$k; +var YAMLMap$1 = YAMLMap$8; +var YAMLSeq2 = YAMLSeq$7; +var resolveBlockMap = resolveBlockMap$2; +var resolveBlockSeq = resolveBlockSeq$2; +var resolveFlowCollection = resolveFlowCollection$2; +function resolveCollection(CN2, ctx, token, onError2, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN2, ctx, token, onError2, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN2, ctx, token, onError2, tag) : resolveFlowCollection.resolveFlowCollection(CN2, ctx, token, onError2, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; +} +function composeCollection$1(CN2, ctx, token, props, onError2) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError2(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap$1.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq2.YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError2, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError2(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError2, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError2, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = identity$5.isNode(res) ? res : new Scalar$4.Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; +} +composeCollection$2.composeCollection = composeCollection$1; +var composeScalar$2 = {}; +var resolveBlockScalar$3 = {}; +var Scalar$3 = Scalar$k; +function resolveBlockScalar$2(ctx, scalar, onError2) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError2); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar$3.Scalar.BLOCK_FOLDED : Scalar$3.Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1; i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0; i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError2(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError2(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines.length - 1; i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0; i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + "\n"; + for (let i = contentStart; i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError2(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar$3.Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value += "\n"; + else + sep = "\n"; + } else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart; i < lines.length; ++i) + value += "\n" + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== "\n") + value += "\n"; + break; + default: + value += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; +} +function parseBlockScalarHeader({ offset, props }, strict, onError2) { + if (props[0].type !== "block-scalar-header") { + onError2(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1; i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError2(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1; i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError2(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError2(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError2(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; +} +function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines = [line0]; + for (let i = 1; i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; +} +resolveBlockScalar$3.resolveBlockScalar = resolveBlockScalar$2; +var resolveFlowScalar$3 = {}; +var Scalar$2 = Scalar$k; +var resolveEnd$3 = resolveEnd$6; +function resolveFlowScalar$2(scalar, strict, onError2) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError2(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar$2.Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar$2.Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar$2.Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + default: + onError2(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd$3.resolveEnd(end, valueEnd, strict, onError2); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; +} +function plainValue(source, onError2) { + let badChar = ""; + switch (source[0]) { + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError2(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return unfoldLines(source); +} +function singleQuotedValue(source, onError2) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError2(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); +} +function unfoldLines(source) { + const line = /(.*?)\r?\n/sy; + let match = line.exec(source); + if (!match) + return source; + let trimEnd, trimBoth; + try { + trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError2(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; +} +function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; +} +const escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "…", + // Unicode next line + _: " ", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " +}; +function parseCharCode(source, offset, length, onError2) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError2(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } +} +resolveFlowScalar$3.resolveFlowScalar = resolveFlowScalar$2; +var identity$4 = identity$x; +var Scalar$1 = Scalar$k; +var resolveBlockScalar$1 = resolveBlockScalar$3; +var resolveFlowScalar$1 = resolveFlowScalar$3; +function composeScalar$1(ctx, token, tagToken, onError2) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar$1.resolveBlockScalar(ctx, token, onError2) : resolveFlowScalar$1.resolveFlowScalar(token, ctx.options.strict, onError2); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[identity$4.SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError2); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value, token, onError2); + else + tag = ctx.schema[identity$4.SCALAR]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = identity$4.isScalar(res) ? res : new Scalar$1.Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar$1.Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; +} +function findScalarTagByName(schema2, value, tagName, tagToken, onError2) { + if (tagName === "!") + return schema2[identity$4.SCALAR]; + const matchWithTest = []; + for (const tag of schema2.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema2.knownTags[tagName]; + if (kt && !kt.collection) { + schema2.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema2[identity$4.SCALAR]; +} +function findScalarTagByTest({ atKey, directives: directives2, schema: schema2 }, value, token, onError2) { + const tag = schema2.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema2[identity$4.SCALAR]; + if (schema2.compat) { + const compat = schema2.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema2[identity$4.SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives2.tagString(tag.tag); + const cs = directives2.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError2(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; +} +composeScalar$2.composeScalar = composeScalar$1; +var utilEmptyScalarPosition$1 = {}; +function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1; i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; +} +utilEmptyScalarPosition$1.emptyScalarPosition = emptyScalarPosition; +var Alias2 = Alias$4; +var identity$3 = identity$x; +var composeCollection = composeCollection$2; +var composeScalar = composeScalar$2; +var resolveEnd$2 = resolveEnd$6; +var utilEmptyScalarPosition = utilEmptyScalarPosition$1; +const CN = { composeNode: composeNode$1, composeEmptyNode }; +function composeNode$1(ctx, token, props, onError2) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError2); + if (anchor || tag) + onError2(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar.composeScalar(ctx, token, tag, onError2); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection.composeCollection(CN, ctx, token, props, onError2); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError2(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError2(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError2)); + if (anchor && node.anchor === "") + onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!identity$3.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError2(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; +} +function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError2) { + const token = { + type: "scalar", + offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar.composeScalar(ctx, token, tag, onError2); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; +} +function composeAlias({ options }, { offset, source, end }, onError2) { + const alias = new Alias2.Alias(source.substring(1)); + if (alias.source === "") + onError2(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError2(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd$2.resolveEnd(end, valueEnd, options.strict, onError2); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; +} +composeNode$2.composeEmptyNode = composeEmptyNode; +composeNode$2.composeNode = composeNode$1; +var Document$2 = Document$4; +var composeNode = composeNode$2; +var resolveEnd$1 = resolveEnd$6; +var resolveProps = resolveProps$5; +function composeDoc$1(options, directives2, { offset, start, value, end }, onError2) { + const opts = Object.assign({ _directives: directives2 }, options); + const doc = new Document$2.Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps.resolveProps(start, { + indicator: "doc-start", + next: value ?? end?.[0], + offset, + onError: onError2, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) + onError2(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode.composeNode(ctx, value, props, onError2) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError2); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd$1.resolveEnd(end, contentEnd, false, onError2); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; +} +composeDoc$2.composeDoc = composeDoc$1; +var node_process$1 = require$$0$a; +var directives = directives$2; +var Document$1 = Document$4; +var errors$3 = errors$4; +var identity$2 = identity$x; +var composeDoc = composeDoc$2; +var resolveEnd = resolveEnd$6; +function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; +} +function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0; i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; +} +class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new errors$3.YAMLWarning(pos, code, message)); + else + this.errors.push(new errors$3.YAMLParseError(pos, code, message)); + }; + this.directives = new directives.Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (identity$2.isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (identity$2.isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0; i < this.errors.length; ++i) + doc.errors.push(this.errors[i]); + for (let i = 0; i < this.warnings.length; ++i) + doc.warnings.push(this.warnings[i]); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + if (node_process$1.env.LOG_STREAM) + console.dir(token, { depth: null }); + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new errors$3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new errors$3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new errors$3.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document$1.Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } +} +composer$1.Composer = Composer; +var cst$2 = {}; +var cstScalar$1 = {}; +var resolveBlockScalar = resolveBlockScalar$3; +var resolveFlowScalar = resolveFlowScalar$3; +var errors$2 = errors$4; +var stringifyString = stringifyString$5; +function resolveAsScalar(token, strict = true, onError2) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError2) + onError2(offset, code, message); + else + throw new errors$2.YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; +} +function createScalarToken(value, context2) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context2; + const source = stringifyString.stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context2.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body2 = source.substring(he + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body2 }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } +} +function setScalarValue(token, value, context2 = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context2; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString.stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } +} +function setBlockScalarValue(token, source) { + const he = source.indexOf("\n"); + const head = source.substring(0, he); + const body2 = source.substring(he + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body2; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body2 }); + } +} +function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; +} +function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } +} +cstScalar$1.createScalarToken = createScalarToken; +cstScalar$1.resolveAsScalar = resolveAsScalar; +cstScalar$1.setScalarValue = setScalarValue; +var cstStringify$1 = {}; +const stringify$1 = (cst2) => "type" in cst2 ? stringifyToken(cst2) : stringifyItem(cst2); +function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } +} +function stringifyItem({ start, key, sep, value }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; +} +cstStringify$1.stringify = stringify$1; +var cstVisit$1 = {}; +const BREAK = Symbol("break visit"); +const SKIP = Symbol("skip children"); +const REMOVE = Symbol("remove item"); +function visit$1(cst2, visitor) { + if ("type" in cst2 && cst2.type === "document") + cst2 = { start: cst2.start, value: cst2.value }; + _visit(Object.freeze([]), cst2, visitor); +} +visit$1.BREAK = BREAK; +visit$1.SKIP = SKIP; +visit$1.REMOVE = REMOVE; +visit$1.itemAtPath = (cst2, path) => { + let item = cst2; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return void 0; + } + return item; +}; +visit$1.parentCollection = (cst2, path) => { + const parent = visit$1.itemAtPath(cst2, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); +}; +function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0; i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; +} +cstVisit$1.visit = visit$1; +var cstScalar = cstScalar$1; +var cstStringify = cstStringify$1; +var cstVisit = cstVisit$1; +const BOM = "\uFEFF"; +const DOCUMENT = ""; +const FLOW_END = ""; +const SCALAR = ""; +const isCollection = (token) => !!token && "items" in token; +const isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); +function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR: + return ""; + default: + return JSON.stringify(token); + } +} +function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; +} +cst$2.createScalarToken = cstScalar.createScalarToken; +cst$2.resolveAsScalar = cstScalar.resolveAsScalar; +cst$2.setScalarValue = cstScalar.setScalarValue; +cst$2.stringify = cstStringify.stringify; +cst$2.visit = cstVisit.visit; +cst$2.BOM = BOM; +cst$2.DOCUMENT = DOCUMENT; +cst$2.FLOW_END = FLOW_END; +cst$2.SCALAR = SCALAR; +cst$2.isCollection = isCollection; +cst$2.isScalar = isScalar; +cst$2.prettyToken = prettyToken; +cst$2.tokenType = tokenType; +var lexer$1 = {}; +var cst$1 = cst$2; +function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } +} +const hexDigits = new Set("0123456789ABCDEFabcdef"); +const tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); +const flowIndicatorChars = new Set(",[]{}"); +const invalidAnchorChars = new Set(" ,[]{}\n\r "); +const isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +class Lexer { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === " ") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i + 1] === "\n"; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === cst$1.BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield cst$1.DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return "block-start"; + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield cst$1.FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield cst$1.SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === "\n") { + i += 1; + ch = "\n"; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield cst$1.SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + let n = 0; + loop: while (true) { + switch (this.charAt(0)) { + case "!": + n += yield* this.pushTag(); + n += yield* this.pushSpaces(true); + continue loop; + case "&": + n += yield* this.pushUntil(isNotAnchorChar); + n += yield* this.pushSpaces(true); + continue loop; + case "-": + case "?": + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === " "); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } +} +lexer$1.Lexer = Lexer; +var lineCounter$1 = {}; +class LineCounter { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } +} +lineCounter$1.LineCounter = LineCounter; +var parser$1 = {}; +var node_process = require$$0$a; +var cst = cst$2; +var lexer = lexer$1; +function includesToken(list, type) { + for (let i = 0; i < list.length; ++i) + if (list[i].type === type) + return true; + return false; +} +function findNonEmptyIndex(list) { + for (let i = 0; i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; +} +function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } +} +function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + default: + return []; + } +} +function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") { + } + return prev.splice(i, prev.length); +} +function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0; i < source.length; ++i) + target.push(source[i]); +} +function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } + } +} +class Parser2 { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new lexer.Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (node_process.env.LOG_TOKENS) + console.log("|", cst.prettyToken(source)); + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = cst.tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map2 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map2) { + const it = map2.items[map2.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map2.indent)) { + const prev = map2.items[map2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map2.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map2.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0; i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map2.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map2.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map2.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (atNextItem || it.value) { + map2.items.push({ start, key: fs2, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs2); + } else { + Object.assign(it, { key: fs2, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map2); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map2.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs2 = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs2, sep: [] }); + else if (it.sep) + this.stack.push(fs2); + else + Object.assign(it, { key: fs2, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map2 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } +} +parser$1.Parser = Parser2; +var publicApi$1 = {}; +var composer = composer$1; +var Document2 = Document$4; +var errors$1 = errors$4; +var log = log$2; +var identity$1 = identity$x; +var lineCounter = lineCounter$1; +var parser = parser$1; +function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter$12 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null; + return { lineCounter: lineCounter$12, prettyErrors }; +} +function parseAllDocuments(source, options = {}) { + const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); + const parser$12 = new parser.Parser(lineCounter2?.addNewLine); + const composer$12 = new composer.Composer(options); + const docs = Array.from(composer$12.compose(parser$12.parse(source))); + if (prettyErrors && lineCounter2) + for (const doc of docs) { + doc.errors.forEach(errors$1.prettifyError(source, lineCounter2)); + doc.warnings.forEach(errors$1.prettifyError(source, lineCounter2)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer$12.streamInfo()); +} +function parseDocument(source, options = {}) { + const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); + const parser$12 = new parser.Parser(lineCounter2?.addNewLine); + const composer$12 = new composer.Composer(options); + let doc = null; + for (const _doc of composer$12.compose(parser$12.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new errors$1.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter2) { + doc.errors.forEach(errors$1.prettifyError(source, lineCounter2)); + doc.warnings.forEach(errors$1.prettifyError(source, lineCounter2)); + } + return doc; +} +function parse$1(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); +} +function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (identity$1.isDocument(value) && !_replacer) + return value.toString(options); + return new Document2.Document(value, _replacer, options).toString(options); +} +publicApi$1.parse = parse$1; +publicApi$1.parseAllDocuments = parseAllDocuments; +publicApi$1.parseDocument = parseDocument; +publicApi$1.stringify = stringify; +var errors = errors$4; +var identity = identity$x; +var Pair2 = Pair$8; +var Scalar2 = Scalar$k; +var YAMLMap2 = YAMLMap$8; +var publicApi = publicApi$1; +var visit = visit$6; +errors.YAMLError; +errors.YAMLParseError; +errors.YAMLWarning; +identity.isAlias; +identity.isCollection; +identity.isDocument; +identity.isMap; +identity.isNode; +identity.isPair; +identity.isScalar; +identity.isSeq; +Pair2.Pair; +Scalar2.Scalar; +YAMLMap2.YAMLMap; +var parse = publicApi.parse; +visit.visit; +visit.visitAsync; +const DRIVERS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "drivers"); +const BUILT_IN_DRIVERS = { + railsschema: { + description: "db/schema.rb version merge", + files: ["db/schema.rb"] + } +}; +const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/; +function parseMergeDrivers(input) { + if (!input?.trim()) return []; + let entries = parse(input); + if (entries == null) return []; + if (!Array.isArray(entries)) entries = [entries]; + const drivers = entries.map(normalizeEntry); + const names = drivers.map((driver) => driver.name); + const duplicate = names.find((name, index) => names.indexOf(name) !== index); + if (duplicate) { + throw new Error(`Merge driver "${duplicate}" is listed more than once.`); + } + return drivers; +} +function normalizeEntry(entry) { + if (typeof entry === "string") entry = { name: entry }; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) { + throw new Error(`Each merge driver must be a name or a mapping, got: ${JSON.stringify(entry)}`); + } + const { name, files, script, ...rest } = entry; + const unknownKeys = Object.keys(rest); + if (unknownKeys.length) { + throw new Error(`Merge driver "${name}" has unknown keys: ${unknownKeys.join(", ")}`); + } + if (typeof name !== "string" || !NAME_PATTERN.test(name)) { + throw new Error(`Merge driver name must be letters, numbers, "-" or "_", got: ${JSON.stringify(name)}`); + } + const builtIn = BUILT_IN_DRIVERS[name]; + if (script == null && !builtIn) { + const known = Object.keys(BUILT_IN_DRIVERS).join(", "); + throw new Error(`Unknown built-in merge driver "${name}" (built-in drivers: ${known}). Give a script to add a custom driver.`); + } + if (script != null && builtIn) { + throw new Error(`Merge driver "${name}" is built in; give a custom driver a different name.`); + } + if (script != null && (typeof script !== "string" || !script.trim())) { + throw new Error(`Merge driver "${name}" needs a script.`); + } + const patterns = normalizeFiles(name, files ?? builtIn?.files); + return builtIn ? { name, files: patterns, description: builtIn.description, path: join(DRIVERS_DIR, name) } : { name, files: patterns, description: `${name} merge driver`, script }; +} +function normalizeFiles(name, files) { + const patterns = typeof files === "string" ? [files] : files; + if (!Array.isArray(patterns) || patterns.length === 0) { + throw new Error(`Merge driver "${name}" needs files: a pattern or a list of patterns.`); + } + for (const pattern of patterns) { + if (typeof pattern !== "string" || !pattern.trim() || /\s/.test(pattern)) { + throw new Error(`Merge driver "${name}" has an invalid file pattern: ${JSON.stringify(pattern)}`); + } + } + return patterns; +} +async function writeDriverScripts(drivers, scriptDir) { + const custom = drivers.filter((driver) => driver.script); + if (custom.length) await mkdir(scriptDir, { recursive: true }); + return Promise.all( + drivers.map(async (driver) => { + if (!driver.script) return driver; + const path = join(scriptDir, driver.name); + const script = driver.script.startsWith("#!") ? driver.script : `#!/usr/bin/env bash +${driver.script}`; + await writeFile(path, script.endsWith("\n") ? script : `${script} +`); + await chmod(path, 493); + return { ...driver, path }; + }) + ); +} +function driverCommand(path) { + return `'${path.replaceAll("'", "'\\''")}' %O %A %B %L %P`; +} +function attributeLines(drivers) { + return drivers.flatMap((driver) => driver.files.map((pattern) => `${pattern} merge=${driver.name}`)); +} +class StagingAutoMerge { + constructor(octokit, primaryBranch, repo, logger = console, { mergeDrivers = [], scriptDir } = {}) { + if (!primaryBranch) { + throw new Error("Primary branch is required."); + } + if (!repo?.owner || !repo?.repo) { + throw new Error("Repository owner and name are required."); + } + this.octokit = octokit; + this.logger = logger; + this.primaryBranch = primaryBranch; + this.repo = repo; + this.mergeDrivers = mergeDrivers; + this.scriptDir = scriptDir ?? join(process.env.RUNNER_TEMP || tmpdir(), "staging-auto-merge-drivers"); + } + async run() { + await this.validateStagingLabel(); + await this.configureGitUser(); + await this.configureMergeDrivers(); + await this.resetToPrimaryBranch(); + await this.mergeStagedPullRequests(); + await this.pushChanges(); + await this.cleanupClosedPullRequests(); + } + async configureGitUser() { + await this.exec('git config --global user.email "github-actions@github.com"'); + await this.exec('git config --global user.name "github-actions"'); + } + // Registers the merge drivers in this checkout only: .git/info/attributes + // and local git config, so nothing is committed to staging. + async configureMergeDrivers() { + if (!this.mergeDrivers.length) return; + const drivers = await writeDriverScripts(this.mergeDrivers, this.scriptDir); + for (const driver of drivers) { + await this.exec("git", ["config", `merge.${driver.name}.name`, driver.description]); + await this.exec("git", ["config", `merge.${driver.name}.driver`, driverCommand(driver.path)]); + } + const attributesPath = (await this.execOutput("git", ["rev-parse", "--path-format=absolute", "--git-path", "info/attributes"])).trim(); + await mkdir(dirname(attributesPath), { recursive: true }); + await appendFile(attributesPath, `${attributeLines(drivers).join("\n")} +`); + this.logger.info("Merge drivers: ", drivers.map((driver) => driver.name).join(", ")); + } + async resetToPrimaryBranch() { + await this.exec("git", ["reset", "--hard", `origin/${this.primaryBranch}`]); + } + async validateStagingLabel() { + this.stagingLabelName = await this.findStagingLabelName(); + if (!this.stagingLabelName) { + throw new Error('Required label "Staging" was not found in this repository.'); + } + this.logger.info("Label Name: ", this.stagingLabelName); + } + async mergeStagedPullRequests() { + const pullRequests = await this.octokit.paginate(this.octokit.rest.pulls.list, { + ...this.repo, + state: "open", + sort: "created", + direction: "asc", + per_page: 100 + }); + for (const pr of pullRequests) { + if (this.hasStagingLabel(pr.labels)) { + await this.mergePullRequest(pr); + } + } + } + async mergePullRequest(pr) { + const { title, number, head: { ref: branch } } = pr; + let execOutput = ""; + let execError = ""; + const options = { + listeners: { + stdout: (data) => { + execOutput += data.toString(); + }, + stderr: (data) => { + execError += data.toString(); + } + } + }; + try { + await this.exec("git", ["merge", `origin/${branch}`, "--squash", "--verbose"], options); + await this.exec("git", ["commit", "-m", title]); + } catch (error) { + await this.abortMerge(); + await this.createMergeConflictComment(number, execOutput, execError); + await this.removeStagingLabel(number); + } + } + async abortMerge() { + await this.exec("git restore --staged ."); + await this.exec("git restore ."); + await this.exec("git clean -df"); + } + async pushChanges() { + await this.exec("git push --force"); + } + async cleanupClosedPullRequests() { + const closedPullRequests = await this.octokit.paginate(this.octokit.rest.issues.listForRepo, { + ...this.repo, + state: "closed", + labels: this.stagingLabelName, + per_page: 100 + }); + for (const closedPr of closedPullRequests) { + if (closedPr.pull_request) { + this.logger.info("removing label from: ", closedPr.title); + await this.removeStagingLabel(closedPr.number); + } + } + } + async exec(command2, args, options) { + return execExports.exec(command2, args, options); + } + async execOutput(command2, args) { + let output = ""; + await this.exec(command2, args, { + listeners: { + stdout: (data) => { + output += data.toString(); + } + } + }); + return output; + } + extractFilenamesFromConflicts(logText) { + const regex = /CONFLICT \(content\): Merge conflict in\s+([^\n]+)/g; + const matches = []; + let match; + while ((match = regex.exec(logText)) !== null) { + matches.push(match[1]); + } + return matches; + } + formatCommentBody(mergeConflictMessage, consoleErrorMessage) { + const formattedConflictFiles = this.extractFilenamesFromConflicts(mergeConflictMessage).join("\n"); + let conflictMessage = `Merge Conflicts in these files: +${formattedConflictFiles}`; + if (consoleErrorMessage) { + conflictMessage += ` + +Merge Command Error: ${consoleErrorMessage}`; + } + return conflictMessage; + } + hasStagingLabel(labels) { + return labels.some((label) => label.name.toLowerCase() === this.stagingLabelName.toLowerCase()); + } + async findStagingLabelName() { + const repoLabels = await this.octokit.paginate(this.octokit.rest.issues.listLabelsForRepo, { + owner: this.repo.owner, + repo: this.repo.repo, + per_page: 100 + }); + return repoLabels.find((label) => label.name.toLowerCase() === "staging")?.name; + } + async removeStagingLabel(issueNumber) { + if (!this.stagingLabelName) return; + try { + await this.octokit.rest.issues.removeLabel({ + owner: this.repo.owner, + repo: this.repo.repo, + issue_number: issueNumber, + name: this.stagingLabelName + }); + } catch (error) { + const status = error?.status; + if (status !== 404) { + throw error; + } + } + } + async createMergeConflictComment(issueNumber, execOutput, execError) { + await this.octokit.rest.issues.createComment({ + owner: this.repo.owner, + repo: this.repo.repo, issue_number: issueNumber, body: this.formatCommentBody(execOutput, execError) }); } } -const token = coreExports.getInput("github-token", { required: true }); -const primaryBranch = coreExports.getInput("primary-branch", { required: true }); -const octokit = getOctokit_1(token); -const stagingAutoMerge = new StagingAutoMerge(octokit, primaryBranch, context.repo, console); -stagingAutoMerge.run().catch(coreExports.setFailed); +try { + const token = coreExports.getInput("github-token", { required: true }); + const primaryBranch = coreExports.getInput("primary-branch", { required: true }); + const mergeDrivers = parseMergeDrivers(coreExports.getInput("merge-drivers")); + const octokit = getOctokit_1(token); + const stagingAutoMerge = new StagingAutoMerge(octokit, primaryBranch, context.repo, console, { mergeDrivers }); + await stagingAutoMerge.run(); +} catch (error) { + coreExports.setFailed(error); +} diff --git a/staging-auto-merge/drivers/railsschema b/staging-auto-merge/drivers/railsschema new file mode 100755 index 0000000..0c95f56 --- /dev/null +++ b/staging-auto-merge/drivers/railsschema @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Git merge driver for db/schema.rb. +# +# Two branches that each add a migration both change the `define(version: …)` +# line. This sets that line to the newest version, then merges the rest as git +# normally would, so real conflicts still stop the merge with conflict markers. +# +# Git calls it as: railsschema %O %A %B %L %P +# (base, ours — which receives the result, theirs, marker size, path) +set -euo pipefail + +base="$1" ours="$2" theirs="$3" marker_size="${4:-7}" path="${5:-db/schema.rb}" + +latest=$(grep -ohE 'define\(version: [0-9_]+\)' "$base" "$ours" "$theirs" | grep -oE '[0-9_]+' | sort | tail -1 || true) + +if [ -n "$latest" ]; then + for file in "$base" "$ours" "$theirs"; do + perl -pi -e "s/define\(version: [0-9_]+\)/define(version: $latest)/" "$file" + done +fi + +git merge-file --marker-size="$marker_size" -L "$path (ours)" -L "$path (base)" -L "$path (theirs)" "$ours" "$base" "$theirs" diff --git a/staging-auto-merge/package-lock.json b/staging-auto-merge/package-lock.json index 7d2b912..0928c08 100644 --- a/staging-auto-merge/package-lock.json +++ b/staging-auto-merge/package-lock.json @@ -10,7 +10,8 @@ "dependencies": { "@actions/core": "^1.11.1", "@actions/exec": "^1.1.1", - "@actions/github": "^6.0.0" + "@actions/github": "^6.0.0", + "yaml": "^2.9.1" }, "devDependencies": { "vite": "^5.0.0", @@ -2093,6 +2094,21 @@ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } } } } diff --git a/staging-auto-merge/package.json b/staging-auto-merge/package.json index f3ec1ae..7277598 100644 --- a/staging-auto-merge/package.json +++ b/staging-auto-merge/package.json @@ -11,7 +11,8 @@ "dependencies": { "@actions/core": "^1.11.1", "@actions/exec": "^1.1.1", - "@actions/github": "^6.0.0" + "@actions/github": "^6.0.0", + "yaml": "^2.9.1" }, "devDependencies": { "vite": "^5.0.0", diff --git a/staging-auto-merge/src/index.js b/staging-auto-merge/src/index.js index 475fe75..da2e45d 100644 --- a/staging-auto-merge/src/index.js +++ b/staging-auto-merge/src/index.js @@ -1,10 +1,16 @@ import { getInput, setFailed } from '@actions/core' import { getOctokit, context } from '@actions/github' import StagingAutoMerge from './staging-auto-merge.js' +import { parseMergeDrivers } from './merge-drivers.js' -const token = getInput('github-token', { required: true }) -const primaryBranch = getInput('primary-branch', { required: true }) -const octokit = getOctokit(token) -const stagingAutoMerge = new StagingAutoMerge(octokit, primaryBranch, context.repo, console) +try { + const token = getInput('github-token', { required: true }) + const primaryBranch = getInput('primary-branch', { required: true }) + const mergeDrivers = parseMergeDrivers(getInput('merge-drivers')) + const octokit = getOctokit(token) + const stagingAutoMerge = new StagingAutoMerge(octokit, primaryBranch, context.repo, console, { mergeDrivers }) -stagingAutoMerge.run().catch(setFailed) + await stagingAutoMerge.run() +} catch (error) { + setFailed(error) +} diff --git a/staging-auto-merge/src/merge-drivers.js b/staging-auto-merge/src/merge-drivers.js new file mode 100644 index 0000000..a30ed9c --- /dev/null +++ b/staging-auto-merge/src/merge-drivers.js @@ -0,0 +1,115 @@ +import { chmod, mkdir, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { parse } from 'yaml' + +// src/ while testing, dist/ once built: both sit next to drivers/. +const DRIVERS_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'drivers') + +export const BUILT_IN_DRIVERS = { + railsschema: { + description: 'db/schema.rb version merge', + files: ['db/schema.rb'], + }, +} + +const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]*$/ + +// Parses the merge-drivers input: a YAML list whose entries are either the +// name of a built-in driver or a mapping with name, files and (for a custom +// driver) script. A single name may be given on its own. +export function parseMergeDrivers(input) { + if (!input?.trim()) return [] + + let entries = parse(input) + if (entries == null) return [] + if (!Array.isArray(entries)) entries = [entries] + + const drivers = entries.map(normalizeEntry) + const names = drivers.map((driver) => driver.name) + const duplicate = names.find((name, index) => names.indexOf(name) !== index) + if (duplicate) { + throw new Error(`Merge driver "${duplicate}" is listed more than once.`) + } + + return drivers +} + +function normalizeEntry(entry) { + if (typeof entry === 'string') entry = { name: entry } + + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + throw new Error(`Each merge driver must be a name or a mapping, got: ${JSON.stringify(entry)}`) + } + + const { name, files, script, ...rest } = entry + const unknownKeys = Object.keys(rest) + if (unknownKeys.length) { + throw new Error(`Merge driver "${name}" has unknown keys: ${unknownKeys.join(', ')}`) + } + + if (typeof name !== 'string' || !NAME_PATTERN.test(name)) { + throw new Error(`Merge driver name must be letters, numbers, "-" or "_", got: ${JSON.stringify(name)}`) + } + + const builtIn = BUILT_IN_DRIVERS[name] + if (script == null && !builtIn) { + const known = Object.keys(BUILT_IN_DRIVERS).join(', ') + throw new Error(`Unknown built-in merge driver "${name}" (built-in drivers: ${known}). Give a script to add a custom driver.`) + } + if (script != null && builtIn) { + throw new Error(`Merge driver "${name}" is built in; give a custom driver a different name.`) + } + if (script != null && (typeof script !== 'string' || !script.trim())) { + throw new Error(`Merge driver "${name}" needs a script.`) + } + + const patterns = normalizeFiles(name, files ?? builtIn?.files) + + return builtIn + ? { name, files: patterns, description: builtIn.description, path: join(DRIVERS_DIR, name) } + : { name, files: patterns, description: `${name} merge driver`, script } +} + +function normalizeFiles(name, files) { + const patterns = typeof files === 'string' ? [files] : files + + if (!Array.isArray(patterns) || patterns.length === 0) { + throw new Error(`Merge driver "${name}" needs files: a pattern or a list of patterns.`) + } + + for (const pattern of patterns) { + if (typeof pattern !== 'string' || !pattern.trim() || /\s/.test(pattern)) { + throw new Error(`Merge driver "${name}" has an invalid file pattern: ${JSON.stringify(pattern)}`) + } + } + + return patterns +} + +// Writes each custom driver's script to scriptDir and returns the drivers +// with the path git should run. +export async function writeDriverScripts(drivers, scriptDir) { + const custom = drivers.filter((driver) => driver.script) + if (custom.length) await mkdir(scriptDir, { recursive: true }) + + return Promise.all( + drivers.map(async (driver) => { + if (!driver.script) return driver + + const path = join(scriptDir, driver.name) + const script = driver.script.startsWith('#!') ? driver.script : `#!/usr/bin/env bash\n${driver.script}` + await writeFile(path, script.endsWith('\n') ? script : `${script}\n`) + await chmod(path, 0o755) + return { ...driver, path } + }), + ) +} + +export function driverCommand(path) { + return `'${path.replaceAll("'", "'\\''")}' %O %A %B %L %P` +} + +export function attributeLines(drivers) { + return drivers.flatMap((driver) => driver.files.map((pattern) => `${pattern} merge=${driver.name}`)) +} diff --git a/staging-auto-merge/src/staging-auto-merge.js b/staging-auto-merge/src/staging-auto-merge.js index 77bdba9..82584af 100644 --- a/staging-auto-merge/src/staging-auto-merge.js +++ b/staging-auto-merge/src/staging-auto-merge.js @@ -1,7 +1,11 @@ +import { appendFile, mkdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' import { exec as actionsExec } from '@actions/exec' +import { attributeLines, driverCommand, writeDriverScripts } from './merge-drivers.js' export default class StagingAutoMerge { - constructor(octokit, primaryBranch, repo, logger = console) { + constructor(octokit, primaryBranch, repo, logger = console, { mergeDrivers = [], scriptDir } = {}) { if (!primaryBranch) { throw new Error('Primary branch is required.') } @@ -14,11 +18,14 @@ export default class StagingAutoMerge { this.logger = logger this.primaryBranch = primaryBranch this.repo = repo + this.mergeDrivers = mergeDrivers + this.scriptDir = scriptDir ?? join(process.env.RUNNER_TEMP || tmpdir(), 'staging-auto-merge-drivers') } async run() { await this.validateStagingLabel() await this.configureGitUser() + await this.configureMergeDrivers() await this.resetToPrimaryBranch() await this.mergeStagedPullRequests() await this.pushChanges() @@ -30,6 +37,25 @@ export default class StagingAutoMerge { await this.exec('git config --global user.name "github-actions"') } + // Registers the merge drivers in this checkout only: .git/info/attributes + // and local git config, so nothing is committed to staging. + async configureMergeDrivers() { + if (!this.mergeDrivers.length) return + + const drivers = await writeDriverScripts(this.mergeDrivers, this.scriptDir) + + for (const driver of drivers) { + await this.exec('git', ['config', `merge.${driver.name}.name`, driver.description]) + await this.exec('git', ['config', `merge.${driver.name}.driver`, driverCommand(driver.path)]) + } + + const attributesPath = (await this.execOutput('git', ['rev-parse', '--path-format=absolute', '--git-path', 'info/attributes'])).trim() + await mkdir(dirname(attributesPath), { recursive: true }) + await appendFile(attributesPath, `${attributeLines(drivers).join('\n')}\n`) + + this.logger.info('Merge drivers: ', drivers.map((driver) => driver.name).join(', ')) + } + async resetToPrimaryBranch() { await this.exec('git', ['reset', '--hard', `origin/${this.primaryBranch}`]) } @@ -115,6 +141,18 @@ export default class StagingAutoMerge { return actionsExec(command, args, options) } + async execOutput(command, args) { + let output = '' + await this.exec(command, args, { + listeners: { + stdout: (data) => { + output += data.toString() + }, + }, + }) + return output + } + extractFilenamesFromConflicts(logText) { const regex = /CONFLICT \(content\): Merge conflict in\s+([^\n]+)/g const matches = [] diff --git a/staging-auto-merge/tests/merge-drivers.test.js b/staging-auto-merge/tests/merge-drivers.test.js new file mode 100644 index 0000000..7763bd4 --- /dev/null +++ b/staging-auto-merge/tests/merge-drivers.test.js @@ -0,0 +1,213 @@ +import { execFileSync, spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { exec as actionsExec } from '@actions/exec' +import StagingAutoMerge from '../src/staging-auto-merge.js' +import { attributeLines, driverCommand, parseMergeDrivers } from '../src/merge-drivers.js' + +describe('parseMergeDrivers', () => { + it('returns no drivers for a blank input', () => { + expect(parseMergeDrivers('')).toEqual([]) + expect(parseMergeDrivers(' \n')).toEqual([]) + expect(parseMergeDrivers('[]')).toEqual([]) + }) + + it('accepts a built-in driver name on its own', () => { + const [driver] = parseMergeDrivers('railsschema') + + expect(driver).toMatchObject({ name: 'railsschema', files: ['db/schema.rb'] }) + expect(driver.path).toMatch(/drivers\/railsschema$/) + }) + + it('mixes built-in and custom drivers', () => { + const drivers = parseMergeDrivers(` +- railsschema +- name: lockfile + files: [Gemfile.lock, "*.lock"] + script: | + exec bin/merge-lockfile "$@" +`) + + expect(drivers.map((driver) => driver.name)).toEqual(['railsschema', 'lockfile']) + expect(drivers[1]).toMatchObject({ files: ['Gemfile.lock', '*.lock'], script: 'exec bin/merge-lockfile "$@"\n' }) + }) + + it('lets a built-in driver apply to other files', () => { + const [driver] = parseMergeDrivers('- name: railsschema\n files: db/primary_schema.rb') + + expect(driver.files).toEqual(['db/primary_schema.rb']) + }) + + it.each([ + ['an unknown built-in driver', 'nope', /Unknown built-in merge driver "nope"/], + ['a custom driver without files', '- name: mine\n script: exit 0', /"mine" needs files/], + ['a custom driver reusing a built-in name', '- name: railsschema\n files: x\n script: exit 0', /is built in/], + ['a name git config cannot hold', '- name: "my driver"\n files: x\n script: exit 0', /name must be/], + ['a file pattern with a space', '- name: mine\n files: "a b"\n script: exit 0', /invalid file pattern/], + ['a misspelled key', '- name: mine\n file: x\n script: exit 0', /unknown keys: file/], + ['the same driver twice', '- railsschema\n- railsschema', /listed more than once/], + ])('rejects %s', (_, input, message) => { + expect(() => parseMergeDrivers(input)).toThrow(message) + }) +}) + +describe('driverCommand', () => { + it('quotes the script path for the shell git runs it with', () => { + expect(driverCommand("/tmp/it's here/x")).toBe("'/tmp/it'\\''s here/x' %O %A %B %L %P") + }) +}) + +describe('attributeLines', () => { + it('routes every pattern to its driver', () => { + expect(attributeLines([{ name: 'a', files: ['x', 'y'] }, { name: 'b', files: ['z'] }])).toEqual([ + 'x merge=a', + 'y merge=a', + 'z merge=b', + ]) + }) +}) + +describe('merging with configured drivers', () => { + // Keep the developer's global git config (signing, hooks) out of the test repo. + const env = { + ...process.env, + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + } + let repo + let scriptDir + + const git = (...args) => spawnSync('git', args, { cwd: repo, env, encoding: 'utf8' }) + const git$ = (...args) => execFileSync('git', args, { cwd: repo, env, encoding: 'utf8' }) + const read = (path) => readFileSync(join(repo, path), 'utf8') + + const writeSchema = (version, ...tables) => { + writeFileSync( + join(repo, 'db/schema.rb'), + `ActiveRecord::Schema[8.1].define(version: ${version}) do\n` + + ' enable_extension "pg_catalog.plpgsql"\n\n' + + tables.map((table) => ` create_table "${table}"\n`).join('\n') + + 'end\n', + ) + } + + const commitSchema = (version, ...tables) => { + writeSchema(version, ...tables) + git$('commit', '-qam', `schema ${version}`) + } + + const configure = async (input) => { + const stagingAutoMerge = new StagingAutoMerge({}, 'main', { owner: 'o', repo: 'r' }, { info: () => {} }, { + mergeDrivers: parseMergeDrivers(input), + scriptDir, + }) + stagingAutoMerge.exec = (command, args, options = {}) => + actionsExec(command, args, { ...options, cwd: repo, env, silent: true }) + await stagingAutoMerge.configureMergeDrivers() + } + + // The same merge the action runs for each pull request. + const squashMerge = (branch) => git('merge', `${branch}`, '--squash', '--verbose').status === 0 + + beforeEach(() => { + repo = mkdtempSync(join(tmpdir(), 'staging-auto-merge-repo-')) + scriptDir = mkdtempSync(join(tmpdir(), 'staging-auto-merge-scripts-')) + mkdirSync(join(repo, 'db')) + writeSchema('2026_01_01_000000', 'accounts', 'people', 'users') + writeFileSync(join(repo, 'VERSION'), '1.0.0\n') + git$('init', '-q', '-b', 'main') + git$('add', '.') + git$('commit', '-qm', 'base') + }) + + afterEach(() => { + rmSync(repo, { recursive: true, force: true }) + rmSync(scriptDir, { recursive: true, force: true }) + }) + + describe('railsschema', () => { + describe('when both branches add a migration', () => { + beforeEach(() => { + git$('checkout', '-qb', 'first') + commitSchema('2026_02_01_000000', 'accounts', 'comments', 'people', 'users') + git$('checkout', '-q', 'main') + git$('checkout', '-qb', 'second') + commitSchema('2026_03_01_000000', 'accounts', 'people', 'users', 'widgets') + git$('checkout', '-q', 'first') + }) + + it('conflicts without the driver', async () => { + expect(squashMerge('second')).toBe(false) + }) + + it('keeps the newest version and both changes', async () => { + await configure('railsschema') + + expect(squashMerge('second')).toBe(true) + expect(read('db/schema.rb')).toContain('define(version: 2026_03_01_000000)') + expect(read('db/schema.rb')).toContain('create_table "comments"') + expect(read('db/schema.rb')).toContain('create_table "widgets"') + }) + + it('takes the newest version whichever side holds it', async () => { + await configure('railsschema') + git$('checkout', '-q', 'second') + + expect(squashMerge('first')).toBe(true) + expect(read('db/schema.rb')).toContain('define(version: 2026_03_01_000000)') + }) + + it('commits nothing to the branch', async () => { + await configure('railsschema') + + expect(git$('status', '--porcelain')).toBe('') + }) + }) + + it('stops the merge with conflict markers around a real conflict only', async () => { + git$('checkout', '-qb', 'first') + commitSchema('2026_02_01_000000', 'accounts', 'members', 'people', 'users') + git$('checkout', '-q', 'main') + git$('checkout', '-qb', 'second') + commitSchema('2026_03_01_000000', 'accounts', 'notes', 'people', 'users') + git$('checkout', '-q', 'first') + await configure('railsschema') + + expect(squashMerge('second')).toBe(false) + const schema = read('db/schema.rb') + expect(schema).toContain('define(version: 2026_03_01_000000)') + expect(schema).toContain('<<<<<<< db/schema.rb (ours)') + expect(schema).toContain('>>>>>>> db/schema.rb (theirs)') + expect(schema.match(/define\(version:/g)).toHaveLength(1) + }) + }) + + it('runs a custom driver alongside a built-in one', async () => { + git$('checkout', '-qb', 'first') + writeFileSync(join(repo, 'VERSION'), '1.1.0\n') + commitSchema('2026_02_01_000000', 'accounts', 'comments', 'people', 'users') + git$('checkout', '-q', 'main') + git$('checkout', '-qb', 'second') + writeFileSync(join(repo, 'VERSION'), '1.2.0\n') + commitSchema('2026_03_01_000000', 'accounts', 'people', 'users', 'widgets') + git$('checkout', '-q', 'first') + + await configure(` +- railsschema +- name: newest-version + files: VERSION + script: | + # $1 base, $2 ours (receives the result), $3 theirs + sort -V "$2" "$3" | tail -1 > "$2.merged" && mv "$2.merged" "$2" +`) + + expect(squashMerge('second')).toBe(true) + expect(read('VERSION')).toBe('1.2.0\n') + expect(read('db/schema.rb')).toContain('define(version: 2026_03_01_000000)') + }) +})