From fb7d9e0d340e497e1880be90a9c7c881380be417 Mon Sep 17 00:00:00 2001 From: Shawn Morreau Date: Thu, 11 Dec 2025 14:53:40 -0500 Subject: [PATCH] move croaked logic, ensure API key error populates comment --- entry | 27096 ++++++++++++++++++++++------------------- main.ts | 21 +- mcp/comment.ts | 113 +- package.json | 2 +- utils/errorReport.ts | 83 +- 5 files changed, 14388 insertions(+), 12927 deletions(-) diff --git a/entry b/entry index ecbb7b8..51b24ec 100755 --- a/entry +++ b/entry @@ -25505,6 +25505,10487 @@ var require_src = __commonJS({ } }); +// utils/cli.ts +function startGroup2(name) { + if (isGitHubActions) { + core.startGroup(name); + } else { + console.group(name); + } +} +function endGroup2() { + if (isGitHubActions) { + core.endGroup(); + } else { + console.groupEnd(); + } +} +function boxString(text, options) { + const { title, maxWidth = 80, indent: indent2 = "", padding = 1 } = options || {}; + const lines = text.trim().split("\n"); + const wrappedLines = []; + for (const line of lines) { + if (line.length <= maxWidth - padding * 2) { + wrappedLines.push(line); + } else { + const words = line.split(" "); + let currentLine = ""; + for (const word of words) { + const testLine = currentLine ? `${currentLine} ${word}` : word; + if (testLine.length <= maxWidth - padding * 2) { + currentLine = testLine; + } else { + if (currentLine) { + wrappedLines.push(currentLine); + currentLine = ""; + } + const maxLineLength2 = maxWidth - padding * 2; + let remainingWord = word; + while (remainingWord.length > maxLineLength2) { + wrappedLines.push(remainingWord.substring(0, maxLineLength2)); + remainingWord = remainingWord.substring(maxLineLength2); + } + currentLine = remainingWord; + } + } + if (currentLine) { + wrappedLines.push(currentLine); + } + } + } + const maxLineLength = Math.max(...wrappedLines.map((line) => line.length)); + const contentBoxWidth = maxLineLength + padding * 2; + const titleLineLength = title ? ` ${title} `.length : 0; + const boxWidth = Math.max(contentBoxWidth, titleLineLength); + let result = ""; + if (title) { + const titleLine = ` ${title} `; + const titlePadding = Math.max(0, boxWidth - titleLine.length); + result += `${indent2}\u250C${titleLine}${"\u2500".repeat(titlePadding)}\u2510 +`; + } + if (!title) { + result += `${indent2}\u250C${"\u2500".repeat(boxWidth)}\u2510 +`; + } + for (const line of wrappedLines) { + const paddedLine = line.padEnd(maxLineLength); + result += `${indent2}\u2502${" ".repeat(padding)}${paddedLine}${" ".repeat(padding)}\u2502 +`; + } + result += `${indent2}\u2514${"\u2500".repeat(boxWidth)}\u2518`; + return result; +} +function box(text, options) { + const boxContent = boxString(text, options); + core.info(boxContent); + if (isGitHubActions) { + core.summary.addRaw(`\`\`\` +${text} +\`\`\` +`); + } +} +async function summaryTable(rows, options) { + const { title } = options || {}; + const formattedRows = rows.map( + (row) => row.map((cell) => { + if (typeof cell === "string") { + return { data: cell }; + } + return cell; + }) + ); + if (isGitHubActions) { + const summary2 = core.summary; + if (title) { + summary2.addRaw(`**${title}** + +`); + } + summary2.addTable(formattedRows); + } + if (title) { + core.info(` +${title}`); + } + const tableText = formattedRows.map((row) => row.map((cell) => cell.data).join(" | ")).join("\n"); + core.info(` +${tableText} +`); +} +async function printTable(rows, options) { + const { title } = options || {}; + const tableData = rows.map( + (row) => row.map((cell) => { + if (typeof cell === "string") { + return cell; + } + return cell.data; + }) + ); + const formatted = (0, import_table.table)(tableData); + if (title) { + core.info(` +${title}`); + } + core.info(` +${formatted} +`); + if (isGitHubActions) { + if (title) { + core.summary.addRaw(`**${title}** + +`); + } + core.summary.addRaw(`\`\`\` +${formatted} +\`\`\` +`); + } +} +function separator(length = 50) { + const separatorText = "\u2500".repeat(length); + core.info(separatorText); + if (isGitHubActions) { + core.summary.addRaw(`--- +`); + } +} +function formatJsonValue(value2) { + const compact = JSON.stringify(value2); + return compact.length > 80 || compact.includes("\n") ? JSON.stringify(value2, null, 2) : compact; +} +function formatIndentedField(label, content) { + if (!content.includes("\n")) { + return ` ${label}: ${content} +`; + } + const lines = content.split("\n"); + let formatted = ` ${label}: ${lines[0]} +`; + for (let i = 1; i < lines.length; i++) { + formatted += ` ${lines[i]} +`; + } + return formatted; +} +var core, import_table, isGitHubActions, isDebugEnabled, log; +var init_cli = __esm({ + "utils/cli.ts"() { + "use strict"; + core = __toESM(require_core(), 1); + import_table = __toESM(require_src(), 1); + isGitHubActions = !!process.env.GITHUB_ACTIONS; + isDebugEnabled = () => process.env.LOG_LEVEL === "debug"; + log = { + /** + * Print info message + */ + info: (message) => { + core.info(message); + if (isGitHubActions) { + core.summary.addRaw(`${message} +`); + } + }, + /** + * Print warning message + */ + warning: (message) => { + core.warning(message); + if (isGitHubActions) { + core.summary.addRaw(`\u26A0\uFE0F ${message} +`); + } + }, + /** + * Print error message + */ + error: (message) => { + core.error(message); + if (isGitHubActions) { + core.summary.addRaw(`\u274C ${message} +`); + } + }, + /** + * Print success message + */ + success: (message) => { + const successMessage = `\u2705 ${message}`; + core.info(successMessage); + if (isGitHubActions) { + core.summary.addRaw(`${successMessage} +`); + } + }, + /** + * Print debug message (only if LOG_LEVEL=debug) + */ + debug: (message) => { + if (isDebugEnabled()) { + if (isGitHubActions) { + core.debug(message); + } else { + core.info(`[DEBUG] ${message}`); + } + } + }, + /** + * Print a formatted box with text + */ + box, + /** + * Add a table to GitHub Actions job summary (rich formatting) + * Only use this once at the end of execution + */ + summaryTable, + /** + * Print a formatted table using the table package + */ + table: printTable, + /** + * Print a separator line + */ + separator, + /** + * Write all accumulated summary content to the job summary + * Call this at the end of execution to finalize the summary + */ + writeSummary: async () => { + if (isGitHubActions) { + await core.summary.write(); + } + }, + /** + * Start a collapsed group (GitHub Actions) or regular group (local) + */ + startGroup: startGroup2, + /** + * End a collapsed group + */ + endGroup: endGroup2, + /** + * Log tool call information to console with formatted output + */ + toolCall: ({ toolName, input }) => { + let output = `\u2192 ${toolName} +`; + const inputFormatted = formatJsonValue(input); + if (inputFormatted !== "{}") { + output += formatIndentedField("input", inputFormatted); + } + log.info(output.trimEnd()); + } + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/arrays.js +var liftArray, spliterate, ReadonlyArray2, includes, range, append2, conflatenate, conflatenateAll, appendUnique, groupBy, arrayEquals; +var init_arrays = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/arrays.js"() { + liftArray = (data) => Array.isArray(data) ? data : [data]; + spliterate = (arr, predicate) => { + const result = [[], []]; + for (const item of arr) { + if (predicate(item)) + result[0].push(item); + else + result[1].push(item); + } + return result; + }; + ReadonlyArray2 = Array; + includes = (array, element) => array.includes(element); + range = (length, offset = 0) => [...new Array(length)].map((_, i) => i + offset); + append2 = (to, value2, opts) => { + if (to === void 0) { + return value2 === void 0 ? [] : Array.isArray(value2) ? value2 : [value2]; + } + if (opts?.prepend) { + if (Array.isArray(value2)) + to.unshift(...value2); + else + to.unshift(value2); + } else { + if (Array.isArray(value2)) + to.push(...value2); + else + to.push(value2); + } + return to; + }; + conflatenate = (to, elementOrList) => { + if (elementOrList === void 0 || elementOrList === null) + return to ?? []; + if (to === void 0 || to === null) + return liftArray(elementOrList); + return to.concat(elementOrList); + }; + conflatenateAll = (...elementsOrLists) => elementsOrLists.reduce(conflatenate, []); + appendUnique = (to, value2, opts) => { + if (to === void 0) + return Array.isArray(value2) ? value2 : [value2]; + const isEqual = opts?.isEqual ?? ((l, r) => l === r); + for (const v of liftArray(value2)) + if (!to.some((existing) => isEqual(existing, v))) + to.push(v); + return to; + }; + groupBy = (array, discriminant) => array.reduce((result, item) => { + const key = item[discriminant]; + result[key] = append2(result[key], item); + return result; + }, {}); + arrayEquals = (l, r, opts) => l.length === r.length && l.every(opts?.isEqual ? (lItem, i) => opts.isEqual(lItem, r[i]) : (lItem, i) => lItem === r[i]); + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/domain.js +var hasDomain2, domainOf2, domainDescriptions2, jsTypeOfDescriptions2; +var init_domain = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/domain.js"() { + hasDomain2 = (data, kind) => domainOf2(data) === kind; + domainOf2 = (data) => { + const builtinType = typeof data; + return builtinType === "object" ? data === null ? "null" : "object" : builtinType === "function" ? "object" : builtinType; + }; + domainDescriptions2 = { + boolean: "boolean", + null: "null", + undefined: "undefined", + bigint: "a bigint", + number: "a number", + object: "an object", + string: "a string", + symbol: "a symbol" + }; + jsTypeOfDescriptions2 = { + ...domainDescriptions2, + function: "a function" + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/errors.js +var InternalArktypeError, throwInternalError2, throwError, ParseError, throwParseError2, noSuggest2, ZeroWidthSpace2; +var init_errors = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/errors.js"() { + InternalArktypeError = class extends Error { + }; + throwInternalError2 = (message) => throwError(message, InternalArktypeError); + throwError = (message, ctor = Error) => { + throw new ctor(message); + }; + ParseError = class extends Error { + name = "ParseError"; + }; + throwParseError2 = (message) => throwError(message, ParseError); + noSuggest2 = (s) => ` ${s}`; + ZeroWidthSpace2 = "\u200B"; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/flatMorph.js +var flatMorph2; +var init_flatMorph = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/flatMorph.js"() { + init_arrays(); + flatMorph2 = (o, flatMapEntry) => { + const result = {}; + const inputIsArray = Array.isArray(o); + let outputShouldBeArray = false; + for (const [i, entry] of Object.entries(o).entries()) { + const mapped = inputIsArray ? flatMapEntry(i, entry[1]) : flatMapEntry(...entry, i); + outputShouldBeArray ||= typeof mapped[0] === "number"; + const flattenedEntries = Array.isArray(mapped[0]) || mapped.length === 0 ? ( + // if we have an empty array (for filtering) or an array with + // another array as its first element, treat it as a list + mapped + ) : [mapped]; + for (const [k, v] of flattenedEntries) { + if (typeof k === "object") + result[k.group] = append2(result[k.group], v); + else + result[k] = v; + } + } + return outputShouldBeArray ? Object.values(result) : result; + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/records.js +var entriesOf, isKeyOf2, hasKey, DynamicBase, NoopBase2, CastableBase, splitByKeys, omit, isEmptyObject2, stringAndSymbolicEntriesOf2, defineProperties, withAlphabetizedKeys, unset2, enumValues; +var init_records = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/records.js"() { + init_errors(); + init_flatMorph(); + entriesOf = Object.entries; + isKeyOf2 = (k, o) => k in o; + hasKey = (o, k) => k in o; + DynamicBase = class { + constructor(properties) { + Object.assign(this, properties); + } + }; + NoopBase2 = class { + }; + CastableBase = class extends NoopBase2 { + }; + splitByKeys = (o, leftKeys) => { + const l = {}; + const r = {}; + let k; + for (k in o) { + if (k in leftKeys) + l[k] = o[k]; + else + r[k] = o[k]; + } + return [l, r]; + }; + omit = (o, keys) => splitByKeys(o, keys)[1]; + isEmptyObject2 = (o) => Object.keys(o).length === 0; + stringAndSymbolicEntriesOf2 = (o) => [ + ...Object.entries(o), + ...Object.getOwnPropertySymbols(o).map((k) => [k, o[k]]) + ]; + defineProperties = (base, merged) => ( + // declared like this to avoid https://github.com/microsoft/TypeScript/issues/55049 + Object.defineProperties(base, Object.getOwnPropertyDescriptors(merged)) + ); + withAlphabetizedKeys = (o) => { + const keys = Object.keys(o).sort(); + const result = {}; + for (let i = 0; i < keys.length; i++) + result[keys[i]] = o[keys[i]]; + return result; + }; + unset2 = noSuggest2(`unset${ZeroWidthSpace2}`); + enumValues = (tsEnum) => Object.values(tsEnum).filter((v) => { + if (typeof v === "number") + return true; + return typeof tsEnum[v] !== "number"; + }); + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/objectKinds.js +var ecmascriptConstructors2, FileConstructor2, platformConstructors2, typedArrayConstructors2, builtinConstructors2, objectKindOf2, objectKindOrDomainOf, isArray, ecmascriptDescriptions2, platformDescriptions2, typedArrayDescriptions2, objectKindDescriptions2, getBuiltinNameOfConstructor2, constructorExtends; +var init_objectKinds = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/objectKinds.js"() { + init_domain(); + init_records(); + ecmascriptConstructors2 = { + Array, + Boolean, + Date, + Error, + Function, + Map, + Number, + Promise, + RegExp, + Set, + String, + WeakMap, + WeakSet + }; + FileConstructor2 = globalThis.File ?? Blob; + platformConstructors2 = { + ArrayBuffer, + Blob, + File: FileConstructor2, + FormData, + Headers, + Request, + Response, + URL + }; + typedArrayConstructors2 = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + BigInt64Array, + BigUint64Array + }; + builtinConstructors2 = { + ...ecmascriptConstructors2, + ...platformConstructors2, + ...typedArrayConstructors2, + String, + Number, + Boolean + }; + objectKindOf2 = (data) => { + let prototype = Object.getPrototypeOf(data); + while (prototype?.constructor && (!isKeyOf2(prototype.constructor.name, builtinConstructors2) || !(data instanceof builtinConstructors2[prototype.constructor.name]))) + prototype = Object.getPrototypeOf(prototype); + const name = prototype?.constructor?.name; + if (name === void 0 || name === "Object") + return void 0; + return name; + }; + objectKindOrDomainOf = (data) => typeof data === "object" && data !== null ? objectKindOf2(data) ?? "object" : domainOf2(data); + isArray = Array.isArray; + ecmascriptDescriptions2 = { + Array: "an array", + Function: "a function", + Date: "a Date", + RegExp: "a RegExp", + Error: "an Error", + Map: "a Map", + Set: "a Set", + String: "a String object", + Number: "a Number object", + Boolean: "a Boolean object", + Promise: "a Promise", + WeakMap: "a WeakMap", + WeakSet: "a WeakSet" + }; + platformDescriptions2 = { + ArrayBuffer: "an ArrayBuffer instance", + Blob: "a Blob instance", + File: "a File instance", + FormData: "a FormData instance", + Headers: "a Headers instance", + Request: "a Request instance", + Response: "a Response instance", + URL: "a URL instance" + }; + typedArrayDescriptions2 = { + Int8Array: "an Int8Array", + Uint8Array: "a Uint8Array", + Uint8ClampedArray: "a Uint8ClampedArray", + Int16Array: "an Int16Array", + Uint16Array: "a Uint16Array", + Int32Array: "an Int32Array", + Uint32Array: "a Uint32Array", + Float32Array: "a Float32Array", + Float64Array: "a Float64Array", + BigInt64Array: "a BigInt64Array", + BigUint64Array: "a BigUint64Array" + }; + objectKindDescriptions2 = { + ...ecmascriptDescriptions2, + ...platformDescriptions2, + ...typedArrayDescriptions2 + }; + getBuiltinNameOfConstructor2 = (ctor) => { + const constructorName = Object(ctor).name ?? null; + return constructorName && isKeyOf2(constructorName, builtinConstructors2) && builtinConstructors2[constructorName] === ctor ? constructorName : null; + }; + constructorExtends = (ctor, base) => { + let current = ctor.prototype; + while (current !== null) { + if (current === base.prototype) + return true; + current = Object.getPrototypeOf(current); + } + return false; + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/clone.js +var deepClone, _clone; +var init_clone = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/clone.js"() { + init_objectKinds(); + deepClone = (input) => _clone(input, /* @__PURE__ */ new Map()); + _clone = (input, seen) => { + if (typeof input !== "object" || input === null) + return input; + if (seen?.has(input)) + return seen.get(input); + const builtinConstructorName = getBuiltinNameOfConstructor2(input.constructor); + if (builtinConstructorName === "Date") + return new Date(input.getTime()); + if (builtinConstructorName && builtinConstructorName !== "Array") + return input; + const cloned = Array.isArray(input) ? input.slice() : Object.create(Object.getPrototypeOf(input)); + const propertyDescriptors = Object.getOwnPropertyDescriptors(input); + if (seen) { + seen.set(input, cloned); + for (const k in propertyDescriptors) { + const desc = propertyDescriptors[k]; + if ("get" in desc || "set" in desc) + continue; + desc.value = _clone(desc.value, seen); + } + } + Object.defineProperties(cloned, propertyDescriptors); + return cloned; + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/describe.js +var init_describe = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/describe.js"() { + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/functions.js +var cached2, isThunk, DynamicFunction, Callable, envHasCsp2; +var init_functions = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/functions.js"() { + init_errors(); + init_records(); + cached2 = (thunk) => { + let result = unset2; + return () => result === unset2 ? result = thunk() : result; + }; + isThunk = (value2) => typeof value2 === "function" && value2.length === 0; + DynamicFunction = class extends Function { + constructor(...args3) { + const params = args3.slice(0, -1); + const body = args3[args3.length - 1]; + try { + super(...params, body); + } catch (e) { + return throwInternalError2(`Encountered an unexpected error while compiling your definition: + Message: ${e} + Source: (${args3.slice(0, -1)}) => { + ${args3[args3.length - 1]} + }`); + } + } + }; + Callable = class { + constructor(fn2, ...[opts]) { + return Object.assign(Object.setPrototypeOf(fn2.bind(opts?.bind ?? this), this.constructor.prototype), opts?.attach); + } + }; + envHasCsp2 = cached2(() => { + try { + return new Function("return false")(); + } catch { + return true; + } + }); + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/generics.js +var brand2, inferred2; +var init_generics = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/generics.js"() { + init_errors(); + brand2 = noSuggest2("brand"); + inferred2 = noSuggest2("arkInferred"); + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/hkt.js +var args2, Hkt; +var init_hkt = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/hkt.js"() { + init_errors(); + args2 = noSuggest2("args"); + Hkt = class { + constructor() { + } + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/intersections.js +var init_intersections = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/intersections.js"() { + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/isomorphic.js +var fileName2, env2, isomorphic2; +var init_isomorphic = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/isomorphic.js"() { + fileName2 = () => { + try { + const error41 = new Error(); + const stackLine = error41.stack?.split("\n")[2]?.trim() || ""; + const filePath = stackLine.match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1] || "unknown"; + return filePath.replace(/^file:\/\//, ""); + } catch { + return "unknown"; + } + }; + env2 = globalThis.process?.env ?? {}; + isomorphic2 = { + fileName: fileName2, + env: env2 + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/keys.js +var init_keys = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/keys.js"() { + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/lazily.js +var init_lazily = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/lazily.js"() { + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/strings.js +var capitalize, uncapitalize, anchoredRegex2, anchoredSource2, RegexPatterns2, Backslash2, whitespaceChars2; +var init_strings = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/strings.js"() { + capitalize = (s) => s[0].toUpperCase() + s.slice(1); + uncapitalize = (s) => s[0].toLowerCase() + s.slice(1); + anchoredRegex2 = (regex3) => new RegExp(anchoredSource2(regex3), typeof regex3 === "string" ? "" : regex3.flags); + anchoredSource2 = (regex3) => { + const source = typeof regex3 === "string" ? regex3 : regex3.source; + return `^(?:${source})$`; + }; + RegexPatterns2 = { + negativeLookahead: (pattern) => `(?!${pattern})`, + nonCapturingGroup: (pattern) => `(?:${pattern})` + }; + Backslash2 = "\\"; + whitespaceChars2 = { + " ": 1, + "\n": 1, + " ": 1 + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/numbers.js +var anchoredNegativeZeroPattern2, positiveIntegerPattern2, looseDecimalPattern2, strictDecimalPattern2, createNumberMatcher2, wellFormedNumberMatcher2, isWellFormedNumber2, numericStringMatcher2, isNumericString2, numberLikeMatcher, isNumberLike, wellFormedIntegerMatcher2, isWellFormedInteger2, integerLikeMatcher2, isIntegerLike2, numericLiteralDescriptions, writeMalformedNumericLiteralMessage, isWellFormed, parseKind, isKindLike, tryParseNumber, tryParseWellFormedNumber, tryParseInteger, parseNumeric, tryParseWellFormedBigint; +var init_numbers = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/numbers.js"() { + init_errors(); + init_strings(); + anchoredNegativeZeroPattern2 = /^-0\.?0*$/.source; + positiveIntegerPattern2 = /[1-9]\d*/.source; + looseDecimalPattern2 = /\.\d+/.source; + strictDecimalPattern2 = /\.\d*[1-9]/.source; + createNumberMatcher2 = (opts) => anchoredRegex2(RegexPatterns2.negativeLookahead(anchoredNegativeZeroPattern2) + RegexPatterns2.nonCapturingGroup("-?" + RegexPatterns2.nonCapturingGroup(RegexPatterns2.nonCapturingGroup("0|" + positiveIntegerPattern2) + RegexPatterns2.nonCapturingGroup(opts.decimalPattern) + "?") + (opts.allowDecimalOnly ? "|" + opts.decimalPattern : "") + "?")); + wellFormedNumberMatcher2 = createNumberMatcher2({ + decimalPattern: strictDecimalPattern2, + allowDecimalOnly: false + }); + isWellFormedNumber2 = wellFormedNumberMatcher2.test.bind(wellFormedNumberMatcher2); + numericStringMatcher2 = createNumberMatcher2({ + decimalPattern: looseDecimalPattern2, + allowDecimalOnly: true + }); + isNumericString2 = numericStringMatcher2.test.bind(numericStringMatcher2); + numberLikeMatcher = /^-?\d*\.?\d*$/; + isNumberLike = (s) => s.length !== 0 && numberLikeMatcher.test(s); + wellFormedIntegerMatcher2 = anchoredRegex2(RegexPatterns2.negativeLookahead("^-0$") + "-?" + RegexPatterns2.nonCapturingGroup(RegexPatterns2.nonCapturingGroup("0|" + positiveIntegerPattern2))); + isWellFormedInteger2 = wellFormedIntegerMatcher2.test.bind(wellFormedIntegerMatcher2); + integerLikeMatcher2 = /^-?\d+$/; + isIntegerLike2 = integerLikeMatcher2.test.bind(integerLikeMatcher2); + numericLiteralDescriptions = { + number: "a number", + bigint: "a bigint", + integer: "an integer" + }; + writeMalformedNumericLiteralMessage = (def, kind) => `'${def}' was parsed as ${numericLiteralDescriptions[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`; + isWellFormed = (def, kind) => kind === "number" ? isWellFormedNumber2(def) : isWellFormedInteger2(def); + parseKind = (def, kind) => kind === "number" ? Number(def) : Number.parseInt(def); + isKindLike = (def, kind) => kind === "number" ? isNumberLike(def) : isIntegerLike2(def); + tryParseNumber = (token, options) => parseNumeric(token, "number", options); + tryParseWellFormedNumber = (token, options) => parseNumeric(token, "number", { ...options, strict: true }); + tryParseInteger = (token, options) => parseNumeric(token, "integer", options); + parseNumeric = (token, kind, options) => { + const value2 = parseKind(token, kind); + if (!Number.isNaN(value2)) { + if (isKindLike(token, kind)) { + if (options?.strict) { + return isWellFormed(token, kind) ? value2 : throwParseError2(writeMalformedNumericLiteralMessage(token, kind)); + } + return value2; + } + } + return options?.errorOnFail ? throwParseError2(options?.errorOnFail === true ? `Failed to parse ${numericLiteralDescriptions[kind]} from '${token}'` : options?.errorOnFail) : void 0; + }; + tryParseWellFormedBigint = (def) => { + if (def[def.length - 1] !== "n") + return; + const maybeIntegerLiteral = def.slice(0, -1); + let value2; + try { + value2 = BigInt(maybeIntegerLiteral); + } catch { + return; + } + if (wellFormedIntegerMatcher2.test(maybeIntegerLiteral)) + return value2; + if (integerLikeMatcher2.test(maybeIntegerLiteral)) { + return throwParseError2(writeMalformedNumericLiteralMessage(def, "bigint")); + } + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/registry.js +var arkUtilVersion2, initialRegistryContents2, registry, namesByResolution, nameCounts, register2, isDotAccessible2, baseNameFor; +var init_registry = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/registry.js"() { + init_domain(); + init_errors(); + init_isomorphic(); + init_objectKinds(); + arkUtilVersion2 = "0.56.0"; + initialRegistryContents2 = { + version: arkUtilVersion2, + filename: isomorphic2.fileName(), + FileConstructor: FileConstructor2 + }; + registry = initialRegistryContents2; + namesByResolution = /* @__PURE__ */ new Map(); + nameCounts = /* @__PURE__ */ Object.create(null); + register2 = (value2) => { + const existingName = namesByResolution.get(value2); + if (existingName) + return existingName; + let name = baseNameFor(value2); + if (nameCounts[name]) + name = `${name}${nameCounts[name]++}`; + else + nameCounts[name] = 1; + registry[name] = value2; + namesByResolution.set(value2, name); + return name; + }; + isDotAccessible2 = (keyName) => /^[$A-Z_a-z][\w$]*$/.test(keyName); + baseNameFor = (value2) => { + switch (typeof value2) { + case "object": { + if (value2 === null) + break; + const prefix = objectKindOf2(value2) ?? "object"; + return prefix[0].toLowerCase() + prefix.slice(1); + } + case "function": + return isDotAccessible2(value2.name) ? value2.name : "fn"; + case "symbol": + return value2.description && isDotAccessible2(value2.description) ? value2.description : "symbol"; + } + return throwInternalError2(`Unexpected attempt to register serializable value of type ${domainOf2(value2)}`); + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/primitive.js +var serializePrimitive2; +var init_primitive = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/primitive.js"() { + serializePrimitive2 = (value2) => typeof value2 === "string" ? JSON.stringify(value2) : typeof value2 === "bigint" ? `${value2}n` : `${value2}`; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/serialize.js +var snapshot, printable2, stringifyUnquoted, printableOpts, _serialize, describeCollapsibleDate, months, timeWithUnnecessarySeconds, pad; +var init_serialize = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/serialize.js"() { + init_domain(); + init_primitive(); + init_records(); + init_registry(); + snapshot = (data, opts = {}) => _serialize(data, { + onUndefined: `$ark.undefined`, + onBigInt: (n) => `$ark.bigint-${n}`, + ...opts + }, []); + printable2 = (data, opts) => { + switch (domainOf2(data)) { + case "object": + const o = data; + const ctorName = o.constructor?.name ?? "Object"; + return ctorName === "Object" || ctorName === "Array" ? opts?.quoteKeys === false ? stringifyUnquoted(o, opts?.indent ?? 0, "") : JSON.stringify(_serialize(o, printableOpts, []), null, opts?.indent) : stringifyUnquoted(o, opts?.indent ?? 0, ""); + case "symbol": + return printableOpts.onSymbol(data); + default: + return serializePrimitive2(data); + } + }; + stringifyUnquoted = (value2, indent2, currentIndent) => { + if (typeof value2 === "function") + return printableOpts.onFunction(value2); + if (typeof value2 !== "object" || value2 === null) + return serializePrimitive2(value2); + const nextIndent = currentIndent + " ".repeat(indent2); + if (Array.isArray(value2)) { + if (value2.length === 0) + return "[]"; + const items = value2.map((item) => stringifyUnquoted(item, indent2, nextIndent)).join(",\n" + nextIndent); + return indent2 ? `[ +${nextIndent}${items} +${currentIndent}]` : `[${items}]`; + } + const ctorName = value2.constructor?.name ?? "Object"; + if (ctorName === "Object") { + const keyValues = stringAndSymbolicEntriesOf2(value2).map(([key, val]) => { + const stringifiedKey = typeof key === "symbol" ? printableOpts.onSymbol(key) : isDotAccessible2(key) ? key : JSON.stringify(key); + const stringifiedValue = stringifyUnquoted(val, indent2, nextIndent); + return `${nextIndent}${stringifiedKey}: ${stringifiedValue}`; + }); + if (keyValues.length === 0) + return "{}"; + return indent2 ? `{ +${keyValues.join(",\n")} +${currentIndent}}` : `{${keyValues.join(", ")}}`; + } + if (value2 instanceof Date) + return describeCollapsibleDate(value2); + if ("expression" in value2 && typeof value2.expression === "string") + return value2.expression; + return ctorName; + }; + printableOpts = { + onCycle: () => "(cycle)", + onSymbol: (v) => `Symbol(${register2(v)})`, + onFunction: (v) => `Function(${register2(v)})` + }; + _serialize = (data, opts, seen) => { + switch (domainOf2(data)) { + case "object": { + const o = data; + if ("toJSON" in o && typeof o.toJSON === "function") + return o.toJSON(); + if (typeof o === "function") + return printableOpts.onFunction(o); + if (seen.includes(o)) + return "(cycle)"; + const nextSeen = [...seen, o]; + if (Array.isArray(o)) + return o.map((item) => _serialize(item, opts, nextSeen)); + if (o instanceof Date) + return o.toDateString(); + const result = {}; + for (const k in o) + result[k] = _serialize(o[k], opts, nextSeen); + for (const s of Object.getOwnPropertySymbols(o)) { + result[opts.onSymbol?.(s) ?? s.toString()] = _serialize(o[s], opts, nextSeen); + } + return result; + } + case "symbol": + return printableOpts.onSymbol(data); + case "bigint": + return opts.onBigInt?.(data) ?? `${data}n`; + case "undefined": + return opts.onUndefined ?? "undefined"; + case "string": + return data.replace(/\\/g, "\\\\"); + default: + return data; + } + }; + describeCollapsibleDate = (date2) => { + const year = date2.getFullYear(); + const month = date2.getMonth(); + const dayOfMonth = date2.getDate(); + const hours = date2.getHours(); + const minutes = date2.getMinutes(); + const seconds = date2.getSeconds(); + const milliseconds = date2.getMilliseconds(); + if (month === 0 && dayOfMonth === 1 && hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0) + return `${year}`; + const datePortion = `${months[month]} ${dayOfMonth}, ${year}`; + if (hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0) + return datePortion; + let timePortion = date2.toLocaleTimeString(); + const suffix2 = timePortion.endsWith(" AM") || timePortion.endsWith(" PM") ? timePortion.slice(-3) : ""; + if (suffix2) + timePortion = timePortion.slice(0, -suffix2.length); + if (milliseconds) + timePortion += `.${pad(milliseconds, 3)}`; + else if (timeWithUnnecessarySeconds.test(timePortion)) + timePortion = timePortion.slice(0, -3); + return `${timePortion + suffix2}, ${datePortion}`; + }; + months = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ]; + timeWithUnnecessarySeconds = /:\d\d:00$/; + pad = (value2, length) => String(value2).padStart(length, "0"); + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/path.js +var appendStringifiedKey, stringifyPath, ReadonlyPath; +var init_path = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/path.js"() { + init_arrays(); + init_errors(); + init_registry(); + init_serialize(); + appendStringifiedKey = (path3, prop, ...[opts]) => { + const stringifySymbol = opts?.stringifySymbol ?? printable2; + let propAccessChain = path3; + switch (typeof prop) { + case "string": + propAccessChain = isDotAccessible2(prop) ? path3 === "" ? prop : `${path3}.${prop}` : `${path3}[${JSON.stringify(prop)}]`; + break; + case "number": + propAccessChain = `${path3}[${prop}]`; + break; + case "symbol": + propAccessChain = `${path3}[${stringifySymbol(prop)}]`; + break; + default: + if (opts?.stringifyNonKey) + propAccessChain = `${path3}[${opts.stringifyNonKey(prop)}]`; + else { + throwParseError2(`${printable2(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`); + } + } + return propAccessChain; + }; + stringifyPath = (path3, ...opts) => path3.reduce((s, k) => appendStringifiedKey(s, k, ...opts), ""); + ReadonlyPath = class extends ReadonlyArray2 { + // alternate strategy for caching since the base object is frozen + cache = {}; + constructor(...items) { + super(); + this.push(...items); + } + toJSON() { + if (this.cache.json) + return this.cache.json; + this.cache.json = []; + for (let i = 0; i < this.length; i++) { + this.cache.json.push(typeof this[i] === "symbol" ? printable2(this[i]) : this[i]); + } + return this.cache.json; + } + stringify() { + if (this.cache.stringify) + return this.cache.stringify; + return this.cache.stringify = stringifyPath(this); + } + stringifyAncestors() { + if (this.cache.stringifyAncestors) + return this.cache.stringifyAncestors; + let propString = ""; + const result = [propString]; + for (const path3 of this) { + propString = appendStringifiedKey(propString, path3); + result.push(propString); + } + return this.cache.stringifyAncestors = result; + } + }; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/scanner.js +var Scanner, writeUnmatchedGroupCloseMessage, writeUnclosedGroupMessage; +var init_scanner = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/scanner.js"() { + init_strings(); + Scanner = class { + chars; + i; + def; + constructor(def) { + this.def = def; + this.chars = [...def]; + this.i = 0; + } + /** Get lookahead and advance scanner by one */ + shift() { + return this.chars[this.i++] ?? ""; + } + get lookahead() { + return this.chars[this.i] ?? ""; + } + get nextLookahead() { + return this.chars[this.i + 1] ?? ""; + } + get length() { + return this.chars.length; + } + shiftUntil(condition) { + let shifted = ""; + while (this.lookahead) { + if (condition(this, shifted)) + break; + else + shifted += this.shift(); + } + return shifted; + } + shiftUntilEscapable(condition) { + let shifted = ""; + while (this.lookahead) { + if (this.lookahead === Backslash2) { + this.shift(); + if (condition(this, shifted)) + shifted += this.shift(); + else if (this.lookahead === Backslash2) + shifted += this.shift(); + else + shifted += `${Backslash2}${this.shift()}`; + } else if (condition(this, shifted)) + break; + else + shifted += this.shift(); + } + return shifted; + } + shiftUntilLookahead(charOrSet) { + return typeof charOrSet === "string" ? this.shiftUntil((s) => s.lookahead === charOrSet) : this.shiftUntil((s) => s.lookahead in charOrSet); + } + shiftUntilNonWhitespace() { + return this.shiftUntil(() => !(this.lookahead in whitespaceChars2)); + } + jumpToIndex(i) { + this.i = i < 0 ? this.length + i : i; + } + jumpForward(count) { + this.i += count; + } + get location() { + return this.i; + } + get unscanned() { + return this.chars.slice(this.i, this.length).join(""); + } + get scanned() { + return this.chars.slice(0, this.i).join(""); + } + sliceChars(start, end) { + return this.chars.slice(start, end).join(""); + } + lookaheadIs(char) { + return this.lookahead === char; + } + lookaheadIsIn(tokens) { + return this.lookahead in tokens; + } + }; + writeUnmatchedGroupCloseMessage = (char, unscanned) => `Unmatched ${char}${unscanned === "" ? "" : ` before ${unscanned}`}`; + writeUnclosedGroupMessage = (missingChar) => `Missing ${missingChar}`; + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/traits.js +var implementedTraits2; +var init_traits = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/traits.js"() { + init_domain(); + init_errors(); + init_objectKinds(); + init_records(); + implementedTraits2 = noSuggest2("implementedTraits"); + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/unionToTuple.js +var init_unionToTuple = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/unionToTuple.js"() { + } +}); + +// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/index.js +var init_out = __esm({ + "node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/index.js"() { + init_arrays(); + init_clone(); + init_describe(); + init_domain(); + init_errors(); + init_flatMorph(); + init_functions(); + init_generics(); + init_hkt(); + init_intersections(); + init_isomorphic(); + init_keys(); + init_lazily(); + init_numbers(); + init_objectKinds(); + init_path(); + init_primitive(); + init_records(); + init_registry(); + init_scanner(); + init_serialize(); + init_strings(); + init_traits(); + init_unionToTuple(); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/registry.js +var _registryName, suffix, registryName, $ark, reference, registeredReference; +var init_registry2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/registry.js"() { + init_out(); + _registryName = "$ark"; + suffix = 2; + while (_registryName in globalThis) + _registryName = `$ark${suffix++}`; + registryName = _registryName; + globalThis[registryName] = registry; + $ark = registry; + reference = (name) => `${registryName}.${name}`; + registeredReference = (value2) => reference(register2(value2)); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/compile.js +var CompiledFunction, compileSerializedValue, compileLiteralPropAccess, serializeLiteralKey, indexPropAccess, NodeCompiler; +var init_compile = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/compile.js"() { + init_out(); + init_registry2(); + CompiledFunction = class extends CastableBase { + argNames; + body = ""; + constructor(...args3) { + super(); + this.argNames = args3; + for (const arg of args3) { + if (arg in this) { + throw new Error(`Arg name '${arg}' would overwrite an existing property on FunctionBody`); + } + ; + this[arg] = arg; + } + } + indentation = 0; + indent() { + this.indentation += 4; + return this; + } + dedent() { + this.indentation -= 4; + return this; + } + prop(key, optional = false) { + return compileLiteralPropAccess(key, optional); + } + index(key, optional = false) { + return indexPropAccess(`${key}`, optional); + } + line(statement) { + ; + this.body += `${" ".repeat(this.indentation)}${statement} +`; + return this; + } + const(identifier, expression) { + this.line(`const ${identifier} = ${expression}`); + return this; + } + let(identifier, expression) { + return this.line(`let ${identifier} = ${expression}`); + } + set(identifier, expression) { + return this.line(`${identifier} = ${expression}`); + } + if(condition, then) { + return this.block(`if (${condition})`, then); + } + elseIf(condition, then) { + return this.block(`else if (${condition})`, then); + } + else(then) { + return this.block("else", then); + } + /** Current index is "i" */ + for(until, body, initialValue = 0) { + return this.block(`for (let i = ${initialValue}; ${until}; i++)`, body); + } + /** Current key is "k" */ + forIn(object2, body) { + return this.block(`for (const k in ${object2})`, body); + } + block(prefix, contents, suffix2 = "") { + this.line(`${prefix} {`); + this.indent(); + contents(this); + this.dedent(); + return this.line(`}${suffix2}`); + } + return(expression = "") { + return this.line(`return ${expression}`); + } + write(name = "anonymous", indent2 = 0) { + return `${name}(${this.argNames.join(", ")}) { ${indent2 ? this.body.split("\n").map((l) => " ".repeat(indent2) + `${l}`).join("\n") : this.body} }`; + } + compile() { + return new DynamicFunction(...this.argNames, this.body); + } + }; + compileSerializedValue = (value2) => hasDomain2(value2, "object") || typeof value2 === "symbol" ? registeredReference(value2) : serializePrimitive2(value2); + compileLiteralPropAccess = (key, optional = false) => { + if (typeof key === "string" && isDotAccessible2(key)) + return `${optional ? "?" : ""}.${key}`; + return indexPropAccess(serializeLiteralKey(key), optional); + }; + serializeLiteralKey = (key) => typeof key === "symbol" ? registeredReference(key) : JSON.stringify(key); + indexPropAccess = (key, optional = false) => `${optional ? "?." : ""}[${key}]`; + NodeCompiler = class extends CompiledFunction { + traversalKind; + optimistic; + constructor(ctx) { + super("data", "ctx"); + this.traversalKind = ctx.kind; + this.optimistic = ctx.optimistic === true; + } + invoke(node2, opts) { + const arg = opts?.arg ?? this.data; + const requiresContext = typeof node2 === "string" ? true : this.requiresContextFor(node2); + const id = typeof node2 === "string" ? node2 : node2.id; + if (requiresContext) + return `${this.referenceToId(id, opts)}(${arg}, ${this.ctx})`; + return `${this.referenceToId(id, opts)}(${arg})`; + } + referenceToId(id, opts) { + const invokedKind = opts?.kind ?? this.traversalKind; + const base = `this.${id}${invokedKind}`; + return opts?.bind ? `${base}.bind(${opts?.bind})` : base; + } + requiresContextFor(node2) { + return this.traversalKind === "Apply" || node2.allowsRequiresContext; + } + initializeErrorCount() { + return this.const("errorCount", "ctx.currentErrorCount"); + } + returnIfFail() { + return this.if("ctx.currentErrorCount > errorCount", () => this.return()); + } + returnIfFailFast() { + return this.if("ctx.failFast && ctx.currentErrorCount > errorCount", () => this.return()); + } + traverseKey(keyExpression, accessExpression, node2) { + const requiresContext = this.requiresContextFor(node2); + if (requiresContext) + this.line(`${this.ctx}.path.push(${keyExpression})`); + this.check(node2, { + arg: accessExpression + }); + if (requiresContext) + this.line(`${this.ctx}.path.pop()`); + return this; + } + check(node2, opts) { + return this.traversalKind === "Allows" ? this.if(`!${this.invoke(node2, opts)}`, () => this.return(false)) : this.line(this.invoke(node2, opts)); + } + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/utils.js +var makeRootAndArrayPropertiesMutable, arkKind, hasArkKind, isNode; +var init_utils = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/utils.js"() { + init_out(); + makeRootAndArrayPropertiesMutable = (o) => ( + // this cast should not be required, but it seems TS is referencing + // the wrong parameters here? + flatMorph2(o, (k, v) => [k, isArray(v) ? [...v] : v]) + ); + arkKind = noSuggest2("arkKind"); + hasArkKind = (value2, kind) => value2?.[arkKind] === kind; + isNode = (value2) => hasArkKind(value2, "root") || hasArkKind(value2, "constraint"); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/implement.js +var basisKinds, structuralKinds, prestructuralKinds, refinementKinds, constraintKinds, rootKinds, nodeKinds, constraintKeys, structureKeys, precedenceByKind, isNodeKind, precedenceOfKind, schemaKindsRightOf, unionChildKinds, morphChildKinds, defaultValueSerializer, compileObjectLiteral, implementNode; +var init_implement = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/implement.js"() { + init_out(); + init_compile(); + init_utils(); + basisKinds = ["unit", "proto", "domain"]; + structuralKinds = [ + "required", + "optional", + "index", + "sequence" + ]; + prestructuralKinds = [ + "pattern", + "divisor", + "exactLength", + "max", + "min", + "maxLength", + "minLength", + "before", + "after" + ]; + refinementKinds = [ + ...prestructuralKinds, + "structure", + "predicate" + ]; + constraintKinds = [...refinementKinds, ...structuralKinds]; + rootKinds = [ + "alias", + "union", + "morph", + "unit", + "intersection", + "proto", + "domain" + ]; + nodeKinds = [...rootKinds, ...constraintKinds]; + constraintKeys = flatMorph2(constraintKinds, (i, kind) => [kind, 1]); + structureKeys = flatMorph2([...structuralKinds, "undeclared"], (i, k) => [k, 1]); + precedenceByKind = flatMorph2(nodeKinds, (i, kind) => [kind, i]); + isNodeKind = (value2) => typeof value2 === "string" && value2 in precedenceByKind; + precedenceOfKind = (kind) => precedenceByKind[kind]; + schemaKindsRightOf = (kind) => rootKinds.slice(precedenceOfKind(kind) + 1); + unionChildKinds = [ + ...schemaKindsRightOf("union"), + "alias" + ]; + morphChildKinds = [ + ...schemaKindsRightOf("morph"), + "alias" + ]; + defaultValueSerializer = (v) => { + if (typeof v === "string" || typeof v === "boolean" || v === null) + return v; + if (typeof v === "number") { + if (Number.isNaN(v)) + return "NaN"; + if (v === Number.POSITIVE_INFINITY) + return "Infinity"; + if (v === Number.NEGATIVE_INFINITY) + return "-Infinity"; + return v; + } + return compileSerializedValue(v); + }; + compileObjectLiteral = (ctx) => { + let result = "{ "; + for (const [k, v] of Object.entries(ctx)) + result += `${k}: ${compileSerializedValue(v)}, `; + return result + " }"; + }; + implementNode = (_) => { + const implementation23 = _; + if (implementation23.hasAssociatedError) { + implementation23.defaults.expected ??= (ctx) => "description" in ctx ? ctx.description : implementation23.defaults.description(ctx); + implementation23.defaults.actual ??= (data) => printable2(data); + implementation23.defaults.problem ??= (ctx) => `must be ${ctx.expected}${ctx.actual ? ` (was ${ctx.actual})` : ""}`; + implementation23.defaults.message ??= (ctx) => { + if (ctx.path.length === 0) + return ctx.problem; + const problemWithLocation = `${ctx.propString} ${ctx.problem}`; + if (problemWithLocation[0] === "[") { + return `value at ${problemWithLocation}`; + } + return problemWithLocation; + }; + } + return implementation23; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/toJsonSchema.js +var ToJsonSchemaError, defaultConfig, ToJsonSchema; +var init_toJsonSchema = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/toJsonSchema.js"() { + init_out(); + ToJsonSchemaError = class extends Error { + name = "ToJsonSchemaError"; + code; + context; + constructor(code, context) { + super(printable2(context, { quoteKeys: false, indent: 4 })); + this.code = code; + this.context = context; + } + hasCode(code) { + return this.code === code; + } + }; + defaultConfig = { + target: "draft-2020-12", + dialect: "https://json-schema.org/draft/2020-12/schema", + useRefs: false, + fallback: { + arrayObject: (ctx) => ToJsonSchema.throw("arrayObject", ctx), + arrayPostfix: (ctx) => ToJsonSchema.throw("arrayPostfix", ctx), + defaultValue: (ctx) => ToJsonSchema.throw("defaultValue", ctx), + domain: (ctx) => ToJsonSchema.throw("domain", ctx), + morph: (ctx) => ToJsonSchema.throw("morph", ctx), + patternIntersection: (ctx) => ToJsonSchema.throw("patternIntersection", ctx), + predicate: (ctx) => ToJsonSchema.throw("predicate", ctx), + proto: (ctx) => ToJsonSchema.throw("proto", ctx), + symbolKey: (ctx) => ToJsonSchema.throw("symbolKey", ctx), + unit: (ctx) => ToJsonSchema.throw("unit", ctx), + date: (ctx) => ToJsonSchema.throw("date", ctx) + } + }; + ToJsonSchema = { + Error: ToJsonSchemaError, + throw: (...args3) => { + throw new ToJsonSchema.Error(...args3); + }, + throwInternalOperandError: (kind, schema2) => throwInternalError2(`Unexpected JSON Schema input for ${kind}: ${printable2(schema2)}`), + defaultConfig + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/config.js +var configureSchema, mergeConfigs, jsonSchemaTargetToDialect, mergeToJsonSchemaConfigs, resolveTargetToDialect, mergeFallbacks, normalizeFallback; +var init_config = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/config.js"() { + init_implement(); + init_registry2(); + init_toJsonSchema(); + $ark.config ??= {}; + configureSchema = (config2) => { + const result = Object.assign($ark.config, mergeConfigs($ark.config, config2)); + if ($ark.resolvedConfig) + $ark.resolvedConfig = mergeConfigs($ark.resolvedConfig, result); + return result; + }; + mergeConfigs = (base, merged) => { + if (!merged) + return base; + const result = { ...base }; + let k; + for (k in merged) { + const keywords2 = { ...base.keywords }; + if (k === "keywords") { + for (const flatAlias in merged[k]) { + const v = merged.keywords[flatAlias]; + if (v === void 0) + continue; + keywords2[flatAlias] = typeof v === "string" ? { description: v } : v; + } + result.keywords = keywords2; + } else if (k === "toJsonSchema") { + result[k] = mergeToJsonSchemaConfigs(base.toJsonSchema, merged.toJsonSchema); + } else if (isNodeKind(k)) { + result[k] = // not casting this makes TS compute a very inefficient + // type that is not needed + { + ...base[k], + ...merged[k] + }; + } else + result[k] = merged[k]; + } + return result; + }; + jsonSchemaTargetToDialect = { + "draft-2020-12": "https://json-schema.org/draft/2020-12/schema", + "draft-07": "http://json-schema.org/draft-07/schema#" + }; + mergeToJsonSchemaConfigs = ((baseConfig, mergedConfig) => { + if (!baseConfig) + return resolveTargetToDialect(mergedConfig ?? {}, void 0); + if (!mergedConfig) + return baseConfig; + const result = { ...baseConfig }; + let k; + for (k in mergedConfig) { + if (k === "fallback") { + result.fallback = mergeFallbacks(baseConfig.fallback, mergedConfig.fallback); + } else + result[k] = mergedConfig[k]; + } + return resolveTargetToDialect(result, mergedConfig); + }); + resolveTargetToDialect = (opts, userOpts) => { + if (userOpts?.dialect !== void 0) + return opts; + if (userOpts?.target !== void 0) { + return { + ...opts, + dialect: jsonSchemaTargetToDialect[userOpts.target] + }; + } + return opts; + }; + mergeFallbacks = (base, merged) => { + base = normalizeFallback(base); + merged = normalizeFallback(merged); + const result = {}; + let code; + for (code in ToJsonSchema.defaultConfig.fallback) { + result[code] = merged[code] ?? merged.default ?? base[code] ?? base.default ?? ToJsonSchema.defaultConfig.fallback[code]; + } + return result; + }; + normalizeFallback = (fallback) => typeof fallback === "function" ? { default: fallback } : fallback ?? {}; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/errors.js +var ArkError, ArkErrors, TraversalError, indent; +var init_errors2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/errors.js"() { + init_out(); + init_utils(); + ArkError = class _ArkError extends CastableBase { + [arkKind] = "error"; + path; + data; + nodeConfig; + input; + ctx; + // TS gets confused by , so internally we just use the base type for input + constructor({ prefixPath, relativePath, ...input }, ctx) { + super(); + this.input = input; + this.ctx = ctx; + defineProperties(this, input); + const data = ctx.data; + if (input.code === "union") { + input.errors = input.errors.flatMap((innerError) => { + const flat = innerError.hasCode("union") ? innerError.errors : [innerError]; + if (!prefixPath && !relativePath) + return flat; + return flat.map((e) => e.transform((e2) => ({ + ...e2, + path: conflatenateAll(prefixPath, e2.path, relativePath) + }))); + }); + } + this.nodeConfig = ctx.config[this.code]; + const basePath = [...input.path ?? ctx.path]; + if (relativePath) + basePath.push(...relativePath); + if (prefixPath) + basePath.unshift(...prefixPath); + this.path = new ReadonlyPath(...basePath); + this.data = "data" in input ? input.data : data; + } + transform(f) { + return new _ArkError(f({ + data: this.data, + path: this.path, + ...this.input + }), this.ctx); + } + hasCode(code) { + return this.code === code; + } + get propString() { + return stringifyPath(this.path); + } + get expected() { + if (this.input.expected) + return this.input.expected; + const config2 = this.meta?.expected ?? this.nodeConfig.expected; + return typeof config2 === "function" ? config2(this.input) : config2; + } + get actual() { + if (this.input.actual) + return this.input.actual; + const config2 = this.meta?.actual ?? this.nodeConfig.actual; + return typeof config2 === "function" ? config2(this.data) : config2; + } + get problem() { + if (this.input.problem) + return this.input.problem; + const config2 = this.meta?.problem ?? this.nodeConfig.problem; + return typeof config2 === "function" ? config2(this) : config2; + } + get message() { + if (this.input.message) + return this.input.message; + const config2 = this.meta?.message ?? this.nodeConfig.message; + return typeof config2 === "function" ? config2(this) : config2; + } + get flat() { + return this.hasCode("intersection") ? [...this.errors] : [this]; + } + toJSON() { + return { + data: this.data, + path: this.path, + ...this.input, + expected: this.expected, + actual: this.actual, + problem: this.problem, + message: this.message + }; + } + toString() { + return this.message; + } + throw() { + throw this; + } + }; + ArkErrors = class _ArkErrors extends ReadonlyArray2 { + [arkKind] = "errors"; + ctx; + constructor(ctx) { + super(); + this.ctx = ctx; + } + /** + * Errors by a pathString representing their location. + */ + byPath = /* @__PURE__ */ Object.create(null); + /** + * {@link byPath} flattened so that each value is an array of ArkError instances at that path. + * + * ✅ Since "intersection" errors will be flattened to their constituent `.errors`, + * they will never be directly present in this representation. + */ + get flatByPath() { + return flatMorph2(this.byPath, (k, v) => [k, v.flat]); + } + /** + * {@link byPath} flattened so that each value is an array of problem strings at that path. + */ + get flatProblemsByPath() { + return flatMorph2(this.byPath, (k, v) => [k, v.flat.map((e) => e.problem)]); + } + /** + * All pathStrings at which errors are present mapped to the errors occuring + * at that path or any nested path within it. + */ + byAncestorPath = /* @__PURE__ */ Object.create(null); + count = 0; + mutable = this; + /** + * Throw a TraversalError based on these errors. + */ + throw() { + throw this.toTraversalError(); + } + /** + * Converts ArkErrors to TraversalError, a subclass of `Error` suitable for throwing with nice + * formatting. + */ + toTraversalError() { + return new TraversalError(this); + } + /** + * Append an ArkError to this array, ignoring duplicates. + */ + add(error41) { + const existing = this.byPath[error41.propString]; + if (existing) { + if (error41 === existing) + return; + if (existing.hasCode("union") && existing.errors.length === 0) + return; + const errorIntersection = error41.hasCode("union") && error41.errors.length === 0 ? error41 : new ArkError({ + code: "intersection", + errors: existing.hasCode("intersection") ? [...existing.errors, error41] : [existing, error41] + }, this.ctx); + const existingIndex = this.indexOf(existing); + this.mutable[existingIndex === -1 ? this.length : existingIndex] = errorIntersection; + this.byPath[error41.propString] = errorIntersection; + this.addAncestorPaths(error41); + } else { + this.byPath[error41.propString] = error41; + this.addAncestorPaths(error41); + this.mutable.push(error41); + } + this.count++; + } + transform(f) { + const result = new _ArkErrors(this.ctx); + for (const e of this) + result.add(f(e)); + return result; + } + /** + * Add all errors from an ArkErrors instance, ignoring duplicates and + * prefixing their paths with that of the current Traversal. + */ + merge(errors) { + for (const e of errors) { + this.add(new ArkError({ ...e, path: [...this.ctx.path, ...e.path] }, this.ctx)); + } + } + /** + * @internal + */ + affectsPath(path3) { + if (this.length === 0) + return false; + return ( + // this would occur if there is an existing error at a prefix of path + // e.g. the path is ["foo", "bar"] and there is an error at ["foo"] + path3.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path + // e.g. the path is ["foo"] and there is an error at ["foo", "bar"] + path3.stringify() in this.byAncestorPath + ); + } + /** + * A human-readable summary of all errors. + */ + get summary() { + return this.toString(); + } + /** + * Alias of this ArkErrors instance for StandardSchema compatibility. + */ + get issues() { + return this; + } + toJSON() { + return [...this.map((e) => e.toJSON())]; + } + toString() { + return this.join("\n"); + } + addAncestorPaths(error41) { + for (const propString of error41.path.stringifyAncestors()) { + this.byAncestorPath[propString] = append2(this.byAncestorPath[propString], error41); + } + } + }; + TraversalError = class extends Error { + name = "TraversalError"; + constructor(errors) { + if (errors.length === 1) + super(errors.summary); + else + super("\n" + errors.map((error41) => ` \u2022 ${indent(error41)}`).join("\n")); + Object.defineProperty(this, "arkErrors", { + value: errors, + enumerable: false + }); + } + }; + indent = (error41) => error41.toString().split("\n").join("\n "); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/traversal.js +var Traversal, traverseKey; +var init_traversal = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/traversal.js"() { + init_out(); + init_errors2(); + init_utils(); + Traversal = class { + /** + * #### the path being validated or morphed + * + * ✅ array indices represented as numbers + * ⚠️ mutated during traversal - use `path.slice(0)` to snapshot + * 🔗 use {@link propString} for a stringified version + */ + path = []; + /** + * #### {@link ArkErrors} that will be part of this traversal's finalized result + * + * ✅ will always be an empty array for a valid traversal + */ + errors = new ArkErrors(this); + /** + * #### the original value being traversed + */ + root; + /** + * #### configuration for this traversal + * + * ✅ options can affect traversal results and error messages + * ✅ defaults < global config < scope config + * ✅ does not include options configured on individual types + */ + config; + queuedMorphs = []; + branches = []; + seen = {}; + constructor(root2, config2) { + this.root = root2; + this.config = config2; + } + /** + * #### the data being validated or morphed + * + * ✅ extracted from {@link root} at {@link path} + */ + get data() { + let result = this.root; + for (const segment of this.path) + result = result?.[segment]; + return result; + } + /** + * #### a string representing {@link path} + * + * @propString + */ + get propString() { + return stringifyPath(this.path); + } + /** + * #### add an {@link ArkError} and return `false` + * + * ✅ useful for predicates like `.narrow` + */ + reject(input) { + this.error(input); + return false; + } + /** + * #### add an {@link ArkError} from a description and return `false` + * + * ✅ useful for predicates like `.narrow` + * 🔗 equivalent to {@link reject}({ expected }) + */ + mustBe(expected) { + this.error(expected); + return false; + } + error(input) { + const errCtx = typeof input === "object" ? input.code ? input : { ...input, code: "predicate" } : { code: "predicate", expected: input }; + return this.errorFromContext(errCtx); + } + /** + * #### whether {@link currentBranch} (or the traversal root, outside a union) has one or more errors + */ + hasError() { + return this.currentErrorCount !== 0; + } + get currentBranch() { + return this.branches[this.branches.length - 1]; + } + queueMorphs(morphs) { + const input = { + path: new ReadonlyPath(...this.path), + morphs + }; + if (this.currentBranch) + this.currentBranch.queuedMorphs.push(input); + else + this.queuedMorphs.push(input); + } + finalize(onFail) { + if (this.queuedMorphs.length) { + if (typeof this.root === "object" && this.root !== null && this.config.clone) + this.root = this.config.clone(this.root); + this.applyQueuedMorphs(); + } + if (this.hasError()) + return onFail ? onFail(this.errors) : this.errors; + return this.root; + } + get currentErrorCount() { + return this.currentBranch ? this.currentBranch.error ? 1 : 0 : this.errors.count; + } + get failFast() { + return this.branches.length !== 0; + } + pushBranch() { + this.branches.push({ + error: void 0, + queuedMorphs: [] + }); + } + popBranch() { + return this.branches.pop(); + } + /** + * @internal + * Convenience for casting from InternalTraversal to Traversal + * for cases where the extra methods on the external type are expected, e.g. + * a morph or predicate. + */ + get external() { + return this; + } + errorFromNodeContext(input) { + return this.errorFromContext(input); + } + errorFromContext(errCtx) { + const error41 = new ArkError(errCtx, this); + if (this.currentBranch) + this.currentBranch.error = error41; + else + this.errors.add(error41); + return error41; + } + applyQueuedMorphs() { + while (this.queuedMorphs.length) { + const queuedMorphs = this.queuedMorphs; + this.queuedMorphs = []; + for (const { path: path3, morphs } of queuedMorphs) { + if (this.errors.affectsPath(path3)) + continue; + this.applyMorphsAtPath(path3, morphs); + } + } + } + applyMorphsAtPath(path3, morphs) { + const key = path3[path3.length - 1]; + let parent; + if (key !== void 0) { + parent = this.root; + for (let pathIndex = 0; pathIndex < path3.length - 1; pathIndex++) + parent = parent[path3[pathIndex]]; + } + for (const morph of morphs) { + this.path = [...path3]; + const morphIsNode = isNode(morph); + const result = morph(parent === void 0 ? this.root : parent[key], this); + if (result instanceof ArkError) { + if (!this.errors.includes(result)) + this.errors.add(result); + break; + } + if (result instanceof ArkErrors) { + if (!morphIsNode) { + this.errors.merge(result); + } + this.queuedMorphs = []; + break; + } + if (parent === void 0) + this.root = result; + else + parent[key] = result; + this.applyQueuedMorphs(); + } + } + }; + traverseKey = (key, fn2, ctx) => { + if (!ctx) + return fn2(); + ctx.path.push(key); + const result = fn2(); + ctx.path.pop(); + return result; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/node.js +var BaseNode, NodeSelector, writeSelectAssertionMessage, typePathToPropString, referenceMatcher, compileMeta, flatRef, flatRefsAreEqual, appendUniqueFlatRefs, appendUniqueNodes; +var init_node = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/node.js"() { + init_out(); + init_implement(); + init_registry2(); + init_traversal(); + init_utils(); + BaseNode = class extends Callable { + attachments; + $; + onFail; + includesTransform; + includesContextualPredicate; + isCyclic; + allowsRequiresContext; + rootApplyStrategy; + contextFreeMorph; + rootApply; + referencesById; + shallowReferences; + flatRefs; + flatMorphs; + allows; + get shallowMorphs() { + return []; + } + constructor(attachments, $2) { + super((data, pipedFromCtx, onFail = this.onFail) => { + if (pipedFromCtx) { + this.traverseApply(data, pipedFromCtx); + return pipedFromCtx.hasError() ? pipedFromCtx.errors : pipedFromCtx.data; + } + return this.rootApply(data, onFail); + }, { attach: attachments }); + this.attachments = attachments; + this.$ = $2; + this.onFail = this.meta.onFail ?? this.$.resolvedConfig.onFail; + this.includesTransform = this.hasKind("morph") || this.hasKind("structure") && this.structuralMorph !== void 0 || this.hasKind("sequence") && this.inner.defaultables !== void 0; + this.includesContextualPredicate = this.hasKind("predicate") && this.inner.predicate.length !== 1; + this.isCyclic = this.kind === "alias"; + this.referencesById = { [this.id]: this }; + this.shallowReferences = this.hasKind("structure") ? [this, ...this.children] : this.children.reduce((acc, child) => appendUniqueNodes(acc, child.shallowReferences), [this]); + const isStructural = this.isStructural(); + this.flatRefs = []; + this.flatMorphs = []; + for (let i = 0; i < this.children.length; i++) { + this.includesTransform ||= this.children[i].includesTransform; + this.includesContextualPredicate ||= this.children[i].includesContextualPredicate; + this.isCyclic ||= this.children[i].isCyclic; + if (!isStructural) { + const childFlatRefs = this.children[i].flatRefs; + for (let j = 0; j < childFlatRefs.length; j++) { + const childRef = childFlatRefs[j]; + if (!this.flatRefs.some((existing) => flatRefsAreEqual(existing, childRef))) { + this.flatRefs.push(childRef); + for (const branch of childRef.node.branches) { + if (branch.hasKind("morph") || branch.hasKind("intersection") && branch.structure?.structuralMorph !== void 0) { + this.flatMorphs.push({ + path: childRef.path, + propString: childRef.propString, + node: branch + }); + } + } + } + } + } + Object.assign(this.referencesById, this.children[i].referencesById); + } + this.flatRefs.sort((l, r) => l.path.length > r.path.length ? 1 : l.path.length < r.path.length ? -1 : l.propString > r.propString ? 1 : l.propString < r.propString ? -1 : l.node.expression < r.node.expression ? -1 : 1); + this.allowsRequiresContext = this.includesContextualPredicate || this.isCyclic; + this.rootApplyStrategy = !this.allowsRequiresContext && this.flatMorphs.length === 0 ? this.shallowMorphs.length === 0 ? "allows" : this.shallowMorphs.every((morph) => morph.length === 1 || morph.name === "$arkStructuralMorph") ? this.hasKind("union") ? ( + // multiple morphs not yet supported for optimistic compilation + this.branches.some((branch) => branch.shallowMorphs.length > 1) ? "contextual" : "branchedOptimistic" + ) : this.shallowMorphs.length > 1 ? "contextual" : "optimistic" : "contextual" : "contextual"; + this.rootApply = this.createRootApply(); + this.allows = this.allowsRequiresContext ? (data) => this.traverseAllows(data, new Traversal(data, this.$.resolvedConfig)) : (data) => this.traverseAllows(data); + } + createRootApply() { + switch (this.rootApplyStrategy) { + case "allows": + return (data, onFail) => { + if (this.allows(data)) + return data; + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + case "contextual": + return (data, onFail) => { + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + case "optimistic": + this.contextFreeMorph = this.shallowMorphs[0]; + const clone2 = this.$.resolvedConfig.clone; + return (data, onFail) => { + if (this.allows(data)) { + return this.contextFreeMorph(clone2 && (typeof data === "object" && data !== null || typeof data === "function") ? clone2(data) : data); + } + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + case "branchedOptimistic": + return this.createBranchedOptimisticRootApply(); + default: + this.rootApplyStrategy; + return throwInternalError2(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`); + } + } + compiledMeta = compileMeta(this.metaJson); + cacheGetter(name, value2) { + Object.defineProperty(this, name, { value: value2 }); + return value2; + } + get description() { + return this.cacheGetter("description", this.meta?.description ?? this.$.resolvedConfig[this.kind].description(this)); + } + // we don't cache this currently since it can be updated once a scope finishes + // resolving cyclic references, although it may be possible to ensure it is cached safely + get references() { + return Object.values(this.referencesById); + } + precedence = precedenceOfKind(this.kind); + precompilation; + // defined as an arrow function since it is often detached, e.g. when passing to tRPC + // otherwise, would run into issues with this binding + assert = (data, pipedFromCtx) => this(data, pipedFromCtx, (errors) => errors.throw()); + traverse(data, pipedFromCtx) { + return this(data, pipedFromCtx, null); + } + /** rawIn should be used internally instead */ + get in() { + return this.cacheGetter("in", this.rawIn.isRoot() ? this.$.finalize(this.rawIn) : this.rawIn); + } + get rawIn() { + return this.cacheGetter("rawIn", this.getIo("in")); + } + /** rawOut should be used internally instead */ + get out() { + return this.cacheGetter("out", this.rawOut.isRoot() ? this.$.finalize(this.rawOut) : this.rawOut); + } + get rawOut() { + return this.cacheGetter("rawOut", this.getIo("out")); + } + // Should be refactored to use transform + // https://github.com/arktypeio/arktype/issues/1020 + getIo(ioKind) { + if (!this.includesTransform) + return this; + const ioInner = {}; + for (const [k, v] of this.innerEntries) { + const keySchemaImplementation = this.impl.keys[k]; + if (keySchemaImplementation.reduceIo) + keySchemaImplementation.reduceIo(ioKind, ioInner, v); + else if (keySchemaImplementation.child) { + const childValue = v; + ioInner[k] = isArray(childValue) ? childValue.map((child) => ioKind === "in" ? child.rawIn : child.rawOut) : ioKind === "in" ? childValue.rawIn : childValue.rawOut; + } else + ioInner[k] = v; + } + return this.$.node(this.kind, ioInner); + } + toJSON() { + return this.json; + } + toString() { + return `Type<${this.expression}>`; + } + equals(r) { + const rNode = isNode(r) ? r : this.$.parseDefinition(r); + return this.innerHash === rNode.innerHash; + } + ifEquals(r) { + return this.equals(r) ? this : void 0; + } + hasKind(kind) { + return this.kind === kind; + } + assertHasKind(kind) { + if (this.kind !== kind) + throwError(`${this.kind} node was not of asserted kind ${kind}`); + return this; + } + hasKindIn(...kinds) { + return kinds.includes(this.kind); + } + assertHasKindIn(...kinds) { + if (!includes(kinds, this.kind)) + throwError(`${this.kind} node was not one of asserted kinds ${kinds}`); + return this; + } + isBasis() { + return includes(basisKinds, this.kind); + } + isConstraint() { + return includes(constraintKinds, this.kind); + } + isStructural() { + return includes(structuralKinds, this.kind); + } + isRefinement() { + return includes(refinementKinds, this.kind); + } + isRoot() { + return includes(rootKinds, this.kind); + } + isUnknown() { + return this.hasKind("intersection") && this.children.length === 0; + } + isNever() { + return this.hasKind("union") && this.children.length === 0; + } + hasUnit(value2) { + return this.hasKind("unit") && this.allows(value2); + } + hasOpenIntersection() { + return this.impl.intersectionIsOpen; + } + get nestableExpression() { + return this.expression; + } + select(selector) { + const normalized = NodeSelector.normalize(selector); + return this._select(normalized); + } + _select(selector) { + let nodes = NodeSelector.applyBoundary[selector.boundary ?? "references"](this); + if (selector.kind) + nodes = nodes.filter((n) => n.kind === selector.kind); + if (selector.where) + nodes = nodes.filter(selector.where); + return NodeSelector.applyMethod[selector.method ?? "filter"](nodes, this, selector); + } + transform(mapper, opts) { + return this._transform(mapper, this._createTransformContext(opts)); + } + _createTransformContext(opts) { + return { + root: this, + selected: void 0, + seen: {}, + path: [], + parseOptions: { + prereduced: opts?.prereduced ?? false + }, + undeclaredKeyHandling: void 0, + ...opts + }; + } + _transform(mapper, ctx) { + const $2 = ctx.bindScope ?? this.$; + if (ctx.seen[this.id]) + return this.$.lazilyResolve(ctx.seen[this.id]); + if (ctx.shouldTransform?.(this, ctx) === false) + return this; + let transformedNode; + ctx.seen[this.id] = () => transformedNode; + if (this.hasKind("structure") && this.undeclared !== ctx.undeclaredKeyHandling) { + ctx = { + ...ctx, + undeclaredKeyHandling: this.undeclared + }; + } + const innerWithTransformedChildren = flatMorph2(this.inner, (k, v) => { + if (!this.impl.keys[k].child) + return [k, v]; + const children = v; + if (!isArray(children)) { + const transformed2 = children._transform(mapper, ctx); + return transformed2 ? [k, transformed2] : []; + } + if (children.length === 0) + return [k, v]; + const transformed = children.flatMap((n) => { + const transformedChild = n._transform(mapper, ctx); + return transformedChild ?? []; + }); + return transformed.length ? [k, transformed] : []; + }); + delete ctx.seen[this.id]; + const innerWithMeta = Object.assign(innerWithTransformedChildren, { + meta: this.meta + }); + const transformedInner = ctx.selected && !ctx.selected.includes(this) ? innerWithMeta : mapper(this.kind, innerWithMeta, ctx); + if (transformedInner === null) + return null; + if (isNode(transformedInner)) + return transformedNode = transformedInner; + const transformedKeys = Object.keys(transformedInner); + const hasNoTypedKeys = transformedKeys.length === 0 || transformedKeys.length === 1 && transformedKeys[0] === "meta"; + if (hasNoTypedKeys && // if inner was previously an empty object (e.g. unknown) ensure it is not pruned + !isEmptyObject2(this.inner)) + return null; + if ((this.kind === "required" || this.kind === "optional" || this.kind === "index") && !("value" in transformedInner)) { + return ctx.undeclaredKeyHandling ? { ...transformedInner, value: $ark.intrinsic.unknown } : null; + } + if (this.kind === "morph") { + ; + transformedInner.in ??= $ark.intrinsic.unknown; + } + return transformedNode = $2.node(this.kind, transformedInner, ctx.parseOptions); + } + configureReferences(meta, selector = "references") { + const normalized = NodeSelector.normalize(selector); + const mapper = typeof meta === "string" ? (kind, inner) => ({ + ...inner, + meta: { ...inner.meta, description: meta } + }) : typeof meta === "function" ? (kind, inner) => ({ ...inner, meta: meta(inner.meta) }) : (kind, inner) => ({ + ...inner, + meta: { ...inner.meta, ...meta } + }); + if (normalized.boundary === "self") { + return this.$.node(this.kind, mapper(this.kind, { ...this.inner, meta: this.meta })); + } + const rawSelected = this._select(normalized); + const selected = rawSelected && liftArray(rawSelected); + const shouldTransform = normalized.boundary === "child" ? (node2, ctx) => ctx.root.children.includes(node2) : normalized.boundary === "shallow" ? (node2) => node2.kind !== "structure" : () => true; + return this.$.finalize(this.transform(mapper, { + shouldTransform, + selected + })); + } + }; + NodeSelector = { + applyBoundary: { + self: (node2) => [node2], + child: (node2) => [...node2.children], + shallow: (node2) => [...node2.shallowReferences], + references: (node2) => [...node2.references] + }, + applyMethod: { + filter: (nodes) => nodes, + assertFilter: (nodes, from, selector) => { + if (nodes.length === 0) + throwError(writeSelectAssertionMessage(from, selector)); + return nodes; + }, + find: (nodes) => nodes[0], + assertFind: (nodes, from, selector) => { + if (nodes.length === 0) + throwError(writeSelectAssertionMessage(from, selector)); + return nodes[0]; + } + }, + normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf2(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector } + }; + writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable2(selector)}.`; + typePathToPropString = (path3) => stringifyPath(path3, { + stringifyNonKey: (node2) => node2.expression + }); + referenceMatcher = /"(\$ark\.[^"]+)"/g; + compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, "$1"); + flatRef = (path3, node2) => ({ + path: path3, + node: node2, + propString: typePathToPropString(path3) + }); + flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node); + appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, { + isEqual: flatRefsAreEqual + }); + appendUniqueNodes = (existing, refs) => appendUnique(existing, refs, { + isEqual: (l, r) => l.equals(r) + }); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/disjoint.js +var Disjoint, describeReasons, describeReason, writeUnsatisfiableExpressionError; +var init_disjoint = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/disjoint.js"() { + init_out(); + init_registry2(); + init_utils(); + Disjoint = class _Disjoint extends Array { + static init(kind, l, r, ctx) { + return new _Disjoint({ + kind, + l, + r, + path: ctx?.path ?? [], + optional: ctx?.optional ?? false + }); + } + add(kind, l, r, ctx) { + this.push({ + kind, + l, + r, + path: ctx?.path ?? [], + optional: ctx?.optional ?? false + }); + return this; + } + get summary() { + return this.describeReasons(); + } + describeReasons() { + if (this.length === 1) { + const { path: path3, l, r } = this[0]; + const pathString = stringifyPath(path3); + return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`); + } + return `The following intersections result in unsatisfiable types: +\u2022 ${this.map(({ path: path3, l, r }) => `${path3}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`; + } + throw() { + return throwParseError2(this.describeReasons()); + } + invert() { + const result = this.map((entry) => ({ + ...entry, + l: entry.r, + r: entry.l + })); + if (!(result instanceof _Disjoint)) + return new _Disjoint(...result); + return result; + } + withPrefixKey(key, kind) { + return this.map((entry) => ({ + ...entry, + path: [key, ...entry.path], + optional: entry.optional || kind === "optional" + })); + } + toNeverIfDisjoint() { + return $ark.intrinsic.never; + } + }; + describeReasons = (l, r) => `${describeReason(l)} and ${describeReason(r)}`; + describeReason = (value2) => isNode(value2) ? value2.expression : isArray(value2) ? value2.map(describeReason).join(" | ") || "never" : String(value2); + writeUnsatisfiableExpressionError = (expression) => `${expression} results in an unsatisfiable type`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/intersections.js +var intersectionCache, intersectNodesRoot, pipeNodesRoot, intersectOrPipeNodes, _intersectNodes, _pipeNodes, pipeMorphed, _pipeMorphed; +var init_intersections2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/intersections.js"() { + init_disjoint(); + init_implement(); + init_utils(); + intersectionCache = {}; + intersectNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { + $: $2, + invert: false, + pipe: false + }); + pipeNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { + $: $2, + invert: false, + pipe: true + }); + intersectOrPipeNodes = ((l, r, ctx) => { + const operator = ctx.pipe ? "|>" : "&"; + const lrCacheKey = `${l.hash}${operator}${r.hash}`; + if (intersectionCache[lrCacheKey] !== void 0) + return intersectionCache[lrCacheKey]; + if (!ctx.pipe) { + const rlCacheKey = `${r.hash}${operator}${l.hash}`; + if (intersectionCache[rlCacheKey] !== void 0) { + const rlResult = intersectionCache[rlCacheKey]; + const lrResult = rlResult instanceof Disjoint ? rlResult.invert() : rlResult; + intersectionCache[lrCacheKey] = lrResult; + return lrResult; + } + } + const isPureIntersection = !ctx.pipe || !l.includesTransform && !r.includesTransform; + if (isPureIntersection && l.equals(r)) + return l; + let result = isPureIntersection ? _intersectNodes(l, r, ctx) : l.hasKindIn(...rootKinds) ? ( + // if l is a RootNode, r will be as well + _pipeNodes(l, r, ctx) + ) : _intersectNodes(l, r, ctx); + if (isNode(result)) { + if (l.equals(result)) + result = l; + else if (r.equals(result)) + result = r; + } + intersectionCache[lrCacheKey] = result; + return result; + }); + _intersectNodes = (l, r, ctx) => { + const leftmostKind = l.precedence < r.precedence ? l.kind : r.kind; + const implementation23 = l.impl.intersections[r.kind] ?? r.impl.intersections[l.kind]; + if (implementation23 === void 0) { + return null; + } else if (leftmostKind === l.kind) + return implementation23(l, r, ctx); + else { + let result = implementation23(r, l, { ...ctx, invert: !ctx.invert }); + if (result instanceof Disjoint) + result = result.invert(); + return result; + } + }; + _pipeNodes = (l, r, ctx) => l.includesTransform || r.includesTransform ? ctx.invert ? pipeMorphed(r, l, ctx) : pipeMorphed(l, r, ctx) : _intersectNodes(l, r, ctx); + pipeMorphed = (from, to, ctx) => from.distribute((fromBranch) => _pipeMorphed(fromBranch, to, ctx), (results) => { + const viableBranches = results.filter(isNode); + if (viableBranches.length === 0) + return Disjoint.init("union", from.branches, to.branches); + if (viableBranches.length < from.branches.length || !from.branches.every((branch, i) => branch.rawIn.equals(viableBranches[i].rawIn))) + return ctx.$.parseSchema(viableBranches); + let meta; + if (viableBranches.length === 1) { + const onlyBranch = viableBranches[0]; + if (!meta) + return onlyBranch; + return ctx.$.node("morph", { + ...onlyBranch.inner, + in: onlyBranch.rawIn.configure(meta, "self") + }); + } + const schema2 = { + branches: viableBranches + }; + if (meta) + schema2.meta = meta; + return ctx.$.parseSchema(schema2); + }); + _pipeMorphed = (from, to, ctx) => { + const fromIsMorph = from.hasKind("morph"); + if (fromIsMorph) { + const morphs = [...from.morphs]; + if (from.lastMorphIfNode) { + const outIntersection = intersectOrPipeNodes(from.lastMorphIfNode, to, ctx); + if (outIntersection instanceof Disjoint) + return outIntersection; + morphs[morphs.length - 1] = outIntersection; + } else + morphs.push(to); + return ctx.$.node("morph", { + morphs, + in: from.inner.in + }); + } + if (to.hasKind("morph")) { + const inTersection = intersectOrPipeNodes(from, to.rawIn, ctx); + if (inTersection instanceof Disjoint) + return inTersection; + return ctx.$.node("morph", { + morphs: [to], + in: inTersection + }); + } + return ctx.$.node("morph", { + morphs: [to], + in: from + }); + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/constraint.js +var BaseConstraint, InternalPrimitiveConstraint, constraintKeyParser, intersectConstraints, flattenConstraints, unflattenConstraints, throwInvalidOperandError, writeInvalidOperandMessage; +var init_constraint = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/constraint.js"() { + init_out(); + init_node(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_utils(); + BaseConstraint = class extends BaseNode { + constructor(attachments, $2) { + super(attachments, $2); + Object.defineProperty(this, arkKind, { + value: "constraint", + enumerable: false + }); + } + impliedSiblings; + intersect(r) { + return intersectNodesRoot(this, r, this.$); + } + }; + InternalPrimitiveConstraint = class extends BaseConstraint { + traverseApply = (data, ctx) => { + if (!this.traverseAllows(data, ctx)) + ctx.errorFromNodeContext(this.errorContext); + }; + compile(js) { + if (js.traversalKind === "Allows") + js.return(this.compiledCondition); + else { + js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); + } + } + get errorContext() { + return { + code: this.kind, + description: this.description, + meta: this.meta, + ...this.inner + }; + } + get compiledErrorContext() { + return compileObjectLiteral(this.errorContext); + } + }; + constraintKeyParser = (kind) => (schema2, ctx) => { + if (isArray(schema2)) { + if (schema2.length === 0) { + return; + } + const nodes = schema2.map((schema3) => ctx.$.node(kind, schema3)); + if (kind === "predicate") + return nodes; + return nodes.sort((l, r) => l.hash < r.hash ? -1 : 1); + } + const child = ctx.$.node(kind, schema2); + return child.hasOpenIntersection() ? [child] : child; + }; + intersectConstraints = (s) => { + const head = s.r.shift(); + if (!head) { + let result = s.l.length === 0 && s.kind === "structure" ? $ark.intrinsic.unknown.internal : s.ctx.$.node(s.kind, Object.assign(s.baseInner, unflattenConstraints(s.l)), { prereduced: true }); + for (const root2 of s.roots) { + if (result instanceof Disjoint) + return result; + result = intersectOrPipeNodes(root2, result, s.ctx); + } + return result; + } + let matched = false; + for (let i = 0; i < s.l.length; i++) { + const result = intersectOrPipeNodes(s.l[i], head, s.ctx); + if (result === null) + continue; + if (result instanceof Disjoint) + return result; + if (result.isRoot()) { + s.roots.push(result); + s.l.splice(i); + return intersectConstraints(s); + } + if (!matched) { + s.l[i] = result; + matched = true; + } else if (!s.l.includes(result)) { + return throwInternalError2(`Unexpectedly encountered multiple distinct intersection results for refinement ${head}`); + } + } + if (!matched) + s.l.push(head); + if (s.kind === "intersection") { + if (head.impliedSiblings) + for (const node2 of head.impliedSiblings) + appendUnique(s.r, node2); + } + return intersectConstraints(s); + }; + flattenConstraints = (inner) => { + const result = Object.entries(inner).flatMap(([k, v]) => k in constraintKeys ? v : []).sort((l, r) => l.precedence < r.precedence ? -1 : l.precedence > r.precedence ? 1 : l.kind === "predicate" && r.kind === "predicate" ? 0 : l.hash < r.hash ? -1 : 1); + return result; + }; + unflattenConstraints = (constraints) => { + const inner = {}; + for (const constraint of constraints) { + if (constraint.hasOpenIntersection()) { + inner[constraint.kind] = append2(inner[constraint.kind], constraint); + } else { + if (inner[constraint.kind]) { + return throwInternalError2(`Unexpected intersection of closed refinements of kind ${constraint.kind}`); + } + inner[constraint.kind] = constraint; + } + } + return inner; + }; + throwInvalidOperandError = (...args3) => throwParseError2(writeInvalidOperandMessage(...args3)); + writeInvalidOperandMessage = (kind, expected, actual) => { + const actualDescription = actual.hasKind("morph") ? "a morph" : actual.isUnknown() ? "unknown" : actual.exclude(expected).defaultShortDescription; + return `${capitalize(kind)} operand must be ${expected.description} (was ${actualDescription})`; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/generic.js +var parseGeneric, LazyGenericBody, GenericRoot, writeUnsatisfiedParameterConstraintMessage; +var init_generic = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/generic.js"() { + init_out(); + init_registry2(); + init_utils(); + parseGeneric = (paramDefs, bodyDef, $2) => new GenericRoot(paramDefs, bodyDef, $2, $2, null); + LazyGenericBody = class extends Callable { + }; + GenericRoot = class extends Callable { + [arkKind] = "generic"; + paramDefs; + bodyDef; + $; + arg$; + baseInstantiation; + hkt; + description; + constructor(paramDefs, bodyDef, $2, arg$, hkt) { + super((...args3) => { + const argNodes = flatMorph2(this.names, (i, name) => { + const arg = this.arg$.parse(args3[i]); + if (!arg.extends(this.constraints[i])) { + throwParseError2(writeUnsatisfiedParameterConstraintMessage(name, this.constraints[i].expression, arg.expression)); + } + return [name, arg]; + }); + if (this.defIsLazy()) { + const def = this.bodyDef(argNodes); + return this.$.parse(def); + } + return this.$.parse(bodyDef, { args: argNodes }); + }); + this.paramDefs = paramDefs; + this.bodyDef = bodyDef; + this.$ = $2; + this.arg$ = arg$; + this.hkt = hkt; + this.description = hkt ? new hkt().description ?? `a generic type for ${hkt.constructor.name}` : "a generic type"; + this.baseInstantiation = this(...this.constraints); + } + defIsLazy() { + return this.bodyDef instanceof LazyGenericBody; + } + cacheGetter(name, value2) { + Object.defineProperty(this, name, { value: value2 }); + return value2; + } + get json() { + return this.cacheGetter("json", { + params: this.params.map((param) => param[1].isUnknown() ? param[0] : [param[0], param[1].json]), + body: snapshot(this.bodyDef) + }); + } + get params() { + return this.cacheGetter("params", this.paramDefs.map((param) => typeof param === "string" ? [param, $ark.intrinsic.unknown] : [param[0], this.$.parse(param[1])])); + } + get names() { + return this.cacheGetter("names", this.params.map((e) => e[0])); + } + get constraints() { + return this.cacheGetter("constraints", this.params.map((e) => e[1])); + } + get internal() { + return this; + } + get referencesById() { + return this.baseInstantiation.internal.referencesById; + } + get references() { + return this.baseInstantiation.internal.references; + } + }; + writeUnsatisfiedParameterConstraintMessage = (name, constraint, arg) => `${name} must be assignable to ${constraint} (was ${arg})`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/predicate.js +var implementation, PredicateNode, Predicate; +var init_predicate = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/predicate.js"() { + init_constraint(); + init_implement(); + init_registry2(); + implementation = implementNode({ + kind: "predicate", + hasAssociatedError: true, + collapsibleKey: "predicate", + keys: { + predicate: {} + }, + normalize: (schema2) => typeof schema2 === "function" ? { predicate: schema2 } : schema2, + defaults: { + description: (node2) => `valid according to ${node2.predicate.name || "an anonymous predicate"}` + }, + intersectionIsOpen: true, + intersections: { + // as long as the narrows in l and r are individually safe to check + // in the order they're specified, checking them in the order + // resulting from this intersection should also be safe. + predicate: () => null + } + }); + PredicateNode = class extends BaseConstraint { + serializedPredicate = registeredReference(this.predicate); + compiledCondition = `${this.serializedPredicate}(data, ctx)`; + compiledNegation = `!${this.compiledCondition}`; + impliedBasis = null; + expression = this.serializedPredicate; + traverseAllows = this.predicate; + errorContext = { + code: "predicate", + description: this.description, + meta: this.meta + }; + compiledErrorContext = compileObjectLiteral(this.errorContext); + traverseApply = (data, ctx) => { + const errorCount = ctx.currentErrorCount; + if (!this.predicate(data, ctx.external) && ctx.currentErrorCount === errorCount) + ctx.errorFromNodeContext(this.errorContext); + }; + compile(js) { + if (js.traversalKind === "Allows") { + js.return(this.compiledCondition); + return; + } + js.initializeErrorCount(); + js.if( + // only add the default error if the predicate didn't add one itself + `${this.compiledNegation} && ctx.currentErrorCount === errorCount`, + () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) + ); + } + reduceJsonSchema(base, ctx) { + return ctx.fallback.predicate({ + code: "predicate", + base, + predicate: this.predicate + }); + } + }; + Predicate = { + implementation, + Node: PredicateNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/divisor.js +var implementation2, DivisorNode, Divisor, writeNonIntegerDivisorMessage, greatestCommonDivisor; +var init_divisor = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/divisor.js"() { + init_out(); + init_constraint(); + init_implement(); + init_registry2(); + implementation2 = implementNode({ + kind: "divisor", + collapsibleKey: "rule", + keys: { + rule: { + parse: (divisor) => Number.isInteger(divisor) ? divisor : throwParseError2(writeNonIntegerDivisorMessage(divisor)) + } + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + hasAssociatedError: true, + defaults: { + description: (node2) => node2.rule === 1 ? "an integer" : node2.rule === 2 ? "even" : `a multiple of ${node2.rule}` + }, + intersections: { + divisor: (l, r, ctx) => ctx.$.node("divisor", { + rule: Math.abs(l.rule * r.rule / greatestCommonDivisor(l.rule, r.rule)) + }) + }, + obviatesBasisDescription: true + }); + DivisorNode = class extends InternalPrimitiveConstraint { + traverseAllows = (data) => data % this.rule === 0; + compiledCondition = `data % ${this.rule} === 0`; + compiledNegation = `data % ${this.rule} !== 0`; + impliedBasis = $ark.intrinsic.number.internal; + expression = `% ${this.rule}`; + reduceJsonSchema(schema2) { + schema2.type = "integer"; + if (this.rule === 1) + return schema2; + schema2.multipleOf = this.rule; + return schema2; + } + }; + Divisor = { + implementation: implementation2, + Node: DivisorNode + }; + writeNonIntegerDivisorMessage = (divisor) => `divisor must be an integer (was ${divisor})`; + greatestCommonDivisor = (l, r) => { + let previous; + let greatestCommonDivisor2 = l; + let current = r; + while (current !== 0) { + previous = current; + current = greatestCommonDivisor2 % current; + greatestCommonDivisor2 = previous; + } + return greatestCommonDivisor2; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/range.js +var BaseRange, negatedComparators, boundKindPairsByLower, parseExclusiveKey, createLengthSchemaNormalizer, createDateSchemaNormalizer, parseDateLimit, writeInvalidLengthBoundMessage, createLengthRuleParser, operandKindsByBoundKind, compileComparator, dateLimitToString, writeUnboundableMessage; +var init_range = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/range.js"() { + init_out(); + init_constraint(); + BaseRange = class extends InternalPrimitiveConstraint { + boundOperandKind = operandKindsByBoundKind[this.kind]; + compiledActual = this.boundOperandKind === "value" ? `data` : this.boundOperandKind === "length" ? `data.length` : `data.valueOf()`; + comparator = compileComparator(this.kind, this.exclusive); + numericLimit = this.rule.valueOf(); + expression = `${this.comparator} ${this.rule}`; + compiledCondition = `${this.compiledActual} ${this.comparator} ${this.numericLimit}`; + compiledNegation = `${this.compiledActual} ${negatedComparators[this.comparator]} ${this.numericLimit}`; + // we need to compute stringLimit before errorContext, which references it + // transitively through description for date bounds + stringLimit = this.boundOperandKind === "date" ? dateLimitToString(this.numericLimit) : `${this.numericLimit}`; + limitKind = this.comparator["0"] === "<" ? "upper" : "lower"; + isStricterThan(r) { + const thisLimitIsStricter = this.limitKind === "upper" ? this.numericLimit < r.numericLimit : this.numericLimit > r.numericLimit; + return thisLimitIsStricter || this.numericLimit === r.numericLimit && this.exclusive === true && !r.exclusive; + } + overlapsRange(r) { + if (this.isStricterThan(r)) + return false; + if (this.numericLimit === r.numericLimit && (this.exclusive || r.exclusive)) + return false; + return true; + } + overlapIsUnit(r) { + return this.numericLimit === r.numericLimit && !this.exclusive && !r.exclusive; + } + }; + negatedComparators = { + "<": ">=", + "<=": ">", + ">": "<=", + ">=": "<" + }; + boundKindPairsByLower = { + min: "max", + minLength: "maxLength", + after: "before" + }; + parseExclusiveKey = { + // omit key with value false since it is the default + parse: (flag) => flag || void 0 + }; + createLengthSchemaNormalizer = (kind) => (schema2) => { + if (typeof schema2 === "number") + return { rule: schema2 }; + const { exclusive, ...normalized } = schema2; + return exclusive ? { + ...normalized, + rule: kind === "minLength" ? normalized.rule + 1 : normalized.rule - 1 + } : normalized; + }; + createDateSchemaNormalizer = (kind) => (schema2) => { + if (typeof schema2 === "number" || typeof schema2 === "string" || schema2 instanceof Date) + return { rule: schema2 }; + const { exclusive, ...normalized } = schema2; + if (!exclusive) + return normalized; + const numericLimit = typeof normalized.rule === "number" ? normalized.rule : typeof normalized.rule === "string" ? new Date(normalized.rule).valueOf() : normalized.rule.valueOf(); + return exclusive ? { + ...normalized, + rule: kind === "after" ? numericLimit + 1 : numericLimit - 1 + } : normalized; + }; + parseDateLimit = (limit) => typeof limit === "string" || typeof limit === "number" ? new Date(limit) : limit; + writeInvalidLengthBoundMessage = (kind, limit) => `${kind} bound must be a positive integer (was ${limit})`; + createLengthRuleParser = (kind) => (limit) => { + if (!Number.isInteger(limit) || limit < 0) + throwParseError2(writeInvalidLengthBoundMessage(kind, limit)); + return limit; + }; + operandKindsByBoundKind = { + min: "value", + max: "value", + minLength: "length", + maxLength: "length", + after: "date", + before: "date" + }; + compileComparator = (kind, exclusive) => `${isKeyOf2(kind, boundKindPairsByLower) ? ">" : "<"}${exclusive ? "" : "="}`; + dateLimitToString = (limit) => typeof limit === "string" ? limit : new Date(limit).toLocaleString(); + writeUnboundableMessage = (root2) => `Bounded expression ${root2} must be exactly one of number, string, Array, or Date`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/after.js +var implementation3, AfterNode, After; +var init_after = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/after.js"() { + init_out(); + init_implement(); + init_registry2(); + init_range(); + implementation3 = implementNode({ + kind: "after", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: parseDateLimit, + serialize: (schema2) => schema2.toISOString() + } + }, + normalize: createDateSchemaNormalizer("after"), + defaults: { + description: (node2) => `${node2.collapsibleLimitString} or later`, + actual: describeCollapsibleDate + }, + intersections: { + after: (l, r) => l.isStricterThan(r) ? l : r + } + }); + AfterNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.Date.internal; + collapsibleLimitString = describeCollapsibleDate(this.rule); + traverseAllows = (data) => data >= this.rule; + reduceJsonSchema(base, ctx) { + return ctx.fallback.date({ code: "date", base, after: this.rule }); + } + }; + After = { + implementation: implementation3, + Node: AfterNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/before.js +var implementation4, BeforeNode, Before; +var init_before = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/before.js"() { + init_out(); + init_disjoint(); + init_implement(); + init_registry2(); + init_range(); + implementation4 = implementNode({ + kind: "before", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: parseDateLimit, + serialize: (schema2) => schema2.toISOString() + } + }, + normalize: createDateSchemaNormalizer("before"), + defaults: { + description: (node2) => `${node2.collapsibleLimitString} or earlier`, + actual: describeCollapsibleDate + }, + intersections: { + before: (l, r) => l.isStricterThan(r) ? l : r, + after: (before, after, ctx) => before.overlapsRange(after) ? before.overlapIsUnit(after) ? ctx.$.node("unit", { unit: before.rule }) : null : Disjoint.init("range", before, after) + } + }); + BeforeNode = class extends BaseRange { + collapsibleLimitString = describeCollapsibleDate(this.rule); + traverseAllows = (data) => data <= this.rule; + impliedBasis = $ark.intrinsic.Date.internal; + reduceJsonSchema(base, ctx) { + return ctx.fallback.date({ code: "date", base, before: this.rule }); + } + }; + Before = { + implementation: implementation4, + Node: BeforeNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/exactLength.js +var implementation5, ExactLengthNode, ExactLength; +var init_exactLength = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/exactLength.js"() { + init_constraint(); + init_disjoint(); + init_implement(); + init_registry2(); + init_toJsonSchema(); + init_range(); + implementation5 = implementNode({ + kind: "exactLength", + collapsibleKey: "rule", + keys: { + rule: { + parse: createLengthRuleParser("exactLength") + } + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + hasAssociatedError: true, + defaults: { + description: (node2) => `exactly length ${node2.rule}`, + actual: (data) => `${data.length}` + }, + intersections: { + exactLength: (l, r, ctx) => Disjoint.init("unit", ctx.$.node("unit", { unit: l.rule }), ctx.$.node("unit", { unit: r.rule }), { path: ["length"] }), + minLength: (exactLength, minLength) => exactLength.rule >= minLength.rule ? exactLength : Disjoint.init("range", exactLength, minLength), + maxLength: (exactLength, maxLength) => exactLength.rule <= maxLength.rule ? exactLength : Disjoint.init("range", exactLength, maxLength) + } + }); + ExactLengthNode = class extends InternalPrimitiveConstraint { + traverseAllows = (data) => data.length === this.rule; + compiledCondition = `data.length === ${this.rule}`; + compiledNegation = `data.length !== ${this.rule}`; + impliedBasis = $ark.intrinsic.lengthBoundable.internal; + expression = `== ${this.rule}`; + reduceJsonSchema(schema2) { + switch (schema2.type) { + case "string": + schema2.minLength = this.rule; + schema2.maxLength = this.rule; + return schema2; + case "array": + schema2.minItems = this.rule; + schema2.maxItems = this.rule; + return schema2; + default: + return ToJsonSchema.throwInternalOperandError("exactLength", schema2); + } + } + }; + ExactLength = { + implementation: implementation5, + Node: ExactLengthNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/max.js +var implementation6, MaxNode, Max; +var init_max = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/max.js"() { + init_disjoint(); + init_implement(); + init_registry2(); + init_range(); + implementation6 = implementNode({ + kind: "max", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: {}, + exclusive: parseExclusiveKey + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + defaults: { + description: (node2) => { + if (node2.rule === 0) + return node2.exclusive ? "negative" : "non-positive"; + return `${node2.exclusive ? "less than" : "at most"} ${node2.rule}`; + } + }, + intersections: { + max: (l, r) => l.isStricterThan(r) ? l : r, + min: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("unit", { unit: max.rule }) : null : Disjoint.init("range", max, min) + }, + obviatesBasisDescription: true + }); + MaxNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.number.internal; + traverseAllows = this.exclusive ? (data) => data < this.rule : (data) => data <= this.rule; + reduceJsonSchema(schema2) { + if (this.exclusive) + schema2.exclusiveMaximum = this.rule; + else + schema2.maximum = this.rule; + return schema2; + } + }; + Max = { + implementation: implementation6, + Node: MaxNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/maxLength.js +var implementation7, MaxLengthNode, MaxLength; +var init_maxLength = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/maxLength.js"() { + init_disjoint(); + init_implement(); + init_registry2(); + init_toJsonSchema(); + init_range(); + implementation7 = implementNode({ + kind: "maxLength", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: createLengthRuleParser("maxLength") + } + }, + reduce: (inner, $2) => inner.rule === 0 ? $2.node("exactLength", inner) : void 0, + normalize: createLengthSchemaNormalizer("maxLength"), + defaults: { + description: (node2) => `at most length ${node2.rule}`, + actual: (data) => `${data.length}` + }, + intersections: { + maxLength: (l, r) => l.isStricterThan(r) ? l : r, + minLength: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("exactLength", { rule: max.rule }) : null : Disjoint.init("range", max, min) + } + }); + MaxLengthNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.lengthBoundable.internal; + traverseAllows = (data) => data.length <= this.rule; + reduceJsonSchema(schema2) { + switch (schema2.type) { + case "string": + schema2.maxLength = this.rule; + return schema2; + case "array": + schema2.maxItems = this.rule; + return schema2; + default: + return ToJsonSchema.throwInternalOperandError("maxLength", schema2); + } + } + }; + MaxLength = { + implementation: implementation7, + Node: MaxLengthNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/min.js +var implementation8, MinNode, Min; +var init_min = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/min.js"() { + init_implement(); + init_registry2(); + init_range(); + implementation8 = implementNode({ + kind: "min", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: {}, + exclusive: parseExclusiveKey + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + defaults: { + description: (node2) => { + if (node2.rule === 0) + return node2.exclusive ? "positive" : "non-negative"; + return `${node2.exclusive ? "more than" : "at least"} ${node2.rule}`; + } + }, + intersections: { + min: (l, r) => l.isStricterThan(r) ? l : r + }, + obviatesBasisDescription: true + }); + MinNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.number.internal; + traverseAllows = this.exclusive ? (data) => data > this.rule : (data) => data >= this.rule; + reduceJsonSchema(schema2) { + if (this.exclusive) + schema2.exclusiveMinimum = this.rule; + else + schema2.minimum = this.rule; + return schema2; + } + }; + Min = { + implementation: implementation8, + Node: MinNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/minLength.js +var implementation9, MinLengthNode, MinLength; +var init_minLength = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/minLength.js"() { + init_implement(); + init_registry2(); + init_toJsonSchema(); + init_range(); + implementation9 = implementNode({ + kind: "minLength", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: createLengthRuleParser("minLength") + } + }, + reduce: (inner) => inner.rule === 0 ? ( + // a minimum length of zero is trivially satisfied + $ark.intrinsic.unknown + ) : void 0, + normalize: createLengthSchemaNormalizer("minLength"), + defaults: { + description: (node2) => node2.rule === 1 ? "non-empty" : `at least length ${node2.rule}`, + // avoid default message like "must be non-empty (was 0)" + actual: (data) => data.length === 0 ? "" : `${data.length}` + }, + intersections: { + minLength: (l, r) => l.isStricterThan(r) ? l : r + } + }); + MinLengthNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.lengthBoundable.internal; + traverseAllows = (data) => data.length >= this.rule; + reduceJsonSchema(schema2) { + switch (schema2.type) { + case "string": + schema2.minLength = this.rule; + return schema2; + case "array": + schema2.minItems = this.rule; + return schema2; + default: + return ToJsonSchema.throwInternalOperandError("minLength", schema2); + } + } + }; + MinLength = { + implementation: implementation9, + Node: MinLengthNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/kinds.js +var boundImplementationsByKind, boundClassesByKind; +var init_kinds = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/kinds.js"() { + init_after(); + init_before(); + init_exactLength(); + init_max(); + init_maxLength(); + init_min(); + init_minLength(); + boundImplementationsByKind = { + min: Min.implementation, + max: Max.implementation, + minLength: MinLength.implementation, + maxLength: MaxLength.implementation, + exactLength: ExactLength.implementation, + after: After.implementation, + before: Before.implementation + }; + boundClassesByKind = { + min: Min.Node, + max: Max.Node, + minLength: MinLength.Node, + maxLength: MaxLength.Node, + exactLength: ExactLength.Node, + after: After.Node, + before: Before.Node + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/pattern.js +var implementation10, PatternNode, Pattern; +var init_pattern = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/pattern.js"() { + init_constraint(); + init_implement(); + init_registry2(); + implementation10 = implementNode({ + kind: "pattern", + collapsibleKey: "rule", + keys: { + rule: {}, + flags: {} + }, + normalize: (schema2) => typeof schema2 === "string" ? { rule: schema2 } : schema2 instanceof RegExp ? schema2.flags ? { rule: schema2.source, flags: schema2.flags } : { rule: schema2.source } : schema2, + obviatesBasisDescription: true, + obviatesBasisExpression: true, + hasAssociatedError: true, + intersectionIsOpen: true, + defaults: { + description: (node2) => `matched by ${node2.rule}` + }, + intersections: { + // for now, non-equal regex are naively intersected: + // https://github.com/arktypeio/arktype/issues/853 + pattern: () => null + } + }); + PatternNode = class extends InternalPrimitiveConstraint { + instance = new RegExp(this.rule, this.flags); + expression = `${this.instance}`; + traverseAllows = this.instance.test.bind(this.instance); + compiledCondition = `${this.expression}.test(data)`; + compiledNegation = `!${this.compiledCondition}`; + impliedBasis = $ark.intrinsic.string.internal; + reduceJsonSchema(base, ctx) { + if (base.pattern) { + return ctx.fallback.patternIntersection({ + code: "patternIntersection", + base, + pattern: this.rule + }); + } + base.pattern = this.rule; + return base; + } + }; + Pattern = { + implementation: implementation10, + Node: PatternNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/parse.js +var schemaKindOf, discriminateRootKind, writeInvalidSchemaMessage, nodeCountsByPrefix, serializeListableChild, nodesByRegisteredId, registerNodeId, parseNode, createNode, withId, withMeta, possiblyCollapse; +var init_parse = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/parse.js"() { + init_out(); + init_kinds2(); + init_disjoint(); + init_implement(); + init_registry2(); + init_utils(); + schemaKindOf = (schema2, allowedKinds) => { + const kind = discriminateRootKind(schema2); + if (allowedKinds && !allowedKinds.includes(kind)) { + return throwParseError2(`Root of kind ${kind} should be one of ${allowedKinds}`); + } + return kind; + }; + discriminateRootKind = (schema2) => { + if (hasArkKind(schema2, "root")) + return schema2.kind; + if (typeof schema2 === "string") { + return schema2[0] === "$" ? "alias" : schema2 in domainDescriptions2 ? "domain" : "proto"; + } + if (typeof schema2 === "function") + return "proto"; + if (typeof schema2 !== "object" || schema2 === null) + return throwParseError2(writeInvalidSchemaMessage(schema2)); + if ("morphs" in schema2) + return "morph"; + if ("branches" in schema2 || isArray(schema2)) + return "union"; + if ("unit" in schema2) + return "unit"; + if ("reference" in schema2) + return "alias"; + const schemaKeys = Object.keys(schema2); + if (schemaKeys.length === 0 || schemaKeys.some((k) => k in constraintKeys)) + return "intersection"; + if ("proto" in schema2) + return "proto"; + if ("domain" in schema2) + return "domain"; + return throwParseError2(writeInvalidSchemaMessage(schema2)); + }; + writeInvalidSchemaMessage = (schema2) => `${printable2(schema2)} is not a valid type schema`; + nodeCountsByPrefix = {}; + serializeListableChild = (listableNode) => isArray(listableNode) ? listableNode.map((node2) => node2.collapsibleJson) : listableNode.collapsibleJson; + nodesByRegisteredId = {}; + $ark.nodesByRegisteredId = nodesByRegisteredId; + registerNodeId = (prefix) => { + nodeCountsByPrefix[prefix] ??= 0; + return `${prefix}${++nodeCountsByPrefix[prefix]}`; + }; + parseNode = (ctx) => { + const impl = nodeImplementationsByKind[ctx.kind]; + const configuredSchema = impl.applyConfig?.(ctx.def, ctx.$.resolvedConfig) ?? ctx.def; + const inner = {}; + const { meta: metaSchema, ...innerSchema } = configuredSchema; + const meta = metaSchema === void 0 ? {} : typeof metaSchema === "string" ? { description: metaSchema } : metaSchema; + const innerSchemaEntries = entriesOf(innerSchema).sort(([lKey], [rKey]) => isNodeKind(lKey) ? isNodeKind(rKey) ? precedenceOfKind(lKey) - precedenceOfKind(rKey) : 1 : isNodeKind(rKey) ? -1 : lKey < rKey ? -1 : 1).filter(([k, v]) => { + if (k.startsWith("meta.")) { + const metaKey = k.slice(5); + meta[metaKey] = v; + return false; + } + return true; + }); + for (const entry of innerSchemaEntries) { + const k = entry[0]; + const keyImpl = impl.keys[k]; + if (!keyImpl) + return throwParseError2(`Key ${k} is not valid on ${ctx.kind} schema`); + const v = keyImpl.parse ? keyImpl.parse(entry[1], ctx) : entry[1]; + if (v !== unset2 && (v !== void 0 || keyImpl.preserveUndefined)) + inner[k] = v; + } + if (impl.reduce && !ctx.prereduced) { + const reduced = impl.reduce(inner, ctx.$); + if (reduced) { + if (reduced instanceof Disjoint) + return reduced.throw(); + return withMeta(reduced, meta); + } + } + const node2 = createNode({ + id: ctx.id, + kind: ctx.kind, + inner, + meta, + $: ctx.$ + }); + return node2; + }; + createNode = ({ id, kind, inner, meta, $: $2, ignoreCache }) => { + const impl = nodeImplementationsByKind[kind]; + const innerEntries = entriesOf(inner); + const children = []; + let innerJson = {}; + for (const [k, v] of innerEntries) { + const keyImpl = impl.keys[k]; + const serialize = keyImpl.serialize ?? (keyImpl.child ? serializeListableChild : defaultValueSerializer); + innerJson[k] = serialize(v); + if (keyImpl.child === true) { + const listableNode = v; + if (isArray(listableNode)) + children.push(...listableNode); + else + children.push(listableNode); + } else if (typeof keyImpl.child === "function") + children.push(...keyImpl.child(v)); + } + if (impl.finalizeInnerJson) + innerJson = impl.finalizeInnerJson(innerJson); + let json3 = { ...innerJson }; + let metaJson = {}; + if (!isEmptyObject2(meta)) { + metaJson = flatMorph2(meta, (k, v) => [ + k, + k === "examples" ? v : defaultValueSerializer(v) + ]); + json3.meta = possiblyCollapse(metaJson, "description", true); + } + innerJson = possiblyCollapse(innerJson, impl.collapsibleKey, false); + const innerHash = JSON.stringify({ kind, ...innerJson }); + json3 = possiblyCollapse(json3, impl.collapsibleKey, false); + const collapsibleJson = possiblyCollapse(json3, impl.collapsibleKey, true); + const hash = JSON.stringify({ kind, ...json3 }); + if ($2.nodesByHash[hash] && !ignoreCache) + return $2.nodesByHash[hash]; + const attachments = { + id, + kind, + impl, + inner, + innerEntries, + innerJson, + innerHash, + meta, + metaJson, + json: json3, + hash, + collapsibleJson, + children + }; + if (kind !== "intersection") { + for (const k in inner) + if (k !== "in" && k !== "out") + attachments[k] = inner[k]; + } + const node2 = new nodeClassesByKind[kind](attachments, $2); + return $2.nodesByHash[hash] = node2; + }; + withId = (node2, id) => { + if (node2.id === id) + return node2; + if (isNode(nodesByRegisteredId[id])) + throwInternalError2(`Unexpected attempt to overwrite node id ${id}`); + return createNode({ + id, + kind: node2.kind, + inner: node2.inner, + meta: node2.meta, + $: node2.$, + ignoreCache: true + }); + }; + withMeta = (node2, meta, id) => { + if (id && isNode(nodesByRegisteredId[id])) + throwInternalError2(`Unexpected attempt to overwrite node id ${id}`); + return createNode({ + id: id ?? registerNodeId(meta.alias ?? node2.kind), + kind: node2.kind, + inner: node2.inner, + meta, + $: node2.$ + }); + }; + possiblyCollapse = (json3, toKey, allowPrimitive) => { + const collapsibleKeys = Object.keys(json3); + if (collapsibleKeys.length === 1 && collapsibleKeys[0] === toKey) { + const collapsed = json3[toKey]; + if (allowPrimitive) + return collapsed; + if ( + // if the collapsed value is still an object + hasDomain2(collapsed, "object") && // and the JSON did not include any implied keys + (Object.keys(collapsed).length === 1 || Array.isArray(collapsed)) + ) { + return collapsed; + } + } + return json3; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/prop.js +var intersectProps, BaseProp, writeDefaultIntersectionMessage; +var init_prop = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/prop.js"() { + init_out(); + init_constraint(); + init_node(); + init_compile(); + init_disjoint(); + init_intersections2(); + init_registry2(); + init_traversal(); + intersectProps = (l, r, ctx) => { + if (l.key !== r.key) + return null; + const key = l.key; + let value2 = intersectOrPipeNodes(l.value, r.value, ctx); + const kind = l.required || r.required ? "required" : "optional"; + if (value2 instanceof Disjoint) { + if (kind === "optional") + value2 = $ark.intrinsic.never.internal; + else { + return value2.withPrefixKey(l.key, l.required && r.required ? "required" : "optional"); + } + } + if (kind === "required") { + return ctx.$.node("required", { + key, + value: value2 + }); + } + const defaultIntersection = l.hasDefault() ? r.hasDefault() ? l.default === r.default ? l.default : throwParseError2(writeDefaultIntersectionMessage(l.default, r.default)) : l.default : r.hasDefault() ? r.default : unset2; + return ctx.$.node("optional", { + key, + value: value2, + // unset is stripped during parsing + default: defaultIntersection + }); + }; + BaseProp = class extends BaseConstraint { + required = this.kind === "required"; + optional = this.kind === "optional"; + impliedBasis = $ark.intrinsic.object.internal; + serializedKey = compileSerializedValue(this.key); + compiledKey = typeof this.key === "string" ? this.key : this.serializedKey; + flatRefs = append2(this.value.flatRefs.map((ref) => flatRef([this.key, ...ref.path], ref.node)), flatRef([this.key], this.value)); + _transform(mapper, ctx) { + ctx.path.push(this.key); + const result = super._transform(mapper, ctx); + ctx.path.pop(); + return result; + } + hasDefault() { + return "default" in this.inner; + } + traverseAllows = (data, ctx) => { + if (this.key in data) { + return traverseKey(this.key, () => this.value.traverseAllows(data[this.key], ctx), ctx); + } + return this.optional; + }; + traverseApply = (data, ctx) => { + if (this.key in data) { + traverseKey(this.key, () => this.value.traverseApply(data[this.key], ctx), ctx); + } else if (this.hasKind("required")) + ctx.errorFromNodeContext(this.errorContext); + }; + compile(js) { + js.if(`${this.serializedKey} in data`, () => js.traverseKey(this.serializedKey, `data${js.prop(this.key)}`, this.value)); + if (this.hasKind("required")) { + js.else(() => js.traversalKind === "Apply" ? js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) : js.return(false)); + } + if (js.traversalKind === "Allows") + js.return(true); + } + }; + writeDefaultIntersectionMessage = (lValue, rValue) => `Invalid intersection of default values ${printable2(lValue)} & ${printable2(rValue)}`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/optional.js +var implementation11, OptionalNode, Optional, defaultableMorphCache, getDefaultableMorph, computeDefaultValueMorph, assertDefaultValueAssignability, writeNonPrimitiveNonFunctionDefaultValueMessage; +var init_optional = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/optional.js"() { + init_out(); + init_intrinsic(); + init_compile(); + init_errors2(); + init_implement(); + init_registry2(); + init_traversal(); + init_prop(); + implementation11 = implementNode({ + kind: "optional", + hasAssociatedError: false, + intersectionIsOpen: true, + keys: { + key: {}, + value: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + }, + default: { + preserveUndefined: true + } + }, + normalize: (schema2) => schema2, + reduce: (inner, $2) => { + if ($2.resolvedConfig.exactOptionalPropertyTypes === false) { + if (!inner.value.allows(void 0)) { + return $2.node("optional", { ...inner, value: inner.value.or(intrinsic.undefined) }, { prereduced: true }); + } + } + }, + defaults: { + description: (node2) => `${node2.compiledKey}?: ${node2.value.description}` + }, + intersections: { + optional: intersectProps + } + }); + OptionalNode = class extends BaseProp { + constructor(...args3) { + super(...args3); + if ("default" in this.inner) + assertDefaultValueAssignability(this.value, this.inner.default, this.key); + } + get rawIn() { + const baseIn = super.rawIn; + if (!this.hasDefault()) + return baseIn; + return this.$.node("optional", omit(baseIn.inner, { default: true }), { + prereduced: true + }); + } + get outProp() { + if (!this.hasDefault()) + return this; + const { default: defaultValue, ...requiredInner } = this.inner; + return this.cacheGetter("outProp", this.$.node("required", requiredInner, { prereduced: true })); + } + expression = this.hasDefault() ? `${this.compiledKey}: ${this.value.expression} = ${printable2(this.inner.default)}` : `${this.compiledKey}?: ${this.value.expression}`; + defaultValueMorph = getDefaultableMorph(this); + defaultValueMorphRef = this.defaultValueMorph && registeredReference(this.defaultValueMorph); + }; + Optional = { + implementation: implementation11, + Node: OptionalNode + }; + defaultableMorphCache = {}; + getDefaultableMorph = (node2) => { + if (!node2.hasDefault()) + return; + const cacheKey = `{${node2.compiledKey}: ${node2.value.id} = ${defaultValueSerializer(node2.default)}}`; + return defaultableMorphCache[cacheKey] ??= computeDefaultValueMorph(node2.key, node2.value, node2.default); + }; + computeDefaultValueMorph = (key, value2, defaultInput) => { + if (typeof defaultInput === "function") { + return value2.includesTransform ? (data, ctx) => { + traverseKey(key, () => value2(data[key] = defaultInput(), ctx), ctx); + return data; + } : (data) => { + data[key] = defaultInput(); + return data; + }; + } + const precomputedMorphedDefault = value2.includesTransform ? value2.assert(defaultInput) : defaultInput; + return hasDomain2(precomputedMorphedDefault, "object") ? ( + // the type signature only allows this if the value was morphed + (data, ctx) => { + traverseKey(key, () => value2(data[key] = defaultInput, ctx), ctx); + return data; + } + ) : (data) => { + data[key] = precomputedMorphedDefault; + return data; + }; + }; + assertDefaultValueAssignability = (node2, value2, key) => { + const wrapped = isThunk(value2); + if (hasDomain2(value2, "object") && !wrapped) + throwParseError2(writeNonPrimitiveNonFunctionDefaultValueMessage(key)); + const out = node2.in(wrapped ? value2() : value2); + if (out instanceof ArkErrors) { + if (key === null) { + throwParseError2(`Default ${out.summary}`); + } + const atPath = out.transform((e) => e.transform((input) => ({ ...input, prefixPath: [key] }))); + throwParseError2(`Default for ${atPath.summary}`); + } + return value2; + }; + writeNonPrimitiveNonFunctionDefaultValueMessage = (key) => { + const keyDescription = key === null ? "" : typeof key === "number" ? `for value at [${key}] ` : `for ${compileSerializedValue(key)} `; + return `Non-primitive default ${keyDescription}must be specified as a function like () => ({my: 'object'})`; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/root.js +var BaseRoot, emptyBrandNameMessage, supportedJsonSchemaTargets, writeInvalidJsonSchemaTargetMessage, validateStandardJsonSchemaTarget, exclusivizeRangeSchema, typeOrTermExtends, structureOf, writeLiteralUnionEntriesMessage, writeNonStructuralOperandMessage; +var init_root = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/root.js"() { + init_out(); + init_config(); + init_constraint(); + init_node(); + init_disjoint(); + init_errors2(); + init_implement(); + init_intersections2(); + init_registry2(); + init_utils(); + init_optional(); + BaseRoot = class extends BaseNode { + constructor(attachments, $2) { + super(attachments, $2); + Object.defineProperty(this, arkKind, { value: "root", enumerable: false }); + } + // doesn't seem possible to override this at a type-level (e.g. via declare) + // without TS complaining about getters + get rawIn() { + return super.rawIn; + } + get rawOut() { + return super.rawOut; + } + get internal() { + return this; + } + get "~standard"() { + return { + vendor: "arktype", + version: 1, + validate: (input) => { + const out = this(input); + if (out instanceof ArkErrors) + return out; + return { value: out }; + }, + jsonSchema: { + input: (opts) => this.rawIn.toJsonSchema({ + target: validateStandardJsonSchemaTarget(opts.target), + ...opts.libraryOptions + }), + output: (opts) => this.rawOut.toJsonSchema({ + target: validateStandardJsonSchemaTarget(opts.target), + ...opts.libraryOptions + }) + } + }; + } + as() { + return this; + } + brand(name) { + if (name === "") + return throwParseError2(emptyBrandNameMessage); + return this; + } + readonly() { + return this; + } + branches = this.hasKind("union") ? this.inner.branches : [this]; + distribute(mapBranch, reduceMapped) { + const mappedBranches = this.branches.map(mapBranch); + return reduceMapped?.(mappedBranches) ?? mappedBranches; + } + get shortDescription() { + return this.meta.description ?? this.defaultShortDescription; + } + toJsonSchema(opts = {}) { + const ctx = mergeToJsonSchemaConfigs(this.$.resolvedConfig.toJsonSchema, opts); + ctx.useRefs ||= this.isCyclic; + const schema2 = typeof ctx.dialect === "string" ? { $schema: ctx.dialect } : {}; + Object.assign(schema2, this.toJsonSchemaRecurse(ctx)); + if (ctx.useRefs) { + const defs = flatMorph2(this.references, (i, ref) => ref.isRoot() && !ref.alwaysExpandJsonSchema ? [ref.id, ref.toResolvedJsonSchema(ctx)] : []); + if (ctx.target === "draft-07") + Object.assign(schema2, { definitions: defs }); + else + schema2.$defs = defs; + } + return schema2; + } + toJsonSchemaRecurse(ctx) { + if (ctx.useRefs && !this.alwaysExpandJsonSchema) { + const defsKey = ctx.target === "draft-07" ? "definitions" : "$defs"; + return { $ref: `#/${defsKey}/${this.id}` }; + } + return this.toResolvedJsonSchema(ctx); + } + get alwaysExpandJsonSchema() { + return this.isBasis() || this.kind === "alias" || this.hasKind("union") && this.isBoolean; + } + toResolvedJsonSchema(ctx) { + const result = this.innerToJsonSchema(ctx); + return Object.assign(result, this.metaJson); + } + intersect(r) { + const rNode = this.$.parseDefinition(r); + const result = this.rawIntersect(rNode); + if (result instanceof Disjoint) + return result; + return this.$.finalize(result); + } + rawIntersect(r) { + return intersectNodesRoot(this, r, this.$); + } + toNeverIfDisjoint() { + return this; + } + and(r) { + const result = this.intersect(r); + return result instanceof Disjoint ? result.throw() : result; + } + rawAnd(r) { + const result = this.rawIntersect(r); + return result instanceof Disjoint ? result.throw() : result; + } + or(r) { + const rNode = this.$.parseDefinition(r); + return this.$.finalize(this.rawOr(rNode)); + } + rawOr(r) { + const branches = [...this.branches, ...r.branches]; + return this.$.node("union", branches); + } + map(flatMapEntry) { + return this.$.schema(this.applyStructuralOperation("map", [flatMapEntry])); + } + pick(...keys) { + return this.$.schema(this.applyStructuralOperation("pick", keys)); + } + omit(...keys) { + return this.$.schema(this.applyStructuralOperation("omit", keys)); + } + required() { + return this.$.schema(this.applyStructuralOperation("required", [])); + } + partial() { + return this.$.schema(this.applyStructuralOperation("partial", [])); + } + _keyof; + keyof() { + if (this._keyof) + return this._keyof; + const result = this.applyStructuralOperation("keyof", []).reduce((result2, branch) => result2.intersect(branch).toNeverIfDisjoint(), $ark.intrinsic.unknown.internal); + if (result.branches.length === 0) { + throwParseError2(writeUnsatisfiableExpressionError(`keyof ${this.expression}`)); + } + return this._keyof = this.$.finalize(result); + } + get props() { + if (this.branches.length !== 1) + return throwParseError2(writeLiteralUnionEntriesMessage(this.expression)); + return [...this.applyStructuralOperation("props", [])[0]]; + } + merge(r) { + const rNode = this.$.parseDefinition(r); + return this.$.schema(rNode.distribute((branch) => this.applyStructuralOperation("merge", [ + structureOf(branch) ?? throwParseError2(writeNonStructuralOperandMessage("merge", branch.expression)) + ]))); + } + applyStructuralOperation(operation, args3) { + return this.distribute((branch) => { + if (branch.equals($ark.intrinsic.object) && operation !== "merge") + return branch; + const structure = structureOf(branch); + if (!structure) { + throwParseError2(writeNonStructuralOperandMessage(operation, branch.expression)); + } + if (operation === "keyof") + return structure.keyof(); + if (operation === "get") + return structure.get(...args3); + if (operation === "props") + return structure.props; + const structuralMethodName = operation === "required" ? "require" : operation === "partial" ? "optionalize" : operation; + return this.$.node("intersection", { + domain: "object", + structure: structure[structuralMethodName](...args3) + }); + }); + } + get(...path3) { + if (path3[0] === void 0) + return this; + return this.$.schema(this.applyStructuralOperation("get", path3)); + } + extract(r) { + const rNode = this.$.parseDefinition(r); + return this.$.schema(this.branches.filter((branch) => branch.extends(rNode))); + } + exclude(r) { + const rNode = this.$.parseDefinition(r); + return this.$.schema(this.branches.filter((branch) => !branch.extends(rNode))); + } + array() { + return this.$.schema(this.isUnknown() ? { proto: Array } : { + proto: Array, + sequence: this + }, { prereduced: true }); + } + overlaps(r) { + const intersection = this.intersect(r); + return !(intersection instanceof Disjoint); + } + extends(r) { + if (this.isNever()) + return true; + const intersection = this.intersect(r); + return !(intersection instanceof Disjoint) && this.equals(intersection); + } + ifExtends(r) { + return this.extends(r) ? this : void 0; + } + subsumes(r) { + const rNode = this.$.parseDefinition(r); + return rNode.extends(this); + } + configure(meta, selector = "shallow") { + return this.configureReferences(meta, selector); + } + describe(description, selector = "shallow") { + return this.configure({ description }, selector); + } + // these should ideally be implemented in arktype since they use its syntax + // https://github.com/arktypeio/arktype/issues/1223 + optional() { + return [this, "?"]; + } + // these should ideally be implemented in arktype since they use its syntax + // https://github.com/arktypeio/arktype/issues/1223 + default(thunkableValue) { + assertDefaultValueAssignability(this, thunkableValue, null); + return [this, "=", thunkableValue]; + } + from(input) { + return this.assert(input); + } + _pipe(...morphs) { + const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(morph), this); + return this.$.finalize(result); + } + tryPipe(...morphs) { + const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(hasArkKind(morph, "root") ? morph : ((In, ctx) => { + try { + return morph(In, ctx); + } catch (e) { + return ctx.error({ + code: "predicate", + predicate: morph, + actual: `aborted due to error: + ${e} +` + }); + } + })), this); + return this.$.finalize(result); + } + pipe = Object.assign(this._pipe.bind(this), { + try: this.tryPipe.bind(this) + }); + to(def) { + return this.$.finalize(this.toNode(this.$.parseDefinition(def))); + } + toNode(root2) { + const result = pipeNodesRoot(this, root2, this.$); + if (result instanceof Disjoint) + return result.throw(); + return result; + } + rawPipeOnce(morph) { + if (hasArkKind(morph, "root")) + return this.toNode(morph); + return this.distribute((branch) => branch.hasKind("morph") ? this.$.node("morph", { + in: branch.inner.in, + morphs: [...branch.morphs, morph] + }) : this.$.node("morph", { + in: branch, + morphs: [morph] + }), this.$.parseSchema); + } + narrow(predicate) { + return this.constrainOut("predicate", predicate); + } + constrain(kind, schema2) { + return this._constrain("root", kind, schema2); + } + constrainIn(kind, schema2) { + return this._constrain("in", kind, schema2); + } + constrainOut(kind, schema2) { + return this._constrain("out", kind, schema2); + } + _constrain(io, kind, schema2) { + const constraint = this.$.node(kind, schema2); + if (constraint.isRoot()) { + return constraint.isUnknown() ? this : throwInternalError2(`Unexpected constraint node ${constraint}`); + } + const operand = io === "root" ? this : io === "in" ? this.rawIn : this.rawOut; + if (operand.hasKind("morph") || constraint.impliedBasis && !operand.extends(constraint.impliedBasis)) { + return throwInvalidOperandError(kind, constraint.impliedBasis, this); + } + const partialIntersection = this.$.node("intersection", { + // important this is constraint.kind instead of kind in case + // the node was reduced during parsing + [constraint.kind]: constraint + }); + const result = io === "out" ? pipeNodesRoot(this, partialIntersection, this.$) : intersectNodesRoot(this, partialIntersection, this.$); + if (result instanceof Disjoint) + result.throw(); + return this.$.finalize(result); + } + onUndeclaredKey(cfg) { + const rule = typeof cfg === "string" ? cfg : cfg.rule; + const deep = typeof cfg === "string" ? false : cfg.deep; + return this.$.finalize(this.transform((kind, inner) => kind === "structure" ? rule === "ignore" ? omit(inner, { undeclared: 1 }) : { ...inner, undeclared: rule } : inner, deep ? void 0 : { shouldTransform: (node2) => !includes(structuralKinds, node2.kind) })); + } + hasEqualMorphs(r) { + if (!this.includesTransform && !r.includesTransform) + return true; + if (!arrayEquals(this.shallowMorphs, r.shallowMorphs)) + return false; + if (!arrayEquals(this.flatMorphs, r.flatMorphs, { + isEqual: (l, r2) => l.propString === r2.propString && (l.node.hasKind("morph") && r2.node.hasKind("morph") ? l.node.hasEqualMorphs(r2.node) : l.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) + })) + return false; + return true; + } + onDeepUndeclaredKey(behavior) { + return this.onUndeclaredKey({ rule: behavior, deep: true }); + } + filter(predicate) { + return this.constrainIn("predicate", predicate); + } + divisibleBy(schema2) { + return this.constrain("divisor", schema2); + } + matching(schema2) { + return this.constrain("pattern", schema2); + } + atLeast(schema2) { + return this.constrain("min", schema2); + } + atMost(schema2) { + return this.constrain("max", schema2); + } + moreThan(schema2) { + return this.constrain("min", exclusivizeRangeSchema(schema2)); + } + lessThan(schema2) { + return this.constrain("max", exclusivizeRangeSchema(schema2)); + } + atLeastLength(schema2) { + return this.constrain("minLength", schema2); + } + atMostLength(schema2) { + return this.constrain("maxLength", schema2); + } + moreThanLength(schema2) { + return this.constrain("minLength", exclusivizeRangeSchema(schema2)); + } + lessThanLength(schema2) { + return this.constrain("maxLength", exclusivizeRangeSchema(schema2)); + } + exactlyLength(schema2) { + return this.constrain("exactLength", schema2); + } + atOrAfter(schema2) { + return this.constrain("after", schema2); + } + atOrBefore(schema2) { + return this.constrain("before", schema2); + } + laterThan(schema2) { + return this.constrain("after", exclusivizeRangeSchema(schema2)); + } + earlierThan(schema2) { + return this.constrain("before", exclusivizeRangeSchema(schema2)); + } + }; + emptyBrandNameMessage = `Expected a non-empty brand name after #`; + supportedJsonSchemaTargets = [ + "draft-2020-12", + "draft-07" + ]; + writeInvalidJsonSchemaTargetMessage = (target) => `JSONSchema target '${target}' is not supported (must be ${supportedJsonSchemaTargets.map((t) => `"${t}"`).join(" or ")})`; + validateStandardJsonSchemaTarget = (target) => { + if (!includes(supportedJsonSchemaTargets, target)) + throwParseError2(writeInvalidJsonSchemaTargetMessage(target)); + return target; + }; + exclusivizeRangeSchema = (schema2) => typeof schema2 === "object" && !(schema2 instanceof Date) ? { ...schema2, exclusive: true } : { + rule: schema2, + exclusive: true + }; + typeOrTermExtends = (t, base) => hasArkKind(base, "root") ? hasArkKind(t, "root") ? t.extends(base) : base.allows(t) : hasArkKind(t, "root") ? t.hasUnit(base) : base === t; + structureOf = (branch) => { + if (branch.hasKind("morph")) + return null; + if (branch.hasKind("intersection")) { + return branch.inner.structure ?? (branch.basis?.domain === "object" ? branch.$.bindReference($ark.intrinsic.emptyStructure) : null); + } + if (branch.isBasis() && branch.domain === "object") + return branch.$.bindReference($ark.intrinsic.emptyStructure); + return null; + }; + writeLiteralUnionEntriesMessage = (expression) => `Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received: +${expression}`; + writeNonStructuralOperandMessage = (operation, operand) => `${operation} operand must be an object (was ${operand})`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/utils.js +var defineRightwardIntersections; +var init_utils2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/utils.js"() { + init_out(); + init_implement(); + defineRightwardIntersections = (kind, implementation23) => flatMorph2(schemaKindsRightOf(kind), (i, kind2) => [ + kind2, + implementation23 + ]); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/alias.js +var normalizeAliasSchema, neverIfDisjoint, implementation12, AliasNode, writeShallowCycleErrorMessage, Alias; +var init_alias = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/alias.js"() { + init_out(); + init_parse(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_utils(); + init_root(); + init_utils2(); + normalizeAliasSchema = (schema2) => typeof schema2 === "string" ? { reference: schema2 } : schema2; + neverIfDisjoint = (result) => result instanceof Disjoint ? $ark.intrinsic.never.internal : result; + implementation12 = implementNode({ + kind: "alias", + hasAssociatedError: false, + collapsibleKey: "reference", + keys: { + reference: { + serialize: (s) => s.startsWith("$") ? s : `$ark.${s}` + }, + resolve: {} + }, + normalize: normalizeAliasSchema, + defaults: { + description: (node2) => node2.reference + }, + intersections: { + alias: (l, r, ctx) => ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r.resolution, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.reference}`), + ...defineRightwardIntersections("alias", (l, r, ctx) => { + if (r.isUnknown()) + return l; + if (r.isNever()) + return r; + if (r.isBasis() && !r.overlaps($ark.intrinsic.object)) { + return Disjoint.init("assignability", $ark.intrinsic.object, r); + } + return ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.id}`); + }) + } + }); + AliasNode = class extends BaseRoot { + expression = this.reference; + structure = void 0; + get resolution() { + const result = this._resolve(); + return nodesByRegisteredId[this.id] = result; + } + _resolve() { + if (this.resolve) + return this.resolve(); + if (this.reference[0] === "$") + return this.$.resolveRoot(this.reference.slice(1)); + const id = this.reference; + let resolution = nodesByRegisteredId[id]; + const seen = []; + while (hasArkKind(resolution, "context")) { + if (seen.includes(resolution.id)) { + return throwParseError2(writeShallowCycleErrorMessage(resolution.id, seen)); + } + seen.push(resolution.id); + resolution = nodesByRegisteredId[resolution.id]; + } + if (!hasArkKind(resolution, "root")) { + return throwInternalError2(`Unexpected resolution for reference ${this.reference} +Seen: [${seen.join("->")}] +Resolution: ${printable2(resolution)}`); + } + return resolution; + } + get resolutionId() { + if (this.reference.includes("&") || this.reference.includes("=>")) + return this.resolution.id; + if (this.reference[0] !== "$") + return this.reference; + const alias = this.reference.slice(1); + const resolution = this.$.resolutions[alias]; + if (typeof resolution === "string") + return resolution; + if (hasArkKind(resolution, "root")) + return resolution.id; + return throwInternalError2(`Unexpected resolution for reference ${this.reference}: ${printable2(resolution)}`); + } + get defaultShortDescription() { + return domainDescriptions2.object; + } + innerToJsonSchema(ctx) { + return this.resolution.toJsonSchemaRecurse(ctx); + } + traverseAllows = (data, ctx) => { + const seen = ctx.seen[this.reference]; + if (seen?.includes(data)) + return true; + ctx.seen[this.reference] = append2(seen, data); + return this.resolution.traverseAllows(data, ctx); + }; + traverseApply = (data, ctx) => { + const seen = ctx.seen[this.reference]; + if (seen?.includes(data)) + return; + ctx.seen[this.reference] = append2(seen, data); + this.resolution.traverseApply(data, ctx); + }; + compile(js) { + const id = this.resolutionId; + js.if(`ctx.seen.${id} && ctx.seen.${id}.includes(data)`, () => js.return(true)); + js.if(`!ctx.seen.${id}`, () => js.line(`ctx.seen.${id} = []`)); + js.line(`ctx.seen.${id}.push(data)`); + js.return(js.invoke(id)); + } + }; + writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join("->")}`; + Alias = { + implementation: implementation12, + Node: AliasNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/basis.js +var InternalBasis; +var init_basis = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/basis.js"() { + init_implement(); + init_root(); + InternalBasis = class extends BaseRoot { + traverseApply = (data, ctx) => { + if (!this.traverseAllows(data, ctx)) + ctx.errorFromNodeContext(this.errorContext); + }; + get errorContext() { + return { + code: this.kind, + description: this.description, + meta: this.meta, + ...this.inner + }; + } + get compiledErrorContext() { + return compileObjectLiteral(this.errorContext); + } + compile(js) { + if (js.traversalKind === "Allows") + js.return(this.compiledCondition); + else { + js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); + } + } + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/domain.js +var implementation13, DomainNode, Domain; +var init_domain2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/domain.js"() { + init_out(); + init_disjoint(); + init_implement(); + init_basis(); + implementation13 = implementNode({ + kind: "domain", + hasAssociatedError: true, + collapsibleKey: "domain", + keys: { + domain: {}, + numberAllowsNaN: {} + }, + normalize: (schema2) => typeof schema2 === "string" ? { domain: schema2 } : hasKey(schema2, "numberAllowsNaN") && schema2.domain !== "number" ? throwParseError2(Domain.writeBadAllowNanMessage(schema2.domain)) : schema2, + applyConfig: (schema2, config2) => schema2.numberAllowsNaN === void 0 && schema2.domain === "number" && config2.numberAllowsNaN ? { ...schema2, numberAllowsNaN: true } : schema2, + defaults: { + description: (node2) => domainDescriptions2[node2.domain], + actual: (data) => Number.isNaN(data) ? "NaN" : domainDescriptions2[domainOf2(data)] + }, + intersections: { + domain: (l, r) => ( + // since l === r is handled by default, remaining cases are disjoint + // outside those including options like numberAllowsNaN + l.domain === "number" && r.domain === "number" ? l.numberAllowsNaN ? r : l : Disjoint.init("domain", l, r) + ) + } + }); + DomainNode = class extends InternalBasis { + requiresNaNCheck = this.domain === "number" && !this.numberAllowsNaN; + traverseAllows = this.requiresNaNCheck ? (data) => typeof data === "number" && !Number.isNaN(data) : (data) => domainOf2(data) === this.domain; + compiledCondition = this.domain === "object" ? `((typeof data === "object" && data !== null) || typeof data === "function")` : `typeof data === "${this.domain}"${this.requiresNaNCheck ? " && !Number.isNaN(data)" : ""}`; + compiledNegation = this.domain === "object" ? `((typeof data !== "object" || data === null) && typeof data !== "function")` : `typeof data !== "${this.domain}"${this.requiresNaNCheck ? " || Number.isNaN(data)" : ""}`; + expression = this.numberAllowsNaN ? "number | NaN" : this.domain; + get nestableExpression() { + return this.numberAllowsNaN ? `(${this.expression})` : this.expression; + } + get defaultShortDescription() { + return domainDescriptions2[this.domain]; + } + innerToJsonSchema(ctx) { + if (this.domain === "bigint" || this.domain === "symbol") { + return ctx.fallback.domain({ + code: "domain", + base: {}, + domain: this.domain + }); + } + return { + type: this.domain + }; + } + }; + Domain = { + implementation: implementation13, + Node: DomainNode, + writeBadAllowNanMessage: (actual) => `numberAllowsNaN may only be specified with domain "number" (was ${actual})` + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/intersection.js +var implementation14, IntersectionNode, Intersection, writeIntersectionExpression, intersectIntersections; +var init_intersection = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/intersection.js"() { + init_out(); + init_constraint(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_utils(); + init_root(); + init_utils2(); + implementation14 = implementNode({ + kind: "intersection", + hasAssociatedError: true, + normalize: (rawSchema) => { + if (isNode(rawSchema)) + return rawSchema; + const { structure, ...schema2 } = rawSchema; + const hasRootStructureKey = !!structure; + const normalizedStructure = structure ?? {}; + const normalized = flatMorph2(schema2, (k, v) => { + if (isKeyOf2(k, structureKeys)) { + if (hasRootStructureKey) { + throwParseError2(`Flattened structure key ${k} cannot be specified alongside a root 'structure' key.`); + } + normalizedStructure[k] = v; + return []; + } + return [k, v]; + }); + if (hasArkKind(normalizedStructure, "constraint") || !isEmptyObject2(normalizedStructure)) + normalized.structure = normalizedStructure; + return normalized; + }, + finalizeInnerJson: ({ structure, ...rest }) => hasDomain2(structure, "object") ? { ...structure, ...rest } : rest, + keys: { + domain: { + child: true, + parse: (schema2, ctx) => ctx.$.node("domain", schema2) + }, + proto: { + child: true, + parse: (schema2, ctx) => ctx.$.node("proto", schema2) + }, + structure: { + child: true, + parse: (schema2, ctx) => ctx.$.node("structure", schema2), + serialize: (node2) => { + if (!node2.sequence?.minLength) + return node2.collapsibleJson; + const { sequence, ...structureJson } = node2.collapsibleJson; + const { minVariadicLength, ...sequenceJson } = sequence; + const collapsibleSequenceJson = sequenceJson.variadic && Object.keys(sequenceJson).length === 1 ? sequenceJson.variadic : sequenceJson; + return { ...structureJson, sequence: collapsibleSequenceJson }; + } + }, + divisor: { + child: true, + parse: constraintKeyParser("divisor") + }, + max: { + child: true, + parse: constraintKeyParser("max") + }, + min: { + child: true, + parse: constraintKeyParser("min") + }, + maxLength: { + child: true, + parse: constraintKeyParser("maxLength") + }, + minLength: { + child: true, + parse: constraintKeyParser("minLength") + }, + exactLength: { + child: true, + parse: constraintKeyParser("exactLength") + }, + before: { + child: true, + parse: constraintKeyParser("before") + }, + after: { + child: true, + parse: constraintKeyParser("after") + }, + pattern: { + child: true, + parse: constraintKeyParser("pattern") + }, + predicate: { + child: true, + parse: constraintKeyParser("predicate") + } + }, + // leverage reduction logic from intersection and identity to ensure initial + // parse result is reduced + reduce: (inner, $2) => ( + // we cast union out of the result here since that only occurs when intersecting two sequences + // that cannot occur when reducing a single intersection schema using unknown + intersectIntersections({}, inner, { + $: $2, + invert: false, + pipe: false + }) + ), + defaults: { + description: (node2) => { + if (node2.children.length === 0) + return "unknown"; + if (node2.structure) + return node2.structure.description; + const childDescriptions = []; + if (node2.basis && !node2.prestructurals.some((r) => r.impl.obviatesBasisDescription)) + childDescriptions.push(node2.basis.description); + if (node2.prestructurals.length) { + const sortedRefinementDescriptions = node2.prestructurals.slice().sort((l, r) => l.kind === "min" && r.kind === "max" ? -1 : 0).map((r) => r.description); + childDescriptions.push(...sortedRefinementDescriptions); + } + if (node2.inner.predicate) { + childDescriptions.push(...node2.inner.predicate.map((p) => p.description)); + } + return childDescriptions.join(" and "); + }, + expected: (source) => ` \u25E6 ${source.errors.map((e) => e.expected).join("\n \u25E6 ")}`, + problem: (ctx) => `(${ctx.actual}) must be... +${ctx.expected}` + }, + intersections: { + intersection: (l, r, ctx) => intersectIntersections(l.inner, r.inner, ctx), + ...defineRightwardIntersections("intersection", (l, r, ctx) => { + if (l.children.length === 0) + return r; + const { domain: domain2, proto, ...lInnerConstraints } = l.inner; + const lBasis = proto ?? domain2; + const basis = lBasis ? intersectOrPipeNodes(lBasis, r, ctx) : r; + return basis instanceof Disjoint ? basis : l?.basis?.equals(basis) ? ( + // if the basis doesn't change, return the original intesection + l + ) : l.$.node("intersection", { ...lInnerConstraints, [basis.kind]: basis }, { prereduced: true }); + }) + } + }); + IntersectionNode = class extends BaseRoot { + basis = this.inner.domain ?? this.inner.proto ?? null; + prestructurals = []; + refinements = this.children.filter((node2) => { + if (!node2.isRefinement()) + return false; + if (includes(prestructuralKinds, node2.kind)) + this.prestructurals.push(node2); + return true; + }); + structure = this.inner.structure; + expression = writeIntersectionExpression(this); + get shallowMorphs() { + return this.inner.structure?.structuralMorph ? [this.inner.structure.structuralMorph] : []; + } + get defaultShortDescription() { + return this.basis?.defaultShortDescription ?? "present"; + } + innerToJsonSchema(ctx) { + return this.children.reduce( + // cast is required since TS doesn't know children have compatible schema prerequisites + (schema2, child) => child.isBasis() ? child.toJsonSchemaRecurse(ctx) : child.reduceJsonSchema(schema2, ctx), + {} + ); + } + traverseAllows = (data, ctx) => this.children.every((child) => child.traverseAllows(data, ctx)); + traverseApply = (data, ctx) => { + const errorCount = ctx.currentErrorCount; + if (this.basis) { + this.basis.traverseApply(data, ctx); + if (ctx.currentErrorCount > errorCount) + return; + } + if (this.prestructurals.length) { + for (let i = 0; i < this.prestructurals.length - 1; i++) { + this.prestructurals[i].traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return; + } + this.prestructurals[this.prestructurals.length - 1].traverseApply(data, ctx); + if (ctx.currentErrorCount > errorCount) + return; + } + if (this.structure) { + this.structure.traverseApply(data, ctx); + if (ctx.currentErrorCount > errorCount) + return; + } + if (this.inner.predicate) { + for (let i = 0; i < this.inner.predicate.length - 1; i++) { + this.inner.predicate[i].traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return; + } + this.inner.predicate[this.inner.predicate.length - 1].traverseApply(data, ctx); + } + }; + compile(js) { + if (js.traversalKind === "Allows") { + for (const child of this.children) + js.check(child); + js.return(true); + return; + } + js.initializeErrorCount(); + if (this.basis) { + js.check(this.basis); + if (this.children.length > 1) + js.returnIfFail(); + } + if (this.prestructurals.length) { + for (let i = 0; i < this.prestructurals.length - 1; i++) { + js.check(this.prestructurals[i]); + js.returnIfFailFast(); + } + js.check(this.prestructurals[this.prestructurals.length - 1]); + if (this.structure || this.inner.predicate) + js.returnIfFail(); + } + if (this.structure) { + js.check(this.structure); + if (this.inner.predicate) + js.returnIfFail(); + } + if (this.inner.predicate) { + for (let i = 0; i < this.inner.predicate.length - 1; i++) { + js.check(this.inner.predicate[i]); + js.returnIfFail(); + } + js.check(this.inner.predicate[this.inner.predicate.length - 1]); + } + } + }; + Intersection = { + implementation: implementation14, + Node: IntersectionNode + }; + writeIntersectionExpression = (node2) => { + if (node2.structure?.expression) + return node2.structure.expression; + const basisExpression = node2.basis && !node2.prestructurals.some((n) => n.impl.obviatesBasisExpression) ? node2.basis.nestableExpression : ""; + const refinementsExpression = node2.prestructurals.map((n) => n.expression).join(" & "); + const fullExpression = `${basisExpression}${basisExpression ? " " : ""}${refinementsExpression}`; + if (fullExpression === "Array == 0") + return "[]"; + return fullExpression || "unknown"; + }; + intersectIntersections = (l, r, ctx) => { + const baseInner = {}; + const lBasis = l.proto ?? l.domain; + const rBasis = r.proto ?? r.domain; + const basisResult = lBasis ? rBasis ? intersectOrPipeNodes(lBasis, rBasis, ctx) : lBasis : rBasis; + if (basisResult instanceof Disjoint) + return basisResult; + if (basisResult) + baseInner[basisResult.kind] = basisResult; + return intersectConstraints({ + kind: "intersection", + baseInner, + l: flattenConstraints(l), + r: flattenConstraints(r), + roots: [], + ctx + }); + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/morph.js +var implementation15, MorphNode, Morph, writeMorphIntersectionMessage; +var init_morph = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/morph.js"() { + init_out(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_utils(); + init_root(); + init_utils2(); + implementation15 = implementNode({ + kind: "morph", + hasAssociatedError: false, + keys: { + in: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + }, + morphs: { + parse: liftArray, + serialize: (morphs) => morphs.map((m) => hasArkKind(m, "root") ? m.json : registeredReference(m)) + }, + declaredIn: { + child: false, + serialize: (node2) => node2.json + }, + declaredOut: { + child: false, + serialize: (node2) => node2.json + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => `a morph from ${node2.rawIn.description} to ${node2.rawOut?.description ?? "unknown"}` + }, + intersections: { + morph: (l, r, ctx) => { + if (!l.hasEqualMorphs(r)) { + return throwParseError2(writeMorphIntersectionMessage(l.expression, r.expression)); + } + const inTersection = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); + if (inTersection instanceof Disjoint) + return inTersection; + const baseInner = { + morphs: l.morphs + }; + if (l.declaredIn || r.declaredIn) { + const declaredIn = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); + if (declaredIn instanceof Disjoint) + return declaredIn.throw(); + else + baseInner.declaredIn = declaredIn; + } + if (l.declaredOut || r.declaredOut) { + const declaredOut = intersectOrPipeNodes(l.rawOut, r.rawOut, ctx); + if (declaredOut instanceof Disjoint) + return declaredOut.throw(); + else + baseInner.declaredOut = declaredOut; + } + return inTersection.distribute((inBranch) => ctx.$.node("morph", { + ...baseInner, + in: inBranch + }), ctx.$.parseSchema); + }, + ...defineRightwardIntersections("morph", (l, r, ctx) => { + const inTersection = l.inner.in ? intersectOrPipeNodes(l.inner.in, r, ctx) : r; + return inTersection instanceof Disjoint ? inTersection : inTersection.equals(l.inner.in) ? l : ctx.$.node("morph", { + ...l.inner, + in: inTersection + }); + }) + } + }); + MorphNode = class extends BaseRoot { + serializedMorphs = this.morphs.map(registeredReference); + compiledMorphs = `[${this.serializedMorphs}]`; + lastMorph = this.inner.morphs[this.inner.morphs.length - 1]; + lastMorphIfNode = hasArkKind(this.lastMorph, "root") ? this.lastMorph : void 0; + introspectableIn = this.inner.in; + introspectableOut = this.lastMorphIfNode ? Object.assign(this.referencesById, this.lastMorphIfNode.referencesById) && this.lastMorphIfNode.rawOut : void 0; + get shallowMorphs() { + return Array.isArray(this.inner.in?.shallowMorphs) ? [...this.inner.in.shallowMorphs, ...this.morphs] : this.morphs; + } + get rawIn() { + return this.declaredIn ?? this.inner.in?.rawIn ?? $ark.intrinsic.unknown.internal; + } + get rawOut() { + return this.declaredOut ?? this.introspectableOut ?? $ark.intrinsic.unknown.internal; + } + declareIn(declaredIn) { + return this.$.node("morph", { + ...this.inner, + declaredIn + }); + } + declareOut(declaredOut) { + return this.$.node("morph", { + ...this.inner, + declaredOut + }); + } + expression = `(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode ? "To" : "Out"}<${this.rawOut.expression}>`; + get defaultShortDescription() { + return this.rawIn.meta.description ?? this.rawIn.defaultShortDescription; + } + innerToJsonSchema(ctx) { + return ctx.fallback.morph({ + code: "morph", + base: this.rawIn.toJsonSchemaRecurse(ctx), + out: this.introspectableOut?.toJsonSchemaRecurse(ctx) ?? null + }); + } + compile(js) { + if (js.traversalKind === "Allows") { + if (!this.introspectableIn) + return; + js.return(js.invoke(this.introspectableIn)); + return; + } + if (this.introspectableIn) + js.line(js.invoke(this.introspectableIn)); + js.line(`ctx.queueMorphs(${this.compiledMorphs})`); + } + traverseAllows = (data, ctx) => !this.introspectableIn || this.introspectableIn.traverseAllows(data, ctx); + traverseApply = (data, ctx) => { + if (this.introspectableIn) + this.introspectableIn.traverseApply(data, ctx); + ctx.queueMorphs(this.morphs); + }; + /** Check if the morphs of r are equal to those of this node */ + hasEqualMorphs(r) { + return arrayEquals(this.morphs, r.morphs, { + isEqual: (lMorph, rMorph) => lMorph === rMorph || hasArkKind(lMorph, "root") && hasArkKind(rMorph, "root") && lMorph.equals(rMorph) + }); + } + }; + Morph = { + implementation: implementation15, + Node: MorphNode + }; + writeMorphIntersectionMessage = (lDescription, rDescription) => `The intersection of distinct morphs at a single path is indeterminate: +Left: ${lDescription} +Right: ${rDescription}`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/proto.js +var implementation16, ProtoNode, Proto; +var init_proto = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/proto.js"() { + init_out(); + init_disjoint(); + init_implement(); + init_registry2(); + init_utils(); + init_basis(); + implementation16 = implementNode({ + kind: "proto", + hasAssociatedError: true, + collapsibleKey: "proto", + keys: { + proto: { + serialize: (ctor) => getBuiltinNameOfConstructor2(ctor) ?? defaultValueSerializer(ctor) + }, + dateAllowsInvalid: {} + }, + normalize: (schema2) => { + const normalized = typeof schema2 === "string" ? { proto: builtinConstructors2[schema2] } : typeof schema2 === "function" ? isNode(schema2) ? schema2 : { proto: schema2 } : typeof schema2.proto === "string" ? { ...schema2, proto: builtinConstructors2[schema2.proto] } : schema2; + if (typeof normalized.proto !== "function") + throwParseError2(Proto.writeInvalidSchemaMessage(normalized.proto)); + if (hasKey(normalized, "dateAllowsInvalid") && normalized.proto !== Date) + throwParseError2(Proto.writeBadInvalidDateMessage(normalized.proto)); + return normalized; + }, + applyConfig: (schema2, config2) => { + if (schema2.dateAllowsInvalid === void 0 && schema2.proto === Date && config2.dateAllowsInvalid) + return { ...schema2, dateAllowsInvalid: true }; + return schema2; + }, + defaults: { + description: (node2) => node2.builtinName ? objectKindDescriptions2[node2.builtinName] : `an instance of ${node2.proto.name}`, + actual: (data) => data instanceof Date && data.toString() === "Invalid Date" ? "an invalid Date" : objectKindOrDomainOf(data) + }, + intersections: { + proto: (l, r) => l.proto === Date && r.proto === Date ? ( + // since l === r is handled by default, + // exactly one of l or r must have allow invalid dates + l.dateAllowsInvalid ? r : l + ) : constructorExtends(l.proto, r.proto) ? l : constructorExtends(r.proto, l.proto) ? r : Disjoint.init("proto", l, r), + domain: (proto, domain2) => domain2.domain === "object" ? proto : Disjoint.init("domain", $ark.intrinsic.object.internal, domain2) + } + }); + ProtoNode = class extends InternalBasis { + builtinName = getBuiltinNameOfConstructor2(this.proto); + serializedConstructor = this.json.proto; + requiresInvalidDateCheck = this.proto === Date && !this.dateAllowsInvalid; + traverseAllows = this.requiresInvalidDateCheck ? (data) => data instanceof Date && data.toString() !== "Invalid Date" : (data) => data instanceof this.proto; + compiledCondition = `data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck ? ` && data.toString() !== "Invalid Date"` : ""}`; + compiledNegation = `!(${this.compiledCondition})`; + innerToJsonSchema(ctx) { + switch (this.builtinName) { + case "Array": + return { + type: "array" + }; + case "Date": + return ctx.fallback.date?.({ code: "date", base: {} }) ?? ctx.fallback.proto({ code: "proto", base: {}, proto: this.proto }); + default: + return ctx.fallback.proto({ + code: "proto", + base: {}, + proto: this.proto + }); + } + } + expression = this.dateAllowsInvalid ? "Date | InvalidDate" : this.proto.name; + get nestableExpression() { + return this.dateAllowsInvalid ? `(${this.expression})` : this.expression; + } + domain = "object"; + get defaultShortDescription() { + return this.description; + } + }; + Proto = { + implementation: implementation16, + Node: ProtoNode, + writeBadInvalidDateMessage: (actual) => `dateAllowsInvalid may only be specified with constructor Date (was ${actual.name})`, + writeInvalidSchemaMessage: (actual) => `instanceOf operand must be a function (was ${domainOf2(actual)})` + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/union.js +var implementation17, UnionNode, createCaseResolutionContext, resolveCase, viableOrderedCandidates, discriminantCaseToNode, optionallyChainPropString, serializedTypeOfDescriptions, serializedPrintable, Union, discriminantToJson, describeExpressionOptions, expressBranches, describeBranches, intersectBranches, reduceBranches, assertDeterminateOverlap, pruneDiscriminant, writeIndiscriminableMorphMessage, writeOrderedIntersectionMessage; +var init_union = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/union.js"() { + init_out(); + init_compile(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_traversal(); + init_utils(); + init_root(); + init_utils2(); + implementation17 = implementNode({ + kind: "union", + hasAssociatedError: true, + collapsibleKey: "branches", + keys: { + ordered: {}, + branches: { + child: true, + parse: (schema2, ctx) => { + const branches = []; + for (const branchSchema of schema2) { + const branchNodes = hasArkKind(branchSchema, "root") ? branchSchema.branches : ctx.$.parseSchema(branchSchema).branches; + for (const node2 of branchNodes) { + if (node2.hasKind("morph")) { + const matchingMorphIndex = branches.findIndex((matching) => matching.hasKind("morph") && matching.hasEqualMorphs(node2)); + if (matchingMorphIndex === -1) + branches.push(node2); + else { + const matchingMorph = branches[matchingMorphIndex]; + branches[matchingMorphIndex] = ctx.$.node("morph", { + ...matchingMorph.inner, + in: matchingMorph.rawIn.rawOr(node2.rawIn) + }); + } + } else + branches.push(node2); + } + } + if (!ctx.def.ordered) + branches.sort((l, r) => l.hash < r.hash ? -1 : 1); + return branches; + } + } + }, + normalize: (schema2) => isArray(schema2) ? { branches: schema2 } : schema2, + reduce: (inner, $2) => { + const reducedBranches = reduceBranches(inner); + if (reducedBranches.length === 1) + return reducedBranches[0]; + if (reducedBranches.length === inner.branches.length) + return; + return $2.node("union", { + ...inner, + branches: reducedBranches + }, { prereduced: true }); + }, + defaults: { + description: (node2) => node2.distribute((branch) => branch.description, describeBranches), + expected: (ctx) => { + const byPath = groupBy(ctx.errors, "propString"); + const pathDescriptions = Object.entries(byPath).map(([path3, errors]) => { + const branchesAtPath = []; + for (const errorAtPath of errors) + appendUnique(branchesAtPath, errorAtPath.expected); + const expected = describeBranches(branchesAtPath); + const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable2(errors[0].data); + return `${path3 && `${path3} `}must be ${expected}${actual && ` (was ${actual})`}`; + }); + return describeBranches(pathDescriptions); + }, + problem: (ctx) => ctx.expected, + message: (ctx) => { + if (ctx.problem[0] === "[") { + return `value at ${ctx.problem}`; + } + return ctx.problem; + } + }, + intersections: { + union: (l, r, ctx) => { + if (l.isNever !== r.isNever) { + return Disjoint.init("presence", l, r); + } + let resultBranches; + if (l.ordered) { + if (r.ordered) { + throwParseError2(writeOrderedIntersectionMessage(l.expression, r.expression)); + } + resultBranches = intersectBranches(r.branches, l.branches, ctx); + if (resultBranches instanceof Disjoint) + resultBranches.invert(); + } else + resultBranches = intersectBranches(l.branches, r.branches, ctx); + if (resultBranches instanceof Disjoint) + return resultBranches; + return ctx.$.parseSchema(l.ordered || r.ordered ? { + branches: resultBranches, + ordered: true + } : { branches: resultBranches }); + }, + ...defineRightwardIntersections("union", (l, r, ctx) => { + const branches = intersectBranches(l.branches, [r], ctx); + if (branches instanceof Disjoint) + return branches; + if (branches.length === 1) + return branches[0]; + return ctx.$.parseSchema(l.ordered ? { branches, ordered: true } : { branches }); + }) + } + }); + UnionNode = class extends BaseRoot { + isBoolean = this.branches.length === 2 && this.branches[0].hasUnit(false) && this.branches[1].hasUnit(true); + get branchGroups() { + const branchGroups = []; + let firstBooleanIndex = -1; + for (const branch of this.branches) { + if (branch.hasKind("unit") && branch.domain === "boolean") { + if (firstBooleanIndex === -1) { + firstBooleanIndex = branchGroups.length; + branchGroups.push(branch); + } else + branchGroups[firstBooleanIndex] = $ark.intrinsic.boolean; + continue; + } + branchGroups.push(branch); + } + return branchGroups; + } + unitBranches = this.branches.filter((n) => n.rawIn.hasKind("unit")); + discriminant = this.discriminate(); + discriminantJson = this.discriminant ? discriminantToJson(this.discriminant) : null; + expression = this.distribute((n) => n.nestableExpression, expressBranches); + createBranchedOptimisticRootApply() { + return (data, onFail) => { + const optimisticResult = this.traverseOptimistic(data); + if (optimisticResult !== unset2) + return optimisticResult; + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + } + get shallowMorphs() { + return this.branches.reduce((morphs, branch) => appendUnique(morphs, branch.shallowMorphs), []); + } + get defaultShortDescription() { + return this.distribute((branch) => branch.defaultShortDescription, describeBranches); + } + innerToJsonSchema(ctx) { + if (this.branchGroups.length === 1 && this.branchGroups[0].equals($ark.intrinsic.boolean)) + return { type: "boolean" }; + const jsonSchemaBranches = this.branchGroups.map((group) => group.toJsonSchemaRecurse(ctx)); + if (jsonSchemaBranches.every((branch) => ( + // iff all branches are pure unit values with no metadata, + // we can simplify the representation to an enum + Object.keys(branch).length === 1 && hasKey(branch, "const") + ))) { + return { + enum: jsonSchemaBranches.map((branch) => branch.const) + }; + } + return { + anyOf: jsonSchemaBranches + }; + } + traverseAllows = (data, ctx) => this.branches.some((b) => b.traverseAllows(data, ctx)); + traverseApply = (data, ctx) => { + const errors = []; + for (let i = 0; i < this.branches.length; i++) { + ctx.pushBranch(); + this.branches[i].traverseApply(data, ctx); + if (!ctx.hasError()) { + if (this.branches[i].includesTransform) + return ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs); + return ctx.popBranch(); + } + errors.push(ctx.popBranch().error); + } + ctx.errorFromNodeContext({ code: "union", errors, meta: this.meta }); + }; + traverseOptimistic = (data) => { + for (let i = 0; i < this.branches.length; i++) { + const branch = this.branches[i]; + if (branch.traverseAllows(data)) { + if (branch.contextFreeMorph) + return branch.contextFreeMorph(data); + return data; + } + } + return unset2; + }; + compile(js) { + if (!this.discriminant || // if we have a union of two units like `boolean`, the + // undiscriminated compilation will be just as fast + this.unitBranches.length === this.branches.length && this.branches.length === 2) + return this.compileIndiscriminable(js); + let condition = this.discriminant.optionallyChainedPropString; + if (this.discriminant.kind === "domain") + condition = `typeof ${condition} === "object" ? ${condition} === null ? "null" : "object" : typeof ${condition} === "function" ? "object" : typeof ${condition}`; + const cases = this.discriminant.cases; + const caseKeys = Object.keys(cases); + const { optimistic } = js; + js.optimistic = false; + js.block(`switch(${condition})`, () => { + for (const k in cases) { + const v = cases[k]; + const caseCondition = k === "default" ? k : `case ${k}`; + let caseResult; + if (v === true) + caseResult = optimistic ? "data" : "true"; + else if (optimistic) { + if (v.rootApplyStrategy === "branchedOptimistic") + caseResult = js.invoke(v, { kind: "Optimistic" }); + else if (v.contextFreeMorph) + caseResult = `${js.invoke(v)} ? ${registeredReference(v.contextFreeMorph)}(data) : "${unset2}"`; + else + caseResult = `${js.invoke(v)} ? data : "${unset2}"`; + } else + caseResult = js.invoke(v); + js.line(`${caseCondition}: return ${caseResult}`); + } + return js; + }); + if (js.traversalKind === "Allows") { + js.return(optimistic ? `"${unset2}"` : false); + return; + } + const expected = describeBranches(this.discriminant.kind === "domain" ? caseKeys.map((k) => { + const jsTypeOf = k.slice(1, -1); + return jsTypeOf === "function" ? domainDescriptions2.object : domainDescriptions2[jsTypeOf]; + }) : caseKeys); + const serializedPathSegments = this.discriminant.path.map((k) => typeof k === "symbol" ? registeredReference(k) : JSON.stringify(k)); + const serializedExpected = JSON.stringify(expected); + const serializedActual = this.discriminant.kind === "domain" ? `${serializedTypeOfDescriptions}[${condition}]` : `${serializedPrintable}(${condition})`; + js.line(`ctx.errorFromNodeContext({ + code: "predicate", + expected: ${serializedExpected}, + actual: ${serializedActual}, + relativePath: [${serializedPathSegments}], + meta: ${this.compiledMeta} +})`); + } + compileIndiscriminable(js) { + if (js.traversalKind === "Apply") { + js.const("errors", "[]"); + for (const branch of this.branches) { + js.line("ctx.pushBranch()").line(js.invoke(branch)).if("!ctx.hasError()", () => js.return(branch.includesTransform ? "ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)" : "ctx.popBranch()")).line("errors.push(ctx.popBranch().error)"); + } + js.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`); + } else { + const { optimistic } = js; + js.optimistic = false; + for (const branch of this.branches) { + js.if(`${js.invoke(branch)}`, () => js.return(optimistic ? branch.contextFreeMorph ? `${registeredReference(branch.contextFreeMorph)}(data)` : "data" : true)); + } + js.return(optimistic ? `"${unset2}"` : false); + } + } + get nestableExpression() { + return this.isBoolean ? "boolean" : `(${this.expression})`; + } + discriminate() { + if (this.branches.length < 2 || this.isCyclic) + return null; + if (this.unitBranches.length === this.branches.length) { + const cases2 = flatMorph2(this.unitBranches, (i, n) => [ + `${n.rawIn.serializedValue}`, + n.hasKind("morph") ? n : true + ]); + return { + kind: "unit", + path: [], + optionallyChainedPropString: "data", + cases: cases2 + }; + } + const candidates = []; + for (let lIndex = 0; lIndex < this.branches.length - 1; lIndex++) { + const l = this.branches[lIndex]; + for (let rIndex = lIndex + 1; rIndex < this.branches.length; rIndex++) { + const r = this.branches[rIndex]; + const result = intersectNodesRoot(l.rawIn, r.rawIn, l.$); + if (!(result instanceof Disjoint)) + continue; + for (const entry of result) { + if (!entry.kind || entry.optional) + continue; + let lSerialized; + let rSerialized; + if (entry.kind === "domain") { + const lValue = entry.l; + const rValue = entry.r; + lSerialized = `"${typeof lValue === "string" ? lValue : lValue.domain}"`; + rSerialized = `"${typeof rValue === "string" ? rValue : rValue.domain}"`; + } else if (entry.kind === "unit") { + lSerialized = entry.l.serializedValue; + rSerialized = entry.r.serializedValue; + } else + continue; + const matching = candidates.find((d) => arrayEquals(d.path, entry.path) && d.kind === entry.kind); + if (!matching) { + candidates.push({ + kind: entry.kind, + cases: { + [lSerialized]: { + branchIndices: [lIndex], + condition: entry.l + }, + [rSerialized]: { + branchIndices: [rIndex], + condition: entry.r + } + }, + path: entry.path + }); + } else { + if (matching.cases[lSerialized]) { + matching.cases[lSerialized].branchIndices = appendUnique(matching.cases[lSerialized].branchIndices, lIndex); + } else { + matching.cases[lSerialized] ??= { + branchIndices: [lIndex], + condition: entry.l + }; + } + if (matching.cases[rSerialized]) { + matching.cases[rSerialized].branchIndices = appendUnique(matching.cases[rSerialized].branchIndices, rIndex); + } else { + matching.cases[rSerialized] ??= { + branchIndices: [rIndex], + condition: entry.r + }; + } + } + } + } + } + const viableCandidates = this.ordered ? viableOrderedCandidates(candidates, this.branches) : candidates; + if (!viableCandidates.length) + return null; + const ctx = createCaseResolutionContext(viableCandidates, this); + const cases = {}; + for (const k in ctx.best.cases) { + const resolution = resolveCase(ctx, k); + if (resolution === null) { + cases[k] = true; + continue; + } + if (resolution.length === this.branches.length) + return null; + if (this.ordered) { + resolution.sort((l, r) => l.originalIndex - r.originalIndex); + } + const branches = resolution.map((entry) => entry.branch); + const caseNode = branches.length === 1 ? branches[0] : this.$.node("union", this.ordered ? { branches, ordered: true } : branches); + Object.assign(this.referencesById, caseNode.referencesById); + cases[k] = caseNode; + } + if (ctx.defaultEntries.length) { + const branches = ctx.defaultEntries.map((entry) => entry.branch); + cases.default = this.$.node("union", this.ordered ? { branches, ordered: true } : branches, { + prereduced: true + }); + Object.assign(this.referencesById, cases.default.referencesById); + } + return Object.assign(ctx.location, { + cases + }); + } + }; + createCaseResolutionContext = (viableCandidates, node2) => { + const ordered = viableCandidates.sort((l, r) => l.path.length === r.path.length ? Object.keys(r.cases).length - Object.keys(l.cases).length : l.path.length - r.path.length); + const best = ordered[0]; + const location = { + kind: best.kind, + path: best.path, + optionallyChainedPropString: optionallyChainPropString(best.path) + }; + const defaultEntries = node2.branches.map((branch, originalIndex) => ({ + originalIndex, + branch + })); + return { + best, + location, + defaultEntries, + node: node2 + }; + }; + resolveCase = (ctx, key) => { + const caseCtx = ctx.best.cases[key]; + const discriminantNode = discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$); + let resolvedEntries = []; + const nextDefaults = []; + for (let i = 0; i < ctx.defaultEntries.length; i++) { + const entry = ctx.defaultEntries[i]; + if (caseCtx.branchIndices.includes(entry.originalIndex)) { + const pruned = pruneDiscriminant(ctx.node.branches[entry.originalIndex], ctx.location); + if (pruned === null) { + resolvedEntries = null; + } else { + resolvedEntries?.push({ + originalIndex: entry.originalIndex, + branch: pruned + }); + } + } else if ( + // we shouldn't need a special case for alias to avoid the below + // once alias resolution issues are improved: + // https://github.com/arktypeio/arktype/issues/1026 + entry.branch.hasKind("alias") && discriminantNode.hasKind("domain") && discriminantNode.domain === "object" + ) + resolvedEntries?.push(entry); + else { + if (entry.branch.rawIn.overlaps(discriminantNode)) { + const overlapping = pruneDiscriminant(entry.branch, ctx.location); + resolvedEntries?.push({ + originalIndex: entry.originalIndex, + branch: overlapping + }); + } + nextDefaults.push(entry); + } + } + ctx.defaultEntries = nextDefaults; + return resolvedEntries; + }; + viableOrderedCandidates = (candidates, originalBranches) => { + const viableCandidates = candidates.filter((candidate) => { + const caseGroups = Object.values(candidate.cases).map((caseCtx) => caseCtx.branchIndices); + for (let i = 0; i < caseGroups.length - 1; i++) { + const currentGroup = caseGroups[i]; + for (let j = i + 1; j < caseGroups.length; j++) { + const nextGroup = caseGroups[j]; + for (const currentIndex of currentGroup) { + for (const nextIndex of nextGroup) { + if (currentIndex > nextIndex) { + if (originalBranches[currentIndex].overlaps(originalBranches[nextIndex])) { + return false; + } + } + } + } + } + } + return true; + }); + return viableCandidates; + }; + discriminantCaseToNode = (caseDiscriminant, path3, $2) => { + let node2 = caseDiscriminant === "undefined" ? $2.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $2.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $2.units([true, false]) : caseDiscriminant; + for (let i = path3.length - 1; i >= 0; i--) { + const key = path3[i]; + node2 = $2.node("intersection", typeof key === "number" ? { + proto: "Array", + // create unknown for preceding elements (could be optimized with safe imports) + sequence: [...range(key).map((_) => ({})), node2] + } : { + domain: "object", + required: [{ key, value: node2 }] + }); + } + return node2; + }; + optionallyChainPropString = (path3) => path3.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data"); + serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions2); + serializedPrintable = registeredReference(printable2); + Union = { + implementation: implementation17, + Node: UnionNode + }; + discriminantToJson = (discriminant) => ({ + kind: discriminant.kind, + path: discriminant.path.map((k) => typeof k === "string" ? k : compileSerializedValue(k)), + cases: flatMorph2(discriminant.cases, (k, node2) => [ + k, + node2 === true ? node2 : node2.hasKind("union") && node2.discriminantJson ? node2.discriminantJson : node2.json + ]) + }); + describeExpressionOptions = { + delimiter: " | ", + finalDelimiter: " | " + }; + expressBranches = (expressions) => describeBranches(expressions, describeExpressionOptions); + describeBranches = (descriptions, opts) => { + const delimiter = opts?.delimiter ?? ", "; + const finalDelimiter = opts?.finalDelimiter ?? " or "; + if (descriptions.length === 0) + return "never"; + if (descriptions.length === 1) + return descriptions[0]; + if (descriptions.length === 2 && descriptions[0] === "false" && descriptions[1] === "true" || descriptions[0] === "true" && descriptions[1] === "false") + return "boolean"; + const seen = {}; + const unique = descriptions.filter((s) => seen[s] ? false : seen[s] = true); + const last = unique.pop(); + return `${unique.join(delimiter)}${unique.length ? finalDelimiter : ""}${last}`; + }; + intersectBranches = (l, r, ctx) => { + const batchesByR = r.map(() => []); + for (let lIndex = 0; lIndex < l.length; lIndex++) { + let candidatesByR = {}; + for (let rIndex = 0; rIndex < r.length; rIndex++) { + if (batchesByR[rIndex] === null) { + continue; + } + if (l[lIndex].equals(r[rIndex])) { + batchesByR[rIndex] = null; + candidatesByR = {}; + break; + } + const branchIntersection = intersectOrPipeNodes(l[lIndex], r[rIndex], ctx); + if (branchIntersection instanceof Disjoint) { + continue; + } + if (branchIntersection.equals(l[lIndex])) { + batchesByR[rIndex].push(l[lIndex]); + candidatesByR = {}; + break; + } + if (branchIntersection.equals(r[rIndex])) { + batchesByR[rIndex] = null; + } else { + candidatesByR[rIndex] = branchIntersection; + } + } + for (const rIndex in candidatesByR) { + batchesByR[rIndex][lIndex] = candidatesByR[rIndex]; + } + } + const resultBranches = batchesByR.flatMap( + // ensure unions returned from branchable intersections like sequence are flattened + (batch, i) => batch?.flatMap((branch) => branch.branches) ?? r[i] + ); + return resultBranches.length === 0 ? Disjoint.init("union", l, r) : resultBranches; + }; + reduceBranches = ({ branches, ordered }) => { + if (branches.length < 2) + return branches; + const uniquenessByIndex = branches.map(() => true); + for (let i = 0; i < branches.length; i++) { + for (let j = i + 1; j < branches.length && uniquenessByIndex[i] && uniquenessByIndex[j]; j++) { + if (branches[i].equals(branches[j])) { + uniquenessByIndex[j] = false; + continue; + } + const intersection = intersectNodesRoot(branches[i].rawIn, branches[j].rawIn, branches[0].$); + if (intersection instanceof Disjoint) + continue; + if (!ordered) + assertDeterminateOverlap(branches[i], branches[j]); + if (intersection.equals(branches[i].rawIn)) { + uniquenessByIndex[i] = !!ordered; + } else if (intersection.equals(branches[j].rawIn)) + uniquenessByIndex[j] = false; + } + } + return branches.filter((_, i) => uniquenessByIndex[i]); + }; + assertDeterminateOverlap = (l, r) => { + if (!l.includesTransform && !r.includesTransform) + return; + if (!arrayEquals(l.shallowMorphs, r.shallowMorphs)) { + throwParseError2(writeIndiscriminableMorphMessage(l.expression, r.expression)); + } + if (!arrayEquals(l.flatMorphs, r.flatMorphs, { + isEqual: (l2, r2) => l2.propString === r2.propString && (l2.node.hasKind("morph") && r2.node.hasKind("morph") ? l2.node.hasEqualMorphs(r2.node) : l2.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l2.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) + })) { + throwParseError2(writeIndiscriminableMorphMessage(l.expression, r.expression)); + } + }; + pruneDiscriminant = (discriminantBranch, discriminantCtx) => discriminantBranch.transform((nodeKind, inner) => { + if (nodeKind === "domain" || nodeKind === "unit") + return null; + return inner; + }, { + shouldTransform: (node2, ctx) => { + const propString = optionallyChainPropString(ctx.path); + if (!discriminantCtx.optionallyChainedPropString.startsWith(propString)) + return false; + if (node2.hasKind("domain") && node2.domain === "object") + return true; + if ((node2.hasKind("domain") || discriminantCtx.kind === "unit") && propString === discriminantCtx.optionallyChainedPropString) + return true; + return node2.children.length !== 0 && node2.kind !== "index"; + } + }); + writeIndiscriminableMorphMessage = (lDescription, rDescription) => `An unordered union of a type including a morph and a type with overlapping input is indeterminate: +Left: ${lDescription} +Right: ${rDescription}`; + writeOrderedIntersectionMessage = (lDescription, rDescription) => `The intersection of two ordered unions is indeterminate: +Left: ${lDescription} +Right: ${rDescription}`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/unit.js +var implementation18, UnitNode, Unit, compileEqualityCheck; +var init_unit = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/unit.js"() { + init_out(); + init_disjoint(); + init_implement(); + init_registry2(); + init_basis(); + init_utils2(); + implementation18 = implementNode({ + kind: "unit", + hasAssociatedError: true, + keys: { + unit: { + preserveUndefined: true, + serialize: (schema2) => schema2 instanceof Date ? schema2.toISOString() : defaultValueSerializer(schema2) + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => printable2(node2.unit), + problem: ({ expected, actual }) => `${expected === actual ? `must be reference equal to ${expected} (serialized to the same value)` : `must be ${expected} (was ${actual})`}` + }, + intersections: { + unit: (l, r) => Disjoint.init("unit", l, r), + ...defineRightwardIntersections("unit", (l, r) => { + if (r.allows(l.unit)) + return l; + const rBasis = r.hasKind("intersection") ? r.basis : r; + if (rBasis) { + const rDomain = rBasis.hasKind("domain") ? rBasis : $ark.intrinsic.object; + if (l.domain !== rDomain.domain) { + const lDomainDisjointValue = l.domain === "undefined" || l.domain === "null" || l.domain === "boolean" ? l.domain : $ark.intrinsic[l.domain]; + return Disjoint.init("domain", lDomainDisjointValue, rDomain); + } + } + return Disjoint.init("assignability", l, r.hasKind("intersection") ? r.children.find((rConstraint) => !rConstraint.allows(l.unit)) : r); + }) + } + }); + UnitNode = class extends InternalBasis { + compiledValue = this.json.unit; + serializedValue = typeof this.unit === "string" || this.unit instanceof Date ? JSON.stringify(this.compiledValue) : `${this.compiledValue}`; + compiledCondition = compileEqualityCheck(this.unit, this.serializedValue); + compiledNegation = compileEqualityCheck(this.unit, this.serializedValue, "negated"); + expression = printable2(this.unit); + domain = domainOf2(this.unit); + get defaultShortDescription() { + return this.domain === "object" ? domainDescriptions2.object : this.description; + } + innerToJsonSchema(ctx) { + return ( + // this is the more standard JSON schema representation, especially for Open API + this.unit === null ? { type: "null" } : $ark.intrinsic.jsonPrimitive.allows(this.unit) ? { const: this.unit } : ctx.fallback.unit({ code: "unit", base: {}, unit: this.unit }) + ); + } + traverseAllows = this.unit instanceof Date ? (data) => data instanceof Date && data.toISOString() === this.compiledValue : Number.isNaN(this.unit) ? (data) => Number.isNaN(data) : (data) => data === this.unit; + }; + Unit = { + implementation: implementation18, + Node: UnitNode + }; + compileEqualityCheck = (unit, serializedValue, negated) => { + if (unit instanceof Date) { + const condition = `data instanceof Date && data.toISOString() === ${serializedValue}`; + return negated ? `!(${condition})` : condition; + } + if (Number.isNaN(unit)) + return `${negated ? "!" : ""}Number.isNaN(data)`; + return `data ${negated ? "!" : "="}== ${serializedValue}`; + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/index.js +var implementation19, IndexNode, Index, writeEnumerableIndexBranches, writeInvalidPropertyKeyMessage; +var init_structure = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/index.js"() { + init_out(); + init_constraint(); + init_node(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_traversal(); + implementation19 = implementNode({ + kind: "index", + hasAssociatedError: false, + intersectionIsOpen: true, + keys: { + signature: { + child: true, + parse: (schema2, ctx) => { + const key = ctx.$.parseSchema(schema2); + if (!key.extends($ark.intrinsic.key)) { + return throwParseError2(writeInvalidPropertyKeyMessage(key.expression)); + } + const enumerableBranches = key.branches.filter((b) => b.hasKind("unit")); + if (enumerableBranches.length) { + return throwParseError2(writeEnumerableIndexBranches(enumerableBranches.map((b) => printable2(b.unit)))); + } + return key; + } + }, + value: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => `[${node2.signature.expression}]: ${node2.value.description}` + }, + intersections: { + index: (l, r, ctx) => { + if (l.signature.equals(r.signature)) { + const valueIntersection = intersectOrPipeNodes(l.value, r.value, ctx); + const value2 = valueIntersection instanceof Disjoint ? $ark.intrinsic.never.internal : valueIntersection; + return ctx.$.node("index", { signature: l.signature, value: value2 }); + } + if (l.signature.extends(r.signature) && l.value.subsumes(r.value)) + return r; + if (r.signature.extends(l.signature) && r.value.subsumes(l.value)) + return l; + return null; + } + } + }); + IndexNode = class extends BaseConstraint { + impliedBasis = $ark.intrinsic.object.internal; + expression = `[${this.signature.expression}]: ${this.value.expression}`; + flatRefs = append2(this.value.flatRefs.map((ref) => flatRef([this.signature, ...ref.path], ref.node)), flatRef([this.signature], this.value)); + traverseAllows = (data, ctx) => stringAndSymbolicEntriesOf2(data).every((entry) => { + if (this.signature.traverseAllows(entry[0], ctx)) { + return traverseKey(entry[0], () => this.value.traverseAllows(entry[1], ctx), ctx); + } + return true; + }); + traverseApply = (data, ctx) => { + for (const entry of stringAndSymbolicEntriesOf2(data)) { + if (this.signature.traverseAllows(entry[0], ctx)) { + traverseKey(entry[0], () => this.value.traverseApply(entry[1], ctx), ctx); + } + } + }; + _transform(mapper, ctx) { + ctx.path.push(this.signature); + const result = super._transform(mapper, ctx); + ctx.path.pop(); + return result; + } + compile() { + } + }; + Index = { + implementation: implementation19, + Node: IndexNode + }; + writeEnumerableIndexBranches = (keys) => `Index keys ${keys.join(", ")} should be specified as named props.`; + writeInvalidPropertyKeyMessage = (indexSchema) => `Indexed key definition '${indexSchema}' must be a string or symbol`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/required.js +var implementation20, RequiredNode, Required; +var init_required = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/required.js"() { + init_implement(); + init_prop(); + implementation20 = implementNode({ + kind: "required", + hasAssociatedError: true, + intersectionIsOpen: true, + keys: { + key: {}, + value: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => `${node2.compiledKey}: ${node2.value.description}`, + expected: (ctx) => ctx.missingValueDescription, + actual: () => "missing" + }, + intersections: { + required: intersectProps, + optional: intersectProps + } + }); + RequiredNode = class extends BaseProp { + expression = `${this.compiledKey}: ${this.value.expression}`; + errorContext = Object.freeze({ + code: "required", + missingValueDescription: this.value.defaultShortDescription, + relativePath: [this.key], + meta: this.meta + }); + compiledErrorContext = compileObjectLiteral(this.errorContext); + }; + Required = { + implementation: implementation20, + Node: RequiredNode + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/sequence.js +var implementation21, SequenceNode, defaultableMorphsCache, getDefaultableMorphs, Sequence, sequenceInnerToTuple, sequenceTupleToInner, postfixAfterOptionalOrDefaultableMessage, postfixWithoutVariadicMessage, _intersectSequences, elementIsRequired; +var init_sequence = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/sequence.js"() { + init_out(); + init_constraint(); + init_node(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_traversal(); + init_optional(); + init_prop(); + implementation21 = implementNode({ + kind: "sequence", + hasAssociatedError: false, + collapsibleKey: "variadic", + keys: { + prefix: { + child: true, + parse: (schema2, ctx) => { + if (schema2.length === 0) + return void 0; + return schema2.map((element) => ctx.$.parseSchema(element)); + } + }, + optionals: { + child: true, + parse: (schema2, ctx) => { + if (schema2.length === 0) + return void 0; + return schema2.map((element) => ctx.$.parseSchema(element)); + } + }, + defaultables: { + child: (defaultables) => defaultables.map((element) => element[0]), + parse: (defaultables, ctx) => { + if (defaultables.length === 0) + return void 0; + return defaultables.map((element) => { + const node2 = ctx.$.parseSchema(element[0]); + assertDefaultValueAssignability(node2, element[1], null); + return [node2, element[1]]; + }); + }, + serialize: (defaults) => defaults.map((element) => [ + element[0].collapsibleJson, + defaultValueSerializer(element[1]) + ]), + reduceIo: (ioKind, inner, defaultables) => { + if (ioKind === "in") { + inner.optionals = defaultables.map((d) => d[0].rawIn); + return; + } + inner.prefix = defaultables.map((d) => d[0].rawOut); + return; + } + }, + variadic: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2, ctx) + }, + minVariadicLength: { + // minVariadicLength is reflected in the id of this node, + // but not its IntersectionNode parent since it is superceded by the minLength + // node it implies + parse: (min) => min === 0 ? void 0 : min + }, + postfix: { + child: true, + parse: (schema2, ctx) => { + if (schema2.length === 0) + return void 0; + return schema2.map((element) => ctx.$.parseSchema(element)); + } + } + }, + normalize: (schema2) => { + if (typeof schema2 === "string") + return { variadic: schema2 }; + if ("variadic" in schema2 || "prefix" in schema2 || "defaultables" in schema2 || "optionals" in schema2 || "postfix" in schema2 || "minVariadicLength" in schema2) { + if (schema2.postfix?.length) { + if (!schema2.variadic) + return throwParseError2(postfixWithoutVariadicMessage); + if (schema2.optionals?.length || schema2.defaultables?.length) + return throwParseError2(postfixAfterOptionalOrDefaultableMessage); + } + if (schema2.minVariadicLength && !schema2.variadic) { + return throwParseError2("minVariadicLength may not be specified without a variadic element"); + } + return schema2; + } + return { variadic: schema2 }; + }, + reduce: (raw, $2) => { + let minVariadicLength = raw.minVariadicLength ?? 0; + const prefix = raw.prefix?.slice() ?? []; + const defaultables = raw.defaultables?.slice() ?? []; + const optionals = raw.optionals?.slice() ?? []; + const postfix = raw.postfix?.slice() ?? []; + if (raw.variadic) { + while (optionals[optionals.length - 1]?.equals(raw.variadic)) + optionals.pop(); + if (optionals.length === 0 && defaultables.length === 0) { + while (prefix[prefix.length - 1]?.equals(raw.variadic)) { + prefix.pop(); + minVariadicLength++; + } + } + while (postfix[0]?.equals(raw.variadic)) { + postfix.shift(); + minVariadicLength++; + } + } else if (optionals.length === 0 && defaultables.length === 0) { + prefix.push(...postfix.splice(0)); + } + if ( + // if any variadic adjacent elements were moved to minVariadicLength + minVariadicLength !== raw.minVariadicLength || // or any postfix elements were moved to prefix + raw.prefix && raw.prefix.length !== prefix.length + ) { + return $2.node("sequence", { + ...raw, + // empty lists will be omitted during parsing + prefix, + defaultables, + optionals, + postfix, + minVariadicLength + }, { prereduced: true }); + } + }, + defaults: { + description: (node2) => { + if (node2.isVariadicOnly) + return `${node2.variadic.nestableExpression}[]`; + const innerDescription = node2.tuple.map((element) => element.kind === "defaultables" ? `${element.node.nestableExpression} = ${printable2(element.default)}` : element.kind === "optionals" ? `${element.node.nestableExpression}?` : element.kind === "variadic" ? `...${element.node.nestableExpression}[]` : element.node.expression).join(", "); + return `[${innerDescription}]`; + } + }, + intersections: { + sequence: (l, r, ctx) => { + const rootState = _intersectSequences({ + l: l.tuple, + r: r.tuple, + disjoint: new Disjoint(), + result: [], + fixedVariants: [], + ctx + }); + const viableBranches = rootState.disjoint.length === 0 ? [rootState, ...rootState.fixedVariants] : rootState.fixedVariants; + return viableBranches.length === 0 ? rootState.disjoint : viableBranches.length === 1 ? ctx.$.node("sequence", sequenceTupleToInner(viableBranches[0].result)) : ctx.$.node("union", viableBranches.map((state) => ({ + proto: Array, + sequence: sequenceTupleToInner(state.result) + }))); + } + // exactLength, minLength, and maxLength don't need to be defined + // here since impliedSiblings guarantees they will be added + // directly to the IntersectionNode parent of the SequenceNode + // they exist on + } + }); + SequenceNode = class extends BaseConstraint { + impliedBasis = $ark.intrinsic.Array.internal; + tuple = sequenceInnerToTuple(this.inner); + prefixLength = this.prefix?.length ?? 0; + defaultablesLength = this.defaultables?.length ?? 0; + optionalsLength = this.optionals?.length ?? 0; + postfixLength = this.postfix?.length ?? 0; + defaultablesAndOptionals = []; + prevariadic = this.tuple.filter((el) => { + if (el.kind === "defaultables" || el.kind === "optionals") { + this.defaultablesAndOptionals.push(el.node); + return true; + } + return el.kind === "prefix"; + }); + variadicOrPostfix = conflatenate(this.variadic && [this.variadic], this.postfix); + // have to wait until prevariadic and variadicOrPostfix are set to calculate + flatRefs = this.addFlatRefs(); + addFlatRefs() { + appendUniqueFlatRefs(this.flatRefs, this.prevariadic.flatMap((element, i) => append2(element.node.flatRefs.map((ref) => flatRef([`${i}`, ...ref.path], ref.node)), flatRef([`${i}`], element.node)))); + appendUniqueFlatRefs(this.flatRefs, this.variadicOrPostfix.flatMap((element) => ( + // a postfix index can't be directly represented as a type + // key, so we just use the same matcher for variadic + append2(element.flatRefs.map((ref) => flatRef([$ark.intrinsic.nonNegativeIntegerString.internal, ...ref.path], ref.node)), flatRef([$ark.intrinsic.nonNegativeIntegerString.internal], element)) + ))); + return this.flatRefs; + } + isVariadicOnly = this.prevariadic.length + this.postfixLength === 0; + minVariadicLength = this.inner.minVariadicLength ?? 0; + minLength = this.prefixLength + this.minVariadicLength + this.postfixLength; + minLengthNode = this.minLength === 0 ? null : this.$.node("minLength", this.minLength); + maxLength = this.variadic ? null : this.tuple.length; + maxLengthNode = this.maxLength === null ? null : this.$.node("maxLength", this.maxLength); + impliedSiblings = this.minLengthNode ? this.maxLengthNode ? [this.minLengthNode, this.maxLengthNode] : [this.minLengthNode] : this.maxLengthNode ? [this.maxLengthNode] : []; + defaultValueMorphs = getDefaultableMorphs(this); + defaultValueMorphsReference = this.defaultValueMorphs.length ? registeredReference(this.defaultValueMorphs) : void 0; + elementAtIndex(data, index) { + if (index < this.prevariadic.length) + return this.tuple[index]; + const firstPostfixIndex = data.length - this.postfixLength; + if (index >= firstPostfixIndex) + return { kind: "postfix", node: this.postfix[index - firstPostfixIndex] }; + return { + kind: "variadic", + node: this.variadic ?? throwInternalError2(`Unexpected attempt to access index ${index} on ${this}`) + }; + } + // minLength/maxLength should be checked by Intersection before either traversal + traverseAllows = (data, ctx) => { + for (let i = 0; i < data.length; i++) { + if (!this.elementAtIndex(data, i).node.traverseAllows(data[i], ctx)) + return false; + } + return true; + }; + traverseApply = (data, ctx) => { + let i = 0; + for (; i < data.length; i++) { + traverseKey(i, () => this.elementAtIndex(data, i).node.traverseApply(data[i], ctx), ctx); + } + }; + get element() { + return this.cacheGetter("element", this.$.node("union", this.children)); + } + // minLength/maxLength compilation should be handled by Intersection + compile(js) { + if (this.prefix) { + for (const [i, node2] of this.prefix.entries()) + js.traverseKey(`${i}`, `data[${i}]`, node2); + } + for (const [i, node2] of this.defaultablesAndOptionals.entries()) { + const dataIndex = `${i + this.prefixLength}`; + js.if(`${dataIndex} >= data.length`, () => js.traversalKind === "Allows" ? js.return(true) : js.return()); + js.traverseKey(dataIndex, `data[${dataIndex}]`, node2); + } + if (this.variadic) { + if (this.postfix) { + js.const("firstPostfixIndex", `data.length${this.postfix ? `- ${this.postfix.length}` : ""}`); + } + js.for(`i < ${this.postfix ? "firstPostfixIndex" : "data.length"}`, () => js.traverseKey("i", "data[i]", this.variadic), this.prevariadic.length); + if (this.postfix) { + for (const [i, node2] of this.postfix.entries()) { + const keyExpression = `firstPostfixIndex + ${i}`; + js.traverseKey(keyExpression, `data[${keyExpression}]`, node2); + } + } + } + if (js.traversalKind === "Allows") + js.return(true); + } + _transform(mapper, ctx) { + ctx.path.push($ark.intrinsic.nonNegativeIntegerString.internal); + const result = super._transform(mapper, ctx); + ctx.path.pop(); + return result; + } + // this depends on tuple so needs to come after it + expression = this.description; + reduceJsonSchema(schema2, ctx) { + const isDraft07 = ctx.target === "draft-07"; + if (this.prevariadic.length) { + const prefixSchemas = this.prevariadic.map((el) => { + const valueSchema = el.node.toJsonSchemaRecurse(ctx); + if (el.kind === "defaultables") { + const value2 = typeof el.default === "function" ? el.default() : el.default; + valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ + code: "defaultValue", + base: valueSchema, + value: value2 + }); + } + return valueSchema; + }); + if (isDraft07) + schema2.items = prefixSchemas; + else + schema2.prefixItems = prefixSchemas; + } + if (this.minLength) + schema2.minItems = this.minLength; + if (this.variadic) { + const variadicItemSchema = this.variadic.toJsonSchemaRecurse(ctx); + if (isDraft07 && this.prevariadic.length) + schema2.additionalItems = variadicItemSchema; + else + schema2.items = variadicItemSchema; + if (this.maxLength) + schema2.maxItems = this.maxLength; + if (this.postfix) { + const elements = this.postfix.map((el) => el.toJsonSchemaRecurse(ctx)); + schema2 = ctx.fallback.arrayPostfix({ + code: "arrayPostfix", + base: schema2, + elements + }); + } + } else { + if (isDraft07) + schema2.additionalItems = false; + else + schema2.items = false; + delete schema2.maxItems; + } + return schema2; + } + }; + defaultableMorphsCache = {}; + getDefaultableMorphs = (node2) => { + if (!node2.defaultables) + return []; + const morphs = []; + let cacheKey = "["; + const lastDefaultableIndex = node2.prefixLength + node2.defaultablesLength - 1; + for (let i = node2.prefixLength; i <= lastDefaultableIndex; i++) { + const [elementNode, defaultValue] = node2.defaultables[i - node2.prefixLength]; + morphs.push(computeDefaultValueMorph(i, elementNode, defaultValue)); + cacheKey += `${i}: ${elementNode.id} = ${defaultValueSerializer(defaultValue)}, `; + } + cacheKey += "]"; + return defaultableMorphsCache[cacheKey] ??= morphs; + }; + Sequence = { + implementation: implementation21, + Node: SequenceNode + }; + sequenceInnerToTuple = (inner) => { + const tuple = []; + if (inner.prefix) + for (const node2 of inner.prefix) + tuple.push({ kind: "prefix", node: node2 }); + if (inner.defaultables) { + for (const [node2, defaultValue] of inner.defaultables) + tuple.push({ kind: "defaultables", node: node2, default: defaultValue }); + } + if (inner.optionals) + for (const node2 of inner.optionals) + tuple.push({ kind: "optionals", node: node2 }); + if (inner.variadic) + tuple.push({ kind: "variadic", node: inner.variadic }); + if (inner.postfix) + for (const node2 of inner.postfix) + tuple.push({ kind: "postfix", node: node2 }); + return tuple; + }; + sequenceTupleToInner = (tuple) => tuple.reduce((result, element) => { + if (element.kind === "variadic") + result.variadic = element.node; + else if (element.kind === "defaultables") { + result.defaultables = append2(result.defaultables, [ + [element.node, element.default] + ]); + } else + result[element.kind] = append2(result[element.kind], element.node); + return result; + }, {}); + postfixAfterOptionalOrDefaultableMessage = "A postfix required element cannot follow an optional or defaultable element"; + postfixWithoutVariadicMessage = "A postfix element requires a variadic element"; + _intersectSequences = (s) => { + const [lHead, ...lTail] = s.l; + const [rHead, ...rTail] = s.r; + if (!lHead || !rHead) + return s; + const lHasPostfix = lTail[lTail.length - 1]?.kind === "postfix"; + const rHasPostfix = rTail[rTail.length - 1]?.kind === "postfix"; + const kind = lHead.kind === "prefix" || rHead.kind === "prefix" ? "prefix" : lHead.kind === "postfix" || rHead.kind === "postfix" ? "postfix" : lHead.kind === "variadic" && rHead.kind === "variadic" ? "variadic" : lHasPostfix || rHasPostfix ? "prefix" : lHead.kind === "defaultables" || rHead.kind === "defaultables" ? "defaultables" : "optionals"; + if (lHead.kind === "prefix" && rHead.kind === "variadic" && rHasPostfix) { + const postfixBranchResult = _intersectSequences({ + ...s, + fixedVariants: [], + r: rTail.map((element) => ({ ...element, kind: "prefix" })) + }); + if (postfixBranchResult.disjoint.length === 0) + s.fixedVariants.push(postfixBranchResult); + } else if (rHead.kind === "prefix" && lHead.kind === "variadic" && lHasPostfix) { + const postfixBranchResult = _intersectSequences({ + ...s, + fixedVariants: [], + l: lTail.map((element) => ({ ...element, kind: "prefix" })) + }); + if (postfixBranchResult.disjoint.length === 0) + s.fixedVariants.push(postfixBranchResult); + } + const result = intersectOrPipeNodes(lHead.node, rHead.node, s.ctx); + if (result instanceof Disjoint) { + if (kind === "prefix" || kind === "postfix") { + s.disjoint.push(...result.withPrefixKey( + // ideally we could handle disjoint paths more precisely here, + // but not trivial to serialize postfix elements as keys + kind === "prefix" ? s.result.length : `-${lTail.length + 1}`, + // both operands must be required for the disjoint to be considered required + elementIsRequired(lHead) && elementIsRequired(rHead) ? "required" : "optional" + )); + s.result = [...s.result, { kind, node: $ark.intrinsic.never.internal }]; + } else if (kind === "optionals" || kind === "defaultables") { + return s; + } else { + return _intersectSequences({ + ...s, + fixedVariants: [], + // if there were any optional elements, there will be no postfix elements + // so this mapping will never occur (which would be illegal otherwise) + l: lTail.map((element) => ({ ...element, kind: "prefix" })), + r: lTail.map((element) => ({ ...element, kind: "prefix" })) + }); + } + } else if (kind === "defaultables") { + if (lHead.kind === "defaultables" && rHead.kind === "defaultables" && lHead.default !== rHead.default) { + throwParseError2(writeDefaultIntersectionMessage(lHead.default, rHead.default)); + } + s.result = [ + ...s.result, + { + kind, + node: result, + default: lHead.kind === "defaultables" ? lHead.default : rHead.kind === "defaultables" ? rHead.default : throwInternalError2(`Unexpected defaultable intersection from ${lHead.kind} and ${rHead.kind} elements.`) + } + ]; + } else + s.result = [...s.result, { kind, node: result }]; + const lRemaining = s.l.length; + const rRemaining = s.r.length; + if (lHead.kind !== "variadic" || lRemaining >= rRemaining && (rHead.kind === "variadic" || rRemaining === 1)) + s.l = lTail; + if (rHead.kind !== "variadic" || rRemaining >= lRemaining && (lHead.kind === "variadic" || lRemaining === 1)) + s.r = rTail; + return _intersectSequences(s); + }; + elementIsRequired = (el) => el.kind === "prefix" || el.kind === "postfix"; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/structure.js +var createStructuralWriter, structuralDescription, structuralExpression, intersectPropsAndIndex, implementation22, StructureNode, defaultableMorphsCache2, constructStructuralMorphCacheKey, getPossibleMorph, precompileMorphs, Structure, indexerToKey, writeNumberIndexMessage, normalizeIndex, typeKeyToString, writeInvalidKeysMessage, writeDuplicateKeyMessage; +var init_structure2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/structure.js"() { + init_out(); + init_constraint(); + init_intrinsic(); + init_root(); + init_compile(); + init_disjoint(); + init_implement(); + init_intersections2(); + init_registry2(); + init_toJsonSchema(); + init_traversal(); + init_utils(); + init_optional(); + createStructuralWriter = (childStringProp) => (node2) => { + if (node2.props.length || node2.index) { + const parts = node2.index?.map((index) => index[childStringProp]) ?? []; + for (const prop of node2.props) + parts.push(prop[childStringProp]); + if (node2.undeclared) + parts.push(`+ (undeclared): ${node2.undeclared}`); + const objectLiteralDescription = `{ ${parts.join(", ")} }`; + return node2.sequence ? `${objectLiteralDescription} & ${node2.sequence.description}` : objectLiteralDescription; + } + return node2.sequence?.description ?? "{}"; + }; + structuralDescription = createStructuralWriter("description"); + structuralExpression = createStructuralWriter("expression"); + intersectPropsAndIndex = (l, r, $2) => { + const kind = l.required ? "required" : "optional"; + if (!r.signature.allows(l.key)) + return null; + const value2 = intersectNodesRoot(l.value, r.value, $2); + if (value2 instanceof Disjoint) { + return kind === "optional" ? $2.node("optional", { + key: l.key, + value: $ark.intrinsic.never.internal + }) : value2.withPrefixKey(l.key, l.kind); + } + return null; + }; + implementation22 = implementNode({ + kind: "structure", + hasAssociatedError: false, + normalize: (schema2) => schema2, + applyConfig: (schema2, config2) => { + if (!schema2.undeclared && config2.onUndeclaredKey !== "ignore") { + return { + ...schema2, + undeclared: config2.onUndeclaredKey + }; + } + return schema2; + }, + keys: { + required: { + child: true, + parse: constraintKeyParser("required"), + reduceIo: (ioKind, inner, nodes) => { + inner.required = append2(inner.required, nodes.map((node2) => ioKind === "in" ? node2.rawIn : node2.rawOut)); + return; + } + }, + optional: { + child: true, + parse: constraintKeyParser("optional"), + reduceIo: (ioKind, inner, nodes) => { + if (ioKind === "in") { + inner.optional = nodes.map((node2) => node2.rawIn); + return; + } + for (const node2 of nodes) { + inner[node2.outProp.kind] = append2(inner[node2.outProp.kind], node2.outProp.rawOut); + } + } + }, + index: { + child: true, + parse: constraintKeyParser("index") + }, + sequence: { + child: true, + parse: constraintKeyParser("sequence") + }, + undeclared: { + parse: (behavior) => behavior === "ignore" ? void 0 : behavior, + reduceIo: (ioKind, inner, value2) => { + if (value2 === "reject") { + inner.undeclared = "reject"; + return; + } + if (ioKind === "in") + delete inner.undeclared; + else + inner.undeclared = "reject"; + } + } + }, + defaults: { + description: structuralDescription + }, + intersections: { + structure: (l, r, ctx) => { + const lInner = { ...l.inner }; + const rInner = { ...r.inner }; + const disjointResult = new Disjoint(); + if (l.undeclared) { + const lKey = l.keyof(); + for (const k of r.requiredKeys) { + if (!lKey.allows(k)) { + disjointResult.add("presence", $ark.intrinsic.never.internal, r.propsByKey[k].value, { + path: [k] + }); + } + } + if (rInner.optional) + rInner.optional = rInner.optional.filter((n) => lKey.allows(n.key)); + if (rInner.index) { + rInner.index = rInner.index.flatMap((n) => { + if (n.signature.extends(lKey)) + return n; + const indexOverlap = intersectNodesRoot(lKey, n.signature, ctx.$); + if (indexOverlap instanceof Disjoint) + return []; + const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); + if (normalized.required) { + rInner.required = conflatenate(rInner.required, normalized.required); + } + if (normalized.optional) { + rInner.optional = conflatenate(rInner.optional, normalized.optional); + } + return normalized.index ?? []; + }); + } + } + if (r.undeclared) { + const rKey = r.keyof(); + for (const k of l.requiredKeys) { + if (!rKey.allows(k)) { + disjointResult.add("presence", l.propsByKey[k].value, $ark.intrinsic.never.internal, { + path: [k] + }); + } + } + if (lInner.optional) + lInner.optional = lInner.optional.filter((n) => rKey.allows(n.key)); + if (lInner.index) { + lInner.index = lInner.index.flatMap((n) => { + if (n.signature.extends(rKey)) + return n; + const indexOverlap = intersectNodesRoot(rKey, n.signature, ctx.$); + if (indexOverlap instanceof Disjoint) + return []; + const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); + if (normalized.required) { + lInner.required = conflatenate(lInner.required, normalized.required); + } + if (normalized.optional) { + lInner.optional = conflatenate(lInner.optional, normalized.optional); + } + return normalized.index ?? []; + }); + } + } + const baseInner = {}; + if (l.undeclared || r.undeclared) { + baseInner.undeclared = l.undeclared === "reject" || r.undeclared === "reject" ? "reject" : "delete"; + } + const childIntersectionResult = intersectConstraints({ + kind: "structure", + baseInner, + l: flattenConstraints(lInner), + r: flattenConstraints(rInner), + roots: [], + ctx + }); + if (childIntersectionResult instanceof Disjoint) + disjointResult.push(...childIntersectionResult); + if (disjointResult.length) + return disjointResult; + return childIntersectionResult; + } + }, + reduce: (inner, $2) => { + if (!inner.required && !inner.optional) + return; + const seen = {}; + let updated = false; + const newOptionalProps = inner.optional ? [...inner.optional] : []; + if (inner.required) { + for (let i = 0; i < inner.required.length; i++) { + const requiredProp = inner.required[i]; + if (requiredProp.key in seen) + throwParseError2(writeDuplicateKeyMessage(requiredProp.key)); + seen[requiredProp.key] = true; + if (inner.index) { + for (const index of inner.index) { + const intersection = intersectPropsAndIndex(requiredProp, index, $2); + if (intersection instanceof Disjoint) + return intersection; + } + } + } + } + if (inner.optional) { + for (let i = 0; i < inner.optional.length; i++) { + const optionalProp = inner.optional[i]; + if (optionalProp.key in seen) + throwParseError2(writeDuplicateKeyMessage(optionalProp.key)); + seen[optionalProp.key] = true; + if (inner.index) { + for (const index of inner.index) { + const intersection = intersectPropsAndIndex(optionalProp, index, $2); + if (intersection instanceof Disjoint) + return intersection; + if (intersection !== null) { + newOptionalProps[i] = intersection; + updated = true; + } + } + } + } + } + if (updated) { + return $2.node("structure", { ...inner, optional: newOptionalProps }, { prereduced: true }); + } + } + }); + StructureNode = class extends BaseConstraint { + impliedBasis = $ark.intrinsic.object.internal; + impliedSiblings = this.children.flatMap((n) => n.impliedSiblings ?? []); + props = conflatenate(this.required, this.optional); + propsByKey = flatMorph2(this.props, (i, node2) => [node2.key, node2]); + propsByKeyReference = registeredReference(this.propsByKey); + expression = structuralExpression(this); + requiredKeys = this.required?.map((node2) => node2.key) ?? []; + optionalKeys = this.optional?.map((node2) => node2.key) ?? []; + literalKeys = [...this.requiredKeys, ...this.optionalKeys]; + _keyof; + keyof() { + if (this._keyof) + return this._keyof; + let branches = this.$.units(this.literalKeys).branches; + if (this.index) { + for (const { signature } of this.index) + branches = branches.concat(signature.branches); + } + return this._keyof = this.$.node("union", branches); + } + map(flatMapProp) { + return this.$.node("structure", this.props.flatMap(flatMapProp).reduce((structureInner, mapped) => { + const originalProp = this.propsByKey[mapped.key]; + if (isNode(mapped)) { + if (mapped.kind !== "required" && mapped.kind !== "optional") { + return throwParseError2(`Map result must have kind "required" or "optional" (was ${mapped.kind})`); + } + structureInner[mapped.kind] = append2(structureInner[mapped.kind], mapped); + return structureInner; + } + const mappedKind = mapped.kind ?? originalProp?.kind ?? "required"; + const mappedPropInner = flatMorph2(mapped, (k, v) => k in Optional.implementation.keys ? [k, v] : []); + structureInner[mappedKind] = append2(structureInner[mappedKind], this.$.node(mappedKind, mappedPropInner)); + return structureInner; + }, {})); + } + assertHasKeys(keys) { + const invalidKeys = keys.filter((k) => !typeOrTermExtends(k, this.keyof())); + if (invalidKeys.length) { + return throwParseError2(writeInvalidKeysMessage(this.expression, invalidKeys)); + } + } + get(indexer, ...path3) { + let value2; + let required2 = false; + const key = indexerToKey(indexer); + if ((typeof key === "string" || typeof key === "symbol") && this.propsByKey[key]) { + value2 = this.propsByKey[key].value; + required2 = this.propsByKey[key].required; + } + if (this.index) { + for (const n of this.index) { + if (typeOrTermExtends(key, n.signature)) + value2 = value2?.and(n.value) ?? n.value; + } + } + if (this.sequence && typeOrTermExtends(key, $ark.intrinsic.nonNegativeIntegerString)) { + if (hasArkKind(key, "root")) { + if (this.sequence.variadic) + value2 = value2?.and(this.sequence.element) ?? this.sequence.element; + } else { + const index = Number.parseInt(key); + if (index < this.sequence.prevariadic.length) { + const fixedElement = this.sequence.prevariadic[index].node; + value2 = value2?.and(fixedElement) ?? fixedElement; + required2 ||= index < this.sequence.prefixLength; + } else if (this.sequence.variadic) { + const nonFixedElement = this.$.node("union", this.sequence.variadicOrPostfix); + value2 = value2?.and(nonFixedElement) ?? nonFixedElement; + } + } + } + if (!value2) { + if (this.sequence?.variadic && hasArkKind(key, "root") && key.extends($ark.intrinsic.number)) { + return throwParseError2(writeNumberIndexMessage(key.expression, this.sequence.expression)); + } + return throwParseError2(writeInvalidKeysMessage(this.expression, [key])); + } + const result = value2.get(...path3); + return required2 ? result : result.or($ark.intrinsic.undefined); + } + pick(...keys) { + this.assertHasKeys(keys); + return this.$.node("structure", this.filterKeys("pick", keys)); + } + omit(...keys) { + this.assertHasKeys(keys); + return this.$.node("structure", this.filterKeys("omit", keys)); + } + optionalize() { + const { required: required2, ...inner } = this.inner; + return this.$.node("structure", { + ...inner, + optional: this.props.map((prop) => prop.hasKind("required") ? this.$.node("optional", prop.inner) : prop) + }); + } + require() { + const { optional, ...inner } = this.inner; + return this.$.node("structure", { + ...inner, + required: this.props.map((prop) => prop.hasKind("optional") ? { + key: prop.key, + value: prop.value + } : prop) + }); + } + merge(r) { + const inner = this.filterKeys("omit", [r.keyof()]); + if (r.required) + inner.required = append2(inner.required, r.required); + if (r.optional) + inner.optional = append2(inner.optional, r.optional); + if (r.index) + inner.index = append2(inner.index, r.index); + if (r.sequence) + inner.sequence = r.sequence; + if (r.undeclared) + inner.undeclared = r.undeclared; + else + delete inner.undeclared; + return this.$.node("structure", inner); + } + filterKeys(operation, keys) { + const result = makeRootAndArrayPropertiesMutable(this.inner); + const shouldKeep = (key) => { + const matchesKey = keys.some((k) => typeOrTermExtends(key, k)); + return operation === "pick" ? matchesKey : !matchesKey; + }; + if (result.required) + result.required = result.required.filter((prop) => shouldKeep(prop.key)); + if (result.optional) + result.optional = result.optional.filter((prop) => shouldKeep(prop.key)); + if (result.index) + result.index = result.index.filter((index) => shouldKeep(index.signature)); + return result; + } + traverseAllows = (data, ctx) => this._traverse("Allows", data, ctx); + traverseApply = (data, ctx) => this._traverse("Apply", data, ctx); + _traverse = (traversalKind, data, ctx) => { + const errorCount = ctx?.currentErrorCount ?? 0; + for (let i = 0; i < this.props.length; i++) { + if (traversalKind === "Allows") { + if (!this.props[i].traverseAllows(data, ctx)) + return false; + } else { + this.props[i].traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return false; + } + } + if (this.sequence) { + if (traversalKind === "Allows") { + if (!this.sequence.traverseAllows(data, ctx)) + return false; + } else { + this.sequence.traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return false; + } + } + if (this.index || this.undeclared === "reject") { + const keys = Object.keys(data); + keys.push(...Object.getOwnPropertySymbols(data)); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (this.index) { + for (const node2 of this.index) { + if (node2.signature.traverseAllows(k, ctx)) { + if (traversalKind === "Allows") { + const result = traverseKey(k, () => node2.value.traverseAllows(data[k], ctx), ctx); + if (!result) + return false; + } else { + traverseKey(k, () => node2.value.traverseApply(data[k], ctx), ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return false; + } + } + } + } + if (this.undeclared === "reject" && !this.declaresKey(k)) { + if (traversalKind === "Allows") + return false; + ctx.errorFromNodeContext({ + code: "predicate", + expected: "removed", + actual: "", + relativePath: [k], + meta: this.meta + }); + if (ctx.failFast) + return false; + } + } + } + if (this.structuralMorph && ctx && !ctx.hasError()) + ctx.queueMorphs([this.structuralMorph]); + return true; + }; + get defaultable() { + return this.cacheGetter("defaultable", this.optional?.filter((o) => o.hasDefault()) ?? []); + } + declaresKey = (k) => k in this.propsByKey || this.index?.some((n) => n.signature.allows(k)) || this.sequence !== void 0 && $ark.intrinsic.nonNegativeIntegerString.allows(k); + _compileDeclaresKey(js) { + const parts = []; + if (this.props.length) + parts.push(`k in ${this.propsByKeyReference}`); + if (this.index) { + for (const index of this.index) + parts.push(js.invoke(index.signature, { kind: "Allows", arg: "k" })); + } + if (this.sequence) + parts.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"); + return parts.join(" || ") || "false"; + } + get structuralMorph() { + return this.cacheGetter("structuralMorph", getPossibleMorph(this)); + } + structuralMorphRef = this.structuralMorph && registeredReference(this.structuralMorph); + compile(js) { + if (js.traversalKind === "Apply") + js.initializeErrorCount(); + for (const prop of this.props) { + js.check(prop); + if (js.traversalKind === "Apply") + js.returnIfFailFast(); + } + if (this.sequence) { + js.check(this.sequence); + if (js.traversalKind === "Apply") + js.returnIfFailFast(); + } + if (this.index || this.undeclared === "reject") { + js.const("keys", "Object.keys(data)"); + js.line("keys.push(...Object.getOwnPropertySymbols(data))"); + js.for("i < keys.length", () => this.compileExhaustiveEntry(js)); + } + if (js.traversalKind === "Allows") + return js.return(true); + if (this.structuralMorphRef) { + js.if("ctx && !ctx.hasError()", () => { + js.line(`ctx.queueMorphs([`); + precompileMorphs(js, this); + return js.line("])"); + }); + } + } + compileExhaustiveEntry(js) { + js.const("k", "keys[i]"); + if (this.index) { + for (const node2 of this.index) { + js.if(`${js.invoke(node2.signature, { arg: "k", kind: "Allows" })}`, () => js.traverseKey("k", "data[k]", node2.value)); + } + } + if (this.undeclared === "reject") { + js.if(`!(${this._compileDeclaresKey(js)})`, () => { + if (js.traversalKind === "Allows") + return js.return(false); + return js.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast", () => js.return()); + }); + } + return js; + } + reduceJsonSchema(schema2, ctx) { + switch (schema2.type) { + case "object": + return this.reduceObjectJsonSchema(schema2, ctx); + case "array": + const arraySchema = this.sequence?.reduceJsonSchema(schema2, ctx) ?? schema2; + if (this.props.length || this.index) { + return ctx.fallback.arrayObject({ + code: "arrayObject", + base: arraySchema, + object: this.reduceObjectJsonSchema({ type: "object" }, ctx) + }); + } + return arraySchema; + default: + return ToJsonSchema.throwInternalOperandError("structure", schema2); + } + } + reduceObjectJsonSchema(schema2, ctx) { + if (this.props.length) { + schema2.properties = {}; + for (const prop of this.props) { + const valueSchema = prop.value.toJsonSchemaRecurse(ctx); + if (typeof prop.key === "symbol") { + ctx.fallback.symbolKey({ + code: "symbolKey", + base: schema2, + key: prop.key, + value: valueSchema, + optional: prop.optional + }); + continue; + } + if (prop.hasDefault()) { + const value2 = typeof prop.default === "function" ? prop.default() : prop.default; + valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ + code: "defaultValue", + base: valueSchema, + value: value2 + }); + } + schema2.properties[prop.key] = valueSchema; + } + if (this.requiredKeys.length && schema2.properties) { + schema2.required = this.requiredKeys.filter((k) => typeof k === "string" && k in schema2.properties); + } + } + if (this.index) { + for (const index of this.index) { + const valueJsonSchema = index.value.toJsonSchemaRecurse(ctx); + if (index.signature.equals($ark.intrinsic.string)) { + schema2.additionalProperties = valueJsonSchema; + continue; + } + for (const keyBranch of index.signature.branches) { + if (!keyBranch.extends($ark.intrinsic.string)) { + schema2 = ctx.fallback.symbolKey({ + code: "symbolKey", + base: schema2, + key: null, + value: valueJsonSchema, + optional: false + }); + continue; + } + let keySchema = { type: "string" }; + if (keyBranch.hasKind("morph")) { + keySchema = ctx.fallback.morph({ + code: "morph", + base: keyBranch.rawIn.toJsonSchemaRecurse(ctx), + out: keyBranch.rawOut.toJsonSchemaRecurse(ctx) + }); + } + if (!keyBranch.hasKind("intersection")) { + return throwInternalError2(`Unexpected index branch kind ${keyBranch.kind}.`); + } + const { pattern } = keyBranch.inner; + if (pattern) { + const keySchemaWithPattern = Object.assign(keySchema, { + pattern: pattern[0].rule + }); + for (let i = 1; i < pattern.length; i++) { + keySchema = ctx.fallback.patternIntersection({ + code: "patternIntersection", + base: keySchemaWithPattern, + pattern: pattern[i].rule + }); + } + schema2.patternProperties ??= {}; + schema2.patternProperties[keySchemaWithPattern.pattern] = valueJsonSchema; + } + } + } + } + if (this.undeclared && !schema2.additionalProperties) + schema2.additionalProperties = false; + return schema2; + } + }; + defaultableMorphsCache2 = {}; + constructStructuralMorphCacheKey = (node2) => { + let cacheKey = ""; + for (let i = 0; i < node2.defaultable.length; i++) + cacheKey += node2.defaultable[i].defaultValueMorphRef; + if (node2.sequence?.defaultValueMorphsReference) + cacheKey += node2.sequence?.defaultValueMorphsReference; + if (node2.undeclared === "delete") { + cacheKey += "delete !("; + if (node2.required) + for (const n of node2.required) + cacheKey += n.compiledKey + " | "; + if (node2.optional) + for (const n of node2.optional) + cacheKey += n.compiledKey + " | "; + if (node2.index) + for (const index of node2.index) + cacheKey += index.signature.id + " | "; + if (node2.sequence) { + if (node2.sequence.maxLength === null) + cacheKey += intrinsic.nonNegativeIntegerString.id; + else { + for (let i = 0; i < node2.sequence.tuple.length; i++) + cacheKey += i + " | "; + } + } + cacheKey += ")"; + } + return cacheKey; + }; + getPossibleMorph = (node2) => { + const cacheKey = constructStructuralMorphCacheKey(node2); + if (!cacheKey) + return void 0; + if (defaultableMorphsCache2[cacheKey]) + return defaultableMorphsCache2[cacheKey]; + const $arkStructuralMorph = (data, ctx) => { + for (let i = 0; i < node2.defaultable.length; i++) { + if (!(node2.defaultable[i].key in data)) + node2.defaultable[i].defaultValueMorph(data, ctx); + } + if (node2.sequence?.defaultables) { + for (let i = data.length - node2.sequence.prefixLength; i < node2.sequence.defaultables.length; i++) + node2.sequence.defaultValueMorphs[i](data, ctx); + } + if (node2.undeclared === "delete") { + for (const k in data) + if (!node2.declaresKey(k)) + delete data[k]; + } + return data; + }; + return defaultableMorphsCache2[cacheKey] = $arkStructuralMorph; + }; + precompileMorphs = (js, node2) => { + const requiresContext = node2.defaultable.some((node3) => node3.defaultValueMorph.length === 2) || node2.sequence?.defaultValueMorphs.some((morph) => morph.length === 2); + const args3 = `(data${requiresContext ? ", ctx" : ""})`; + return js.block(`${args3} => `, (js2) => { + for (let i = 0; i < node2.defaultable.length; i++) { + const { serializedKey, defaultValueMorphRef } = node2.defaultable[i]; + js2.if(`!(${serializedKey} in data)`, (js3) => js3.line(`${defaultValueMorphRef}${args3}`)); + } + if (node2.sequence?.defaultables) { + js2.for(`i < ${node2.sequence.defaultables.length}`, (js3) => js3.set(`data[i]`, 5), `data.length - ${node2.sequence.prefixLength}`); + } + if (node2.undeclared === "delete") { + js2.forIn("data", (js3) => js3.if(`!(${node2._compileDeclaresKey(js3)})`, (js4) => js4.line(`delete data[k]`))); + } + return js2.return("data"); + }); + }; + Structure = { + implementation: implementation22, + Node: StructureNode + }; + indexerToKey = (indexable) => { + if (hasArkKind(indexable, "root") && indexable.hasKind("unit")) + indexable = indexable.unit; + if (typeof indexable === "number") + indexable = `${indexable}`; + return indexable; + }; + writeNumberIndexMessage = (indexExpression, sequenceExpression) => `${indexExpression} is not allowed as an array index on ${sequenceExpression}. Use the 'nonNegativeIntegerString' keyword instead.`; + normalizeIndex = (signature, value2, $2) => { + const [enumerableBranches, nonEnumerableBranches] = spliterate(signature.branches, (k) => k.hasKind("unit")); + if (!enumerableBranches.length) + return { index: $2.node("index", { signature, value: value2 }) }; + const normalized = {}; + for (const n of enumerableBranches) { + const prop = $2.node("required", { key: n.unit, value: value2 }); + normalized[prop.kind] = append2(normalized[prop.kind], prop); + } + if (nonEnumerableBranches.length) { + normalized.index = $2.node("index", { + signature: nonEnumerableBranches, + value: value2 + }); + } + return normalized; + }; + typeKeyToString = (k) => hasArkKind(k, "root") ? k.expression : printable2(k); + writeInvalidKeysMessage = (o, keys) => `Key${keys.length === 1 ? "" : "s"} ${keys.map(typeKeyToString).join(", ")} ${keys.length === 1 ? "does" : "do"} not exist on ${o}`; + writeDuplicateKeyMessage = (key) => `Duplicate key ${compileSerializedValue(key)}`; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/kinds.js +var nodeImplementationsByKind, nodeClassesByKind; +var init_kinds2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/kinds.js"() { + init_out(); + init_config(); + init_predicate(); + init_divisor(); + init_kinds(); + init_pattern(); + init_alias(); + init_domain2(); + init_intersection(); + init_morph(); + init_proto(); + init_union(); + init_unit(); + init_registry2(); + init_toJsonSchema(); + init_structure(); + init_optional(); + init_required(); + init_sequence(); + init_structure2(); + nodeImplementationsByKind = { + ...boundImplementationsByKind, + alias: Alias.implementation, + domain: Domain.implementation, + unit: Unit.implementation, + proto: Proto.implementation, + union: Union.implementation, + morph: Morph.implementation, + intersection: Intersection.implementation, + divisor: Divisor.implementation, + pattern: Pattern.implementation, + predicate: Predicate.implementation, + required: Required.implementation, + optional: Optional.implementation, + index: Index.implementation, + sequence: Sequence.implementation, + structure: Structure.implementation + }; + $ark.defaultConfig = withAlphabetizedKeys(Object.assign(flatMorph2(nodeImplementationsByKind, (kind, implementation23) => [ + kind, + implementation23.defaults + ]), { + jitless: envHasCsp2(), + clone: deepClone, + onUndeclaredKey: "ignore", + exactOptionalPropertyTypes: true, + numberAllowsNaN: false, + dateAllowsInvalid: false, + onFail: null, + keywords: {}, + toJsonSchema: ToJsonSchema.defaultConfig + })); + $ark.resolvedConfig = mergeConfigs($ark.defaultConfig, $ark.config); + nodeClassesByKind = { + ...boundClassesByKind, + alias: Alias.Node, + domain: Domain.Node, + unit: Unit.Node, + proto: Proto.Node, + union: Union.Node, + morph: Morph.Node, + intersection: Intersection.Node, + divisor: Divisor.Node, + pattern: Pattern.Node, + predicate: Predicate.Node, + required: Required.Node, + optional: Optional.Node, + index: Index.Node, + sequence: Sequence.Node, + structure: Structure.Node + }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/module.js +var RootModule, bindModule; +var init_module = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/module.js"() { + init_out(); + init_utils(); + RootModule = class extends DynamicBase { + // ensure `[arkKind]` is non-enumerable so it doesn't get spread on import/export + get [arkKind]() { + return "module"; + } + }; + bindModule = (module, $2) => new RootModule(flatMorph2(module, (alias, value2) => [ + alias, + hasArkKind(value2, "module") ? bindModule(value2, $2) : $2.bindReference(value2) + ])); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/scope.js +var schemaBranchesOf, throwMismatchedNodeRootError, writeDuplicateAliasError, scopesByName, rawUnknownUnion, rootScopeFnName, precompile, bindPrecompilation, precompileReferences, BaseScope, SchemaScope, bootstrapAliasReferences, resolutionsToJson, maybeResolveSubalias, schemaScope, rootSchemaScope, resolutionsOfModule, writeUnresolvableMessage, writeNonSubmoduleDotMessage, writeMissingSubmoduleAccessMessage, rootSchema, node, defineSchema, genericNode; +var init_scope = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/scope.js"() { + init_out(); + init_config(); + init_generic(); + init_kinds2(); + init_module(); + init_parse(); + init_alias(); + init_compile(); + init_registry2(); + init_traversal(); + init_utils(); + schemaBranchesOf = (schema2) => isArray(schema2) ? schema2 : "branches" in schema2 && isArray(schema2.branches) ? schema2.branches : void 0; + throwMismatchedNodeRootError = (expected, actual) => throwParseError2(`Node of kind ${actual} is not valid as a ${expected} definition`); + writeDuplicateAliasError = (alias) => `#${alias} duplicates public alias ${alias}`; + scopesByName = {}; + $ark.ambient ??= {}; + rootScopeFnName = "function $"; + precompile = (references) => bindPrecompilation(references, precompileReferences(references)); + bindPrecompilation = (references, precompiler) => { + const precompilation = precompiler.write(rootScopeFnName, 4); + const compiledTraversals = precompiler.compile()(); + for (const node2 of references) { + if (node2.precompilation) { + continue; + } + node2.traverseAllows = compiledTraversals[`${node2.id}Allows`].bind(compiledTraversals); + if (node2.isRoot() && !node2.allowsRequiresContext) { + node2.allows = node2.traverseAllows; + } + node2.traverseApply = compiledTraversals[`${node2.id}Apply`].bind(compiledTraversals); + if (compiledTraversals[`${node2.id}Optimistic`]) { + ; + node2.traverseOptimistic = compiledTraversals[`${node2.id}Optimistic`].bind(compiledTraversals); + } + node2.precompilation = precompilation; + } + }; + precompileReferences = (references) => new CompiledFunction().return(references.reduce((js, node2) => { + const allowsCompiler = new NodeCompiler({ kind: "Allows" }).indent(); + node2.compile(allowsCompiler); + const allowsJs = allowsCompiler.write(`${node2.id}Allows`); + const applyCompiler = new NodeCompiler({ kind: "Apply" }).indent(); + node2.compile(applyCompiler); + const applyJs = applyCompiler.write(`${node2.id}Apply`); + const result = `${js}${allowsJs}, +${applyJs}, +`; + if (!node2.hasKind("union")) + return result; + const optimisticCompiler = new NodeCompiler({ + kind: "Allows", + optimistic: true + }).indent(); + node2.compile(optimisticCompiler); + const optimisticJs = optimisticCompiler.write(`${node2.id}Optimistic`); + return `${result}${optimisticJs}, +`; + }, "{\n") + "}"); + BaseScope = class { + config; + resolvedConfig; + name; + get [arkKind]() { + return "scope"; + } + referencesById = {}; + references = []; + resolutions = {}; + exportedNames = []; + aliases = {}; + resolved = false; + nodesByHash = {}; + intrinsic; + constructor(def, config2) { + this.config = mergeConfigs($ark.config, config2); + this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config2); + this.name = this.resolvedConfig.name ?? `anonymousScope${Object.keys(scopesByName).length}`; + if (this.name in scopesByName) + throwParseError2(`A Scope already named ${this.name} already exists`); + scopesByName[this.name] = this; + const aliasEntries = Object.entries(def).map((entry) => this.preparseOwnAliasEntry(...entry)); + for (const [k, v] of aliasEntries) { + let name = k; + if (k[0] === "#") { + name = k.slice(1); + if (name in this.aliases) + throwParseError2(writeDuplicateAliasError(name)); + this.aliases[name] = v; + } else { + if (name in this.aliases) + throwParseError2(writeDuplicateAliasError(k)); + this.aliases[name] = v; + this.exportedNames.push(name); + } + if (!hasArkKind(v, "module") && !hasArkKind(v, "generic") && !isThunk(v)) { + const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name }); + this.resolutions[name] = hasArkKind(preparsed, "root") ? this.bindReference(preparsed) : this.createParseContext(preparsed).id; + } + } + rawUnknownUnion ??= this.node("union", { + branches: [ + "string", + "number", + "object", + "bigint", + "symbol", + { unit: true }, + { unit: false }, + { unit: void 0 }, + { unit: null } + ] + }, { prereduced: true }); + this.nodesByHash[rawUnknownUnion.hash] = this.node("intersection", {}, { prereduced: true }); + this.intrinsic = $ark.intrinsic ? flatMorph2($ark.intrinsic, (k, v) => ( + // don't include cyclic aliases from JSON scope + k.startsWith("json") ? [] : [k, this.bindReference(v)] + )) : {}; + } + cacheGetter(name, value2) { + Object.defineProperty(this, name, { value: value2 }); + return value2; + } + get internal() { + return this; + } + // json is populated when the scope is exported, so ensure it is populated + // before allowing external access + _json; + get json() { + if (!this._json) + this.export(); + return this._json; + } + defineSchema(def) { + return def; + } + generic = (...params) => { + const $2 = this; + return (def, possibleHkt) => new GenericRoot(params, possibleHkt ? new LazyGenericBody(def) : def, $2, $2, possibleHkt ?? null); + }; + units = (values, opts) => { + const uniqueValues = []; + for (const value2 of values) + if (!uniqueValues.includes(value2)) + uniqueValues.push(value2); + const branches = uniqueValues.map((unit) => this.node("unit", { unit }, opts)); + return this.node("union", branches, { + ...opts, + prereduced: true + }); + }; + lazyResolutions = []; + lazilyResolve(resolve, syntheticAlias) { + const node2 = this.node("alias", { + reference: syntheticAlias ?? "synthetic", + resolve + }, { prereduced: true }); + if (!this.resolved) + this.lazyResolutions.push(node2); + return node2; + } + schema = (schema2, opts) => this.finalize(this.parseSchema(schema2, opts)); + parseSchema = (schema2, opts) => this.node(schemaKindOf(schema2), schema2, opts); + preparseNode(kinds, schema2, opts) { + let kind = typeof kinds === "string" ? kinds : schemaKindOf(schema2, kinds); + if (isNode(schema2) && schema2.kind === kind) + return schema2; + if (kind === "alias" && !opts?.prereduced) { + const { reference: reference2 } = Alias.implementation.normalize(schema2, this); + if (reference2.startsWith("$")) { + const resolution = this.resolveRoot(reference2.slice(1)); + schema2 = resolution; + kind = resolution.kind; + } + } else if (kind === "union" && hasDomain2(schema2, "object")) { + const branches = schemaBranchesOf(schema2); + if (branches?.length === 1) { + schema2 = branches[0]; + kind = schemaKindOf(schema2); + } + } + if (isNode(schema2) && schema2.kind === kind) + return schema2; + const impl = nodeImplementationsByKind[kind]; + const normalizedSchema = impl.normalize?.(schema2, this) ?? schema2; + if (isNode(normalizedSchema)) { + return normalizedSchema.kind === kind ? normalizedSchema : throwMismatchedNodeRootError(kind, normalizedSchema.kind); + } + return { + ...opts, + $: this, + kind, + def: normalizedSchema, + prefix: opts.alias ?? kind + }; + } + bindReference(reference2) { + let bound; + if (isNode(reference2)) { + bound = reference2.$ === this ? reference2 : new reference2.constructor(reference2.attachments, this); + } else { + bound = reference2.$ === this ? reference2 : new GenericRoot(reference2.params, reference2.bodyDef, reference2.$, this, reference2.hkt); + } + if (!this.resolved) { + Object.assign(this.referencesById, bound.referencesById); + } + return bound; + } + resolveRoot(name) { + return this.maybeResolveRoot(name) ?? throwParseError2(writeUnresolvableMessage(name)); + } + maybeResolveRoot(name) { + const result = this.maybeResolve(name); + if (hasArkKind(result, "generic")) + return; + return result; + } + /** If name is a valid reference to a submodule alias, return its resolution */ + maybeResolveSubalias(name) { + return maybeResolveSubalias(this.aliases, name) ?? maybeResolveSubalias(this.ambient, name); + } + get ambient() { + return $ark.ambient; + } + maybeResolve(name) { + const cached4 = this.resolutions[name]; + if (cached4) { + if (typeof cached4 !== "string") + return this.bindReference(cached4); + const v = nodesByRegisteredId[cached4]; + if (hasArkKind(v, "root")) + return this.resolutions[name] = v; + if (hasArkKind(v, "context")) { + if (v.phase === "resolving") { + return this.node("alias", { reference: `$${name}` }, { prereduced: true }); + } + if (v.phase === "resolved") { + return throwInternalError2(`Unexpected resolved context for was uncached by its scope: ${printable2(v)}`); + } + v.phase = "resolving"; + const node2 = this.bindReference(this.parseOwnDefinitionFormat(v.def, v)); + v.phase = "resolved"; + nodesByRegisteredId[node2.id] = node2; + nodesByRegisteredId[v.id] = node2; + return this.resolutions[name] = node2; + } + return throwInternalError2(`Unexpected nodesById entry for ${cached4}: ${printable2(v)}`); + } + let def = this.aliases[name] ?? this.ambient?.[name]; + if (!def) + return this.maybeResolveSubalias(name); + def = this.normalizeRootScopeValue(def); + if (hasArkKind(def, "generic")) + return this.resolutions[name] = this.bindReference(def); + if (hasArkKind(def, "module")) { + if (!def.root) + throwParseError2(writeMissingSubmoduleAccessMessage(name)); + return this.resolutions[name] = this.bindReference(def.root); + } + return this.resolutions[name] = this.parse(def, { + alias: name + }); + } + createParseContext(input) { + const id = input.id ?? registerNodeId(input.prefix); + return nodesByRegisteredId[id] = Object.assign(input, { + [arkKind]: "context", + $: this, + id, + phase: "unresolved" + }); + } + traversal(root2) { + return new Traversal(root2, this.resolvedConfig); + } + import(...names) { + return new RootModule(flatMorph2(this.export(...names), (alias, value2) => [ + `#${alias}`, + value2 + ])); + } + precompilation; + _exportedResolutions; + _exports; + export(...names) { + if (!this._exports) { + this._exports = {}; + for (const name of this.exportedNames) { + const def = this.aliases[name]; + this._exports[name] = hasArkKind(def, "module") ? bindModule(def, this) : bootstrapAliasReferences(this.maybeResolve(name)); + } + for (const node2 of this.lazyResolutions) + node2.resolution; + this._exportedResolutions = resolutionsOfModule(this, this._exports); + this._json = resolutionsToJson(this._exportedResolutions); + Object.assign(this.resolutions, this._exportedResolutions); + this.references = Object.values(this.referencesById); + if (!this.resolvedConfig.jitless) { + const precompiler = precompileReferences(this.references); + this.precompilation = precompiler.write(rootScopeFnName, 4); + bindPrecompilation(this.references, precompiler); + } + this.resolved = true; + } + const namesToExport = names.length ? names : this.exportedNames; + return new RootModule(flatMorph2(namesToExport, (_, name) => [ + name, + this._exports[name] + ])); + } + resolve(name) { + return this.export()[name]; + } + node = (kinds, nodeSchema, opts = {}) => { + const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts); + if (isNode(ctxOrNode)) + return this.bindReference(ctxOrNode); + const ctx = this.createParseContext(ctxOrNode); + const node2 = parseNode(ctx); + const bound = this.bindReference(node2); + return nodesByRegisteredId[ctx.id] = bound; + }; + parse = (def, opts = {}) => this.finalize(this.parseDefinition(def, opts)); + parseDefinition(def, opts = {}) { + if (hasArkKind(def, "root")) + return this.bindReference(def); + const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts); + if (hasArkKind(ctxInputOrNode, "root")) + return this.bindReference(ctxInputOrNode); + const ctx = this.createParseContext(ctxInputOrNode); + nodesByRegisteredId[ctx.id] = ctx; + let node2 = this.bindReference(this.parseOwnDefinitionFormat(def, ctx)); + if (node2.isCyclic) + node2 = withId(node2, ctx.id); + nodesByRegisteredId[ctx.id] = node2; + return node2; + } + finalize(node2) { + bootstrapAliasReferences(node2); + if (!node2.precompilation && !this.resolvedConfig.jitless) + precompile(node2.references); + return node2; + } + }; + SchemaScope = class extends BaseScope { + parseOwnDefinitionFormat(def, ctx) { + return parseNode(ctx); + } + preparseOwnDefinitionFormat(schema2, opts) { + return this.preparseNode(schemaKindOf(schema2), schema2, opts); + } + preparseOwnAliasEntry(k, v) { + return [k, v]; + } + normalizeRootScopeValue(v) { + return v; + } + }; + bootstrapAliasReferences = (resolution) => { + const aliases = resolution.references.filter((node2) => node2.hasKind("alias")); + for (const aliasNode of aliases) { + Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById); + for (const ref of resolution.references) { + if (aliasNode.id in ref.referencesById) + Object.assign(ref.referencesById, aliasNode.referencesById); + } + } + return resolution; + }; + resolutionsToJson = (resolutions) => flatMorph2(resolutions, (k, v) => [ + k, + hasArkKind(v, "root") || hasArkKind(v, "generic") ? v.json : hasArkKind(v, "module") ? resolutionsToJson(v) : throwInternalError2(`Unexpected resolution ${printable2(v)}`) + ]); + maybeResolveSubalias = (base, name) => { + const dotIndex = name.indexOf("."); + if (dotIndex === -1) + return; + const dotPrefix = name.slice(0, dotIndex); + const prefixSchema = base[dotPrefix]; + if (prefixSchema === void 0) + return; + if (!hasArkKind(prefixSchema, "module")) + return throwParseError2(writeNonSubmoduleDotMessage(dotPrefix)); + const subalias = name.slice(dotIndex + 1); + const resolution = prefixSchema[subalias]; + if (resolution === void 0) + return maybeResolveSubalias(prefixSchema, subalias); + if (hasArkKind(resolution, "root") || hasArkKind(resolution, "generic")) + return resolution; + if (hasArkKind(resolution, "module")) { + return resolution.root ?? throwParseError2(writeMissingSubmoduleAccessMessage(name)); + } + throwInternalError2(`Unexpected resolution for alias '${name}': ${printable2(resolution)}`); + }; + schemaScope = (aliases, config2) => new SchemaScope(aliases, config2); + rootSchemaScope = new SchemaScope({}); + resolutionsOfModule = ($2, typeSet) => { + const result = {}; + for (const k in typeSet) { + const v = typeSet[k]; + if (hasArkKind(v, "module")) { + const innerResolutions = resolutionsOfModule($2, v); + const prefixedResolutions = flatMorph2(innerResolutions, (innerK, innerV) => [`${k}.${innerK}`, innerV]); + Object.assign(result, prefixedResolutions); + } else if (hasArkKind(v, "root") || hasArkKind(v, "generic")) + result[k] = v; + else + throwInternalError2(`Unexpected scope resolution ${printable2(v)}`); + } + return result; + }; + writeUnresolvableMessage = (token) => `'${token}' is unresolvable`; + writeNonSubmoduleDotMessage = (name) => `'${name}' must reference a module to be accessed using dot syntax`; + writeMissingSubmoduleAccessMessage = (name) => `Reference to submodule '${name}' must specify an alias`; + rootSchemaScope.export(); + rootSchema = rootSchemaScope.schema; + node = rootSchemaScope.node; + defineSchema = rootSchemaScope.defineSchema; + genericNode = rootSchemaScope.generic; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/shared.js +var arrayIndexSource, arrayIndexMatcher, arrayIndexMatcherReference; +var init_shared = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/shared.js"() { + init_registry2(); + arrayIndexSource = `^(?:0|[1-9]\\d*)$`; + arrayIndexMatcher = new RegExp(arrayIndexSource); + arrayIndexMatcherReference = registeredReference(arrayIndexMatcher); + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/intrinsic.js +var intrinsicBases, intrinsicRoots, intrinsicJson, intrinsic; +var init_intrinsic = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/intrinsic.js"() { + init_scope(); + init_registry2(); + init_shared(); + intrinsicBases = schemaScope({ + bigint: "bigint", + // since we know this won't be reduced, it can be safely cast to a union + boolean: [{ unit: false }, { unit: true }], + false: { unit: false }, + never: [], + null: { unit: null }, + number: "number", + object: "object", + string: "string", + symbol: "symbol", + true: { unit: true }, + unknown: {}, + undefined: { unit: void 0 }, + Array, + Date + }, { prereducedAliases: true }).export(); + $ark.intrinsic = { ...intrinsicBases }; + intrinsicRoots = schemaScope({ + integer: { + domain: "number", + divisor: 1 + }, + lengthBoundable: ["string", Array], + key: ["string", "symbol"], + nonNegativeIntegerString: { domain: "string", pattern: arrayIndexSource } + }, { prereducedAliases: true }).export(); + Object.assign($ark.intrinsic, intrinsicRoots); + intrinsicJson = schemaScope({ + jsonPrimitive: [ + "string", + "number", + { unit: true }, + { unit: false }, + { unit: null } + ], + jsonObject: { + domain: "object", + index: { + signature: "string", + value: "$jsonData" + } + }, + jsonData: ["$jsonPrimitive", "$jsonObject"] + }, { prereducedAliases: true }).export(); + intrinsic = { + ...intrinsicBases, + ...intrinsicRoots, + ...intrinsicJson, + emptyStructure: node("structure", {}, { prereduced: true }) + }; + $ark.intrinsic = { ...intrinsic }; + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/declare.js +var init_declare = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/declare.js"() { + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/jsonSchema.js +var init_jsonSchema = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/jsonSchema.js"() { + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/standardSchema.js +var init_standardSchema = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/standardSchema.js"() { + } +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/index.js +var init_out2 = __esm({ + "node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/index.js"() { + init_config(); + init_constraint(); + init_generic(); + init_intrinsic(); + init_kinds2(); + init_module(); + init_node(); + init_parse(); + init_predicate(); + init_after(); + init_before(); + init_divisor(); + init_exactLength(); + init_kinds(); + init_max(); + init_maxLength(); + init_min(); + init_minLength(); + init_pattern(); + init_range(); + init_domain2(); + init_intersection(); + init_morph(); + init_proto(); + init_root(); + init_union(); + init_unit(); + init_scope(); + init_compile(); + init_declare(); + init_disjoint(); + init_errors2(); + init_implement(); + init_intersections2(); + init_jsonSchema(); + init_registry2(); + init_standardSchema(); + init_toJsonSchema(); + init_traversal(); + init_utils(); + init_structure(); + init_optional(); + init_prop(); + init_required(); + init_sequence(); + init_structure2(); + init_out(); + } +}); + +// node_modules/.pnpm/arkregex@0.0.4/node_modules/arkregex/out/regex.js +var regex; +var init_regex = __esm({ + "node_modules/.pnpm/arkregex@0.0.4/node_modules/arkregex/out/regex.js"() { + regex = ((src, flags) => new RegExp(src, flags)); + Object.assign(regex, { as: regex }); + } +}); + +// node_modules/.pnpm/arkregex@0.0.4/node_modules/arkregex/out/index.js +var init_out3 = __esm({ + "node_modules/.pnpm/arkregex@0.0.4/node_modules/arkregex/out/index.js"() { + init_regex(); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/config.js +var configure; +var init_config2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/config.js"() { + init_config(); + configure = configureSchema; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/date.js +var isDateLiteral, isValidDate, extractDateLiteralSource, writeInvalidDateMessage, tryParseDate, maybeParseDate; +var init_date = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/date.js"() { + init_out(); + isDateLiteral = (value2) => typeof value2 === "string" && value2[0] === "d" && (value2[1] === "'" || value2[1] === '"') && value2[value2.length - 1] === value2[1]; + isValidDate = (d) => d.toString() !== "Invalid Date"; + extractDateLiteralSource = (literal) => literal.slice(2, -1); + writeInvalidDateMessage = (source) => `'${source}' could not be parsed by the Date constructor`; + tryParseDate = (source, errorOnFail) => maybeParseDate(source, errorOnFail); + maybeParseDate = (source, errorOnFail) => { + const stringParsedDate = new Date(source); + if (isValidDate(stringParsedDate)) + return stringParsedDate; + const epochMillis = tryParseNumber(source); + if (epochMillis !== void 0) { + const numberParsedDate = new Date(epochMillis); + if (isValidDate(numberParsedDate)) + return numberParsedDate; + } + return errorOnFail ? throwParseError2(errorOnFail === true ? writeInvalidDateMessage(source) : errorOnFail) : void 0; + }; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/enclosed.js +var regexExecArray, parseEnclosed, enclosingQuote, enclosingChar, enclosingLiteralTokens, enclosingRegexTokens, enclosingTokens, untilLookaheadIsClosing, enclosingCharDescriptions, writeUnterminatedEnclosedMessage; +var init_enclosed = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/enclosed.js"() { + init_out2(); + init_out(); + init_date(); + regexExecArray = rootSchema({ + proto: "Array", + sequence: "string", + required: { + key: "groups", + value: ["object", { unit: void 0 }] + } + }); + parseEnclosed = (s, enclosing) => { + const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]); + if (s.scanner.lookahead === "") + return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing)); + s.scanner.shift(); + if (enclosing in enclosingRegexTokens) { + let regex3; + try { + regex3 = new RegExp(enclosed); + } catch (e) { + throwParseError2(String(e)); + } + s.root = s.ctx.$.node("intersection", { + domain: "string", + pattern: enclosed + }, { prereduced: true }); + if (enclosing === "x/") { + s.root = s.ctx.$.node("morph", { + in: s.root, + morphs: (s2) => regex3.exec(s2), + declaredOut: regexExecArray + }); + } + } else if (isKeyOf2(enclosing, enclosingQuote)) + s.root = s.ctx.$.node("unit", { unit: enclosed }); + else { + const date2 = tryParseDate(enclosed, writeInvalidDateMessage(enclosed)); + s.root = s.ctx.$.node("unit", { meta: enclosed, unit: date2 }); + } + }; + enclosingQuote = { + "'": 1, + '"': 1 + }; + enclosingChar = { + "/": 1, + "'": 1, + '"': 1 + }; + enclosingLiteralTokens = { + "d'": "'", + 'd"': '"', + "'": "'", + '"': '"' + }; + enclosingRegexTokens = { + "/": "/", + "x/": "/" + }; + enclosingTokens = { + ...enclosingLiteralTokens, + ...enclosingRegexTokens + }; + untilLookaheadIsClosing = { + "'": (scanner) => scanner.lookahead === `'`, + '"': (scanner) => scanner.lookahead === `"`, + "/": (scanner) => scanner.lookahead === `/` + }; + enclosingCharDescriptions = { + '"': "double-quote", + "'": "single-quote", + "/": "forward slash" + }; + writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/ast/validate.js +var writePrefixedPrivateReferenceMessage, shallowOptionalMessage, shallowDefaultableMessage; +var init_validate = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/ast/validate.js"() { + writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`; + shallowOptionalMessage = "Optional definitions like 'string?' are only valid as properties in an object or tuple"; + shallowDefaultableMessage = "Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple"; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/tokens.js +var terminatingChars, lookaheadIsFinalizing; +var init_tokens = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/tokens.js"() { + init_out(); + terminatingChars = { + "<": 1, + ">": 1, + "=": 1, + "|": 1, + "&": 1, + ")": 1, + "[": 1, + "%": 1, + ",": 1, + ":": 1, + "?": 1, + "#": 1, + ...whitespaceChars2 + }; + lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ? unscanned[0] === "=" ? ( + // >== would only occur in an expression like Array==5 + // otherwise, >= would only occur as part of a bound like number>=5 + unscanned[1] === "=" + ) : unscanned.trimStart() === "" || isKeyOf2(unscanned.trimStart()[0], terminatingChars) : lookahead === "=" ? unscanned[0] !== "=" : lookahead === "," || lookahead === "?"; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/genericArgs.js +var parseGenericArgs, _parseGenericArgs, writeInvalidGenericArgCountMessage; +var init_genericArgs = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/genericArgs.js"() { + init_out(); + parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []); + _parseGenericArgs = (name, g, s, argNodes) => { + const argState = s.parseUntilFinalizer(); + argNodes.push(argState.root); + if (argState.finalizer === ">") { + if (argNodes.length !== g.params.length) { + return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map((arg) => arg.expression))); + } + return argNodes; + } + if (argState.finalizer === ",") + return _parseGenericArgs(name, g, s, argNodes); + return argState.error(writeUnclosedGroupMessage(">")); + }; + writeInvalidGenericArgCountMessage = (name, params, argDefs) => `${name}<${params.join(", ")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? "" : `: ${argDefs.join(", ")}`})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/unenclosed.js +var parseUnenclosed, parseGenericInstantiation, unenclosedToNode, maybeParseReference, maybeParseUnenclosedLiteral, writeMissingOperandMessage, writeMissingRightOperandMessage, writeExpressionExpectedMessage; +var init_unenclosed = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/unenclosed.js"() { + init_out2(); + init_out(); + init_validate(); + init_tokens(); + init_genericArgs(); + parseUnenclosed = (s) => { + const token = s.scanner.shiftUntilLookahead(terminatingChars); + if (token === "keyof") + s.addPrefix("keyof"); + else + s.root = unenclosedToNode(s, token); + }; + parseGenericInstantiation = (name, g, s) => { + s.scanner.shiftUntilNonWhitespace(); + const lookahead = s.scanner.shift(); + if (lookahead !== "<") + return s.error(writeInvalidGenericArgCountMessage(name, g.names, [])); + const parsedArgs = parseGenericArgs(name, g, s); + return g(...parsedArgs); + }; + unenclosedToNode = (s, token) => maybeParseReference(s, token) ?? maybeParseUnenclosedLiteral(s, token) ?? s.error(token === "" ? s.scanner.lookahead === "#" ? writePrefixedPrivateReferenceMessage(s.shiftedBy(1).scanner.shiftUntilLookahead(terminatingChars)) : writeMissingOperandMessage(s) : writeUnresolvableMessage(token)); + maybeParseReference = (s, token) => { + if (s.ctx.args?.[token]) { + const arg = s.ctx.args[token]; + if (typeof arg !== "string") + return arg; + return s.ctx.$.node("alias", { reference: arg }, { prereduced: true }); + } + const resolution = s.ctx.$.maybeResolve(token); + if (hasArkKind(resolution, "root")) + return resolution; + if (resolution === void 0) + return; + if (hasArkKind(resolution, "generic")) + return parseGenericInstantiation(token, resolution, s); + return throwParseError2(`Unexpected resolution ${printable2(resolution)}`); + }; + maybeParseUnenclosedLiteral = (s, token) => { + const maybeNumber = tryParseWellFormedNumber(token); + if (maybeNumber !== void 0) + return s.ctx.$.node("unit", { unit: maybeNumber }); + const maybeBigint = tryParseWellFormedBigint(token); + if (maybeBigint !== void 0) + return s.ctx.$.node("unit", { unit: maybeBigint }); + }; + writeMissingOperandMessage = (s) => { + const operator = s.previousOperator(); + return operator ? writeMissingRightOperandMessage(operator, s.scanner.unscanned) : writeExpressionExpectedMessage(s.scanner.unscanned); + }; + writeMissingRightOperandMessage = (token, unscanned = "") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : ""}`; + writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : ""}`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/operand.js +var parseOperand; +var init_operand = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/operand.js"() { + init_out(); + init_enclosed(); + init_unenclosed(); + parseOperand = (s) => s.scanner.lookahead === "" ? s.error(writeMissingOperandMessage(s)) : s.scanner.lookahead === "(" ? s.shiftedBy(1).reduceGroupOpen() : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift()) : s.scanner.lookaheadIsIn(whitespaceChars2) ? parseOperand(s.shiftedBy(1)) : s.scanner.lookahead === "d" ? s.scanner.nextLookahead in enclosingQuote ? parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`) : parseUnenclosed(s) : s.scanner.lookahead === "x" ? s.scanner.nextLookahead === "/" ? s.shiftedBy(2) && parseEnclosed(s, "x/") : parseUnenclosed(s) : parseUnenclosed(s); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/reduce/shared.js +var minComparators, maxComparators, invertedComparators, writeOpenRangeMessage, writeUnpairableComparatorMessage, writeMultipleLeftBoundsMessage; +var init_shared2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/reduce/shared.js"() { + minComparators = { + ">": true, + ">=": true + }; + maxComparators = { + "<": true, + "<=": true + }; + invertedComparators = { + "<": ">", + ">": "<", + "<=": ">=", + ">=": "<=", + "==": "==" + }; + writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`; + writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`; + writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/bounds.js +var parseBound, comparatorStartChars, shiftComparator, getBoundKinds, openLeftBoundToRoot, parseRightBound, writeInvalidLimitMessage; +var init_bounds = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/bounds.js"() { + init_out2(); + init_out(); + init_shared2(); + init_date(); + parseBound = (s, start) => { + const comparator = shiftComparator(s, start); + if (s.root.hasKind("unit")) { + if (typeof s.root.unit === "number") { + s.reduceLeftBound(s.root.unit, comparator); + s.unsetRoot(); + return; + } + if (s.root.unit instanceof Date) { + const literal = `d'${s.root.description ?? s.root.unit.toISOString()}'`; + s.unsetRoot(); + s.reduceLeftBound(literal, comparator); + return; + } + } + return parseRightBound(s, comparator); + }; + comparatorStartChars = { + "<": 1, + ">": 1, + "=": 1 + }; + shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}` : start; + getBoundKinds = (comparator, limit, root2, boundKind) => { + if (root2.extends($ark.intrinsic.number)) { + if (typeof limit !== "number") { + return throwParseError2(writeInvalidLimitMessage(comparator, limit, boundKind)); + } + return comparator === "==" ? ["min", "max"] : comparator[0] === ">" ? ["min"] : ["max"]; + } + if (root2.extends($ark.intrinsic.lengthBoundable)) { + if (typeof limit !== "number") { + return throwParseError2(writeInvalidLimitMessage(comparator, limit, boundKind)); + } + return comparator === "==" ? ["exactLength"] : comparator[0] === ">" ? ["minLength"] : ["maxLength"]; + } + if (root2.extends($ark.intrinsic.Date)) { + return comparator === "==" ? ["after", "before"] : comparator[0] === ">" ? ["after"] : ["before"]; + } + return throwParseError2(writeUnboundableMessage(root2.expression)); + }; + openLeftBoundToRoot = (leftBound) => ({ + rule: isDateLiteral(leftBound.limit) ? extractDateLiteralSource(leftBound.limit) : leftBound.limit, + exclusive: leftBound.comparator.length === 1 + }); + parseRightBound = (s, comparator) => { + const previousRoot = s.unsetRoot(); + const previousScannerIndex = s.scanner.location; + s.parseOperand(); + const limitNode = s.unsetRoot(); + const limitToken = s.scanner.sliceChars(previousScannerIndex, s.scanner.location); + s.root = previousRoot; + if (!limitNode.hasKind("unit") || typeof limitNode.unit !== "number" && !(limitNode.unit instanceof Date)) + return s.error(writeInvalidLimitMessage(comparator, limitToken, "right")); + const limit = limitNode.unit; + const exclusive = comparator.length === 1; + const boundKinds = getBoundKinds(comparator, typeof limit === "number" ? limit : limitToken, previousRoot, "right"); + for (const kind of boundKinds) { + s.constrainRoot(kind, comparator === "==" ? { rule: limit } : { rule: limit, exclusive }); + } + if (!s.branches.leftBound) + return; + if (!isKeyOf2(comparator, maxComparators)) + return s.error(writeUnpairableComparatorMessage(comparator)); + const lowerBoundKind = getBoundKinds(s.branches.leftBound.comparator, s.branches.leftBound.limit, previousRoot, "left"); + s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.leftBound)); + s.branches.leftBound = null; + }; + writeInvalidLimitMessage = (comparator, limit, boundKind) => `Comparator ${boundKind === "left" ? invertedComparators[comparator] : comparator} must be ${boundKind === "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/brand.js +var parseBrand; +var init_brand = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/brand.js"() { + init_tokens(); + parseBrand = (s) => { + s.scanner.shiftUntilNonWhitespace(); + const brandName = s.scanner.shiftUntilLookahead(terminatingChars); + s.root = s.root.brand(brandName); + }; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/divisor.js +var parseDivisor, writeInvalidDivisorMessage; +var init_divisor2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/divisor.js"() { + init_out(); + init_tokens(); + parseDivisor = (s) => { + s.scanner.shiftUntilNonWhitespace(); + const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars); + const divisor = tryParseInteger(divisorToken, { + errorOnFail: writeInvalidDivisorMessage(divisorToken) + }); + if (divisor === 0) + s.error(writeInvalidDivisorMessage(0)); + s.root = s.root.constrain("divisor", divisor); + }; + writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/operator.js +var parseOperator, writeUnexpectedCharacterMessage, incompleteArrayTokenMessage; +var init_operator = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/operator.js"() { + init_out(); + init_tokens(); + init_bounds(); + init_brand(); + init_divisor2(); + parseOperator = (s) => { + const lookahead = s.scanner.shift(); + return lookahead === "" ? s.finalize("") : lookahead === "[" ? s.scanner.shift() === "]" ? s.setRoot(s.root.array()) : s.error(incompleteArrayTokenMessage) : lookahead === "|" ? s.scanner.lookahead === ">" ? s.shiftedBy(1).pushRootToBranch("|>") : s.pushRootToBranch(lookahead) : lookahead === "&" ? s.pushRootToBranch(lookahead) : lookahead === ")" ? s.finalizeGroup() : lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ? s.finalize(lookahead) : isKeyOf2(lookahead, comparatorStartChars) ? parseBound(s, lookahead) : lookahead === "%" ? parseDivisor(s) : lookahead === "#" ? parseBrand(s) : lookahead in whitespaceChars2 ? parseOperator(s) : s.error(writeUnexpectedCharacterMessage(lookahead)); + }; + writeUnexpectedCharacterMessage = (char, shouldBe = "") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`; + incompleteArrayTokenMessage = `Missing expected ']'`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/default.js +var parseDefault, writeNonLiteralDefaultMessage; +var init_default = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/default.js"() { + parseDefault = (s) => { + const baseNode = s.unsetRoot(); + s.parseOperand(); + const defaultNode = s.unsetRoot(); + if (!defaultNode.hasKind("unit")) + return s.error(writeNonLiteralDefaultMessage(defaultNode.expression)); + const defaultValue = defaultNode.unit instanceof Date ? () => new Date(defaultNode.unit) : defaultNode.unit; + return [baseNode, "=", defaultValue]; + }; + writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/string.js +var parseString, fullStringParse, parseUntilFinalizer, next; +var init_string = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/string.js"() { + init_out(); + init_dynamic(); + init_default(); + init_operator(); + parseString = (def, ctx) => { + const aliasResolution = ctx.$.maybeResolveRoot(def); + if (aliasResolution) + return aliasResolution; + if (def.endsWith("[]")) { + const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2)); + if (possibleElementResolution) + return possibleElementResolution.array(); + } + const s = new RuntimeState(new Scanner(def), ctx); + const node2 = fullStringParse(s); + if (s.finalizer === ">") + throwParseError2(writeUnexpectedCharacterMessage(">")); + return node2; + }; + fullStringParse = (s) => { + s.parseOperand(); + let result = parseUntilFinalizer(s).root; + if (!result) { + return throwInternalError2(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`); + } + if (s.finalizer === "=") + result = parseDefault(s); + else if (s.finalizer === "?") + result = [result, "?"]; + s.scanner.shiftUntilNonWhitespace(); + if (s.scanner.lookahead) { + throwParseError2(writeUnexpectedCharacterMessage(s.scanner.lookahead)); + } + return result; + }; + parseUntilFinalizer = (s) => { + while (s.finalizer === void 0) + next(s); + return s; + }; + next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand(); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/reduce/dynamic.js +var RuntimeState; +var init_dynamic = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/reduce/dynamic.js"() { + init_out(); + init_operand(); + init_operator(); + init_string(); + init_shared2(); + RuntimeState = class _RuntimeState { + root; + branches = { + prefixes: [], + leftBound: null, + intersection: null, + union: null, + pipe: null + }; + finalizer; + groups = []; + scanner; + ctx; + constructor(scanner, ctx) { + this.scanner = scanner; + this.ctx = ctx; + } + error(message) { + return throwParseError2(message); + } + hasRoot() { + return this.root !== void 0; + } + setRoot(root2) { + this.root = root2; + } + unsetRoot() { + const value2 = this.root; + this.root = void 0; + return value2; + } + constrainRoot(...args3) { + this.root = this.root.constrain(args3[0], args3[1]); + } + finalize(finalizer) { + if (this.groups.length) + return this.error(writeUnclosedGroupMessage(")")); + this.finalizeBranches(); + this.finalizer = finalizer; + } + reduceLeftBound(limit, comparator) { + const invertedComparator = invertedComparators[comparator]; + if (!isKeyOf2(invertedComparator, minComparators)) + return this.error(writeUnpairableComparatorMessage(comparator)); + if (this.branches.leftBound) { + return this.error(writeMultipleLeftBoundsMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator, limit, invertedComparator)); + } + this.branches.leftBound = { + comparator: invertedComparator, + limit + }; + } + finalizeBranches() { + this.assertRangeUnset(); + if (this.branches.pipe) { + this.pushRootToBranch("|>"); + this.root = this.branches.pipe; + return; + } + if (this.branches.union) { + this.pushRootToBranch("|"); + this.root = this.branches.union; + return; + } + if (this.branches.intersection) { + this.pushRootToBranch("&"); + this.root = this.branches.intersection; + return; + } + this.applyPrefixes(); + } + finalizeGroup() { + this.finalizeBranches(); + const topBranchState = this.groups.pop(); + if (!topBranchState) { + return this.error(writeUnmatchedGroupCloseMessage(")", this.scanner.unscanned)); + } + this.branches = topBranchState; + } + addPrefix(prefix) { + this.branches.prefixes.push(prefix); + } + applyPrefixes() { + while (this.branches.prefixes.length) { + const lastPrefix = this.branches.prefixes.pop(); + this.root = lastPrefix === "keyof" ? this.root.keyof() : throwInternalError2(`Unexpected prefix '${lastPrefix}'`); + } + } + pushRootToBranch(token) { + this.assertRangeUnset(); + this.applyPrefixes(); + const root2 = this.root; + this.root = void 0; + this.branches.intersection = this.branches.intersection?.rawAnd(root2) ?? root2; + if (token === "&") + return; + this.branches.union = this.branches.union?.rawOr(this.branches.intersection) ?? this.branches.intersection; + this.branches.intersection = null; + if (token === "|") + return; + this.branches.pipe = this.branches.pipe?.rawPipeOnce(this.branches.union) ?? this.branches.union; + this.branches.union = null; + } + parseUntilFinalizer() { + return parseUntilFinalizer(new _RuntimeState(this.scanner, this.ctx)); + } + parseOperator() { + return parseOperator(this); + } + parseOperand() { + return parseOperand(this); + } + assertRangeUnset() { + if (this.branches.leftBound) { + return this.error(writeOpenRangeMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator)); + } + } + reduceGroupOpen() { + this.groups.push(this.branches); + this.branches = { + prefixes: [], + leftBound: null, + union: null, + intersection: null, + pipe: null + }; + } + previousOperator() { + return this.branches.leftBound?.comparator ?? this.branches.prefixes[this.branches.prefixes.length - 1] ?? (this.branches.intersection ? "&" : this.branches.union ? "|" : this.branches.pipe ? "|>" : void 0); + } + shiftedBy(count) { + this.scanner.jumpForward(count); + return this; + } + }; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/generic.js +var emptyGenericParameterMessage, parseGenericParamName, extendsToken, _parseOptionalConstraint; +var init_generic2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/generic.js"() { + init_out2(); + init_out(); + init_dynamic(); + init_tokens(); + init_string(); + emptyGenericParameterMessage = "An empty string is not a valid generic parameter name"; + parseGenericParamName = (scanner, result, ctx) => { + scanner.shiftUntilNonWhitespace(); + const name = scanner.shiftUntilLookahead(terminatingChars); + if (name === "") { + if (scanner.lookahead === "" && result.length) + return result; + return throwParseError2(emptyGenericParameterMessage); + } + scanner.shiftUntilNonWhitespace(); + return _parseOptionalConstraint(scanner, name, result, ctx); + }; + extendsToken = "extends "; + _parseOptionalConstraint = (scanner, name, result, ctx) => { + scanner.shiftUntilNonWhitespace(); + if (scanner.unscanned.startsWith(extendsToken)) + scanner.jumpForward(extendsToken.length); + else { + if (scanner.lookahead === ",") + scanner.shift(); + result.push(name); + return parseGenericParamName(scanner, result, ctx); + } + const s = parseUntilFinalizer(new RuntimeState(scanner, ctx)); + result.push([name, s.root]); + return parseGenericParamName(scanner, result, ctx); + }; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/fn.js +var InternalFnParser, InternalTypedFn, badFnReturnTypeMessage; +var init_fn = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/fn.js"() { + init_out(); + InternalFnParser = class extends Callable { + constructor($2) { + const attach = { + $: $2, + raw: $2.fn + }; + super((...signature) => { + const returnOperatorIndex = signature.indexOf(":"); + const lastParamIndex = returnOperatorIndex === -1 ? signature.length - 1 : returnOperatorIndex - 1; + const paramDefs = signature.slice(0, lastParamIndex + 1); + const paramTuple = $2.parse(paramDefs).assertHasKind("intersection"); + let returnType = $2.intrinsic.unknown; + if (returnOperatorIndex !== -1) { + if (returnOperatorIndex !== signature.length - 2) + return throwParseError2(badFnReturnTypeMessage); + returnType = $2.parse(signature[returnOperatorIndex + 1]); + } + return (impl) => new InternalTypedFn(impl, paramTuple, returnType); + }, { attach }); + } + }; + InternalTypedFn = class extends Callable { + raw; + params; + returns; + expression; + constructor(raw, params, returns) { + const typedName = `typed ${raw.name}`; + const typed = { + // assign to a key with the expected name to force it to be created that way + [typedName]: (...args3) => { + const validatedArgs = params.assert(args3); + const returned = raw(...validatedArgs); + return returns.assert(returned); + } + }[typedName]; + super(typed); + this.raw = raw; + this.params = params; + this.returns = returns; + let argsExpression = params.expression; + if (argsExpression[0] === "[" && argsExpression[argsExpression.length - 1] === "]") + argsExpression = argsExpression.slice(1, -1); + else if (argsExpression.endsWith("[]")) + argsExpression = `...${argsExpression}`; + this.expression = `(${argsExpression}) => ${returns?.expression ?? "unknown"}`; + } + }; + badFnReturnTypeMessage = `":" must be followed by exactly one return type e.g: +fn("string", ":", "number")(s => s.length)`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/match.js +var InternalMatchParser, InternalChainedMatchParser, throwOnDefault, chainedAtMessage, doubleAtMessage; +var init_match = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/match.js"() { + init_out2(); + init_out(); + InternalMatchParser = class extends Callable { + $; + constructor($2) { + super((...args3) => new InternalChainedMatchParser($2)(...args3), { + bind: $2 + }); + this.$ = $2; + } + in(def) { + return new InternalChainedMatchParser(this.$, def === void 0 ? void 0 : this.$.parse(def)); + } + at(key, cases) { + return new InternalChainedMatchParser(this.$).at(key, cases); + } + case(when, then) { + return new InternalChainedMatchParser(this.$).case(when, then); + } + }; + InternalChainedMatchParser = class extends Callable { + $; + in; + key; + branches = []; + constructor($2, In) { + super((cases) => this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.parse(k), v]))); + this.$ = $2; + this.in = In; + } + at(key, cases) { + if (this.key) + throwParseError2(doubleAtMessage); + if (this.branches.length) + throwParseError2(chainedAtMessage); + this.key = key; + return cases ? this.match(cases) : this; + } + case(def, resolver) { + return this.caseEntry(this.$.parse(def), resolver); + } + caseEntry(node2, resolver) { + const wrappableNode = this.key ? this.$.parse({ [this.key]: node2 }) : node2; + const branch = wrappableNode.pipe(resolver); + this.branches.push(branch); + return this; + } + match(cases) { + return this(cases); + } + strings(cases) { + return this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.node("unit", { unit: k }), v])); + } + caseEntries(entries) { + for (let i = 0; i < entries.length; i++) { + const [k, v] = entries[i]; + if (k === "default") { + if (i !== entries.length - 1) { + throwParseError2(`default may only be specified as the last key of a switch definition`); + } + return this.default(v); + } + if (typeof v !== "function") { + return throwParseError2(`Value for case "${k}" must be a function (was ${domainOf2(v)})`); + } + this.caseEntry(k, v); + } + return this; + } + default(defaultCase) { + if (typeof defaultCase === "function") + this.case(intrinsic.unknown, defaultCase); + const schema2 = { + branches: this.branches, + ordered: true + }; + if (defaultCase === "never" || defaultCase === "assert") + schema2.meta = { onFail: throwOnDefault }; + const cases = this.$.node("union", schema2); + if (!this.in) + return this.$.finalize(cases); + let inputValidatedCases = this.in.pipe(cases); + if (defaultCase === "never" || defaultCase === "assert") { + inputValidatedCases = inputValidatedCases.configureReferences({ + onFail: throwOnDefault + }, "self"); + } + return this.$.finalize(inputValidatedCases); + } + }; + throwOnDefault = (errors) => errors.throw(); + chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in().at('bar')`; + doubleAtMessage = `At most one key matcher may be specified per expression`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/property.js +var parseProperty, invalidOptionalKeyKindMessage, invalidDefaultableKeyKindMessage; +var init_property = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/property.js"() { + init_out(); + init_definition(); + parseProperty = (def, ctx) => { + if (isArray(def)) { + if (def[1] === "=") + return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "=", def[2]]; + if (def[1] === "?") + return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "?"]; + } + return parseInnerDefinition(def, ctx); + }; + invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`; + invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/objectLiteral.js +var parseObjectLiteral, appendNamedProp, writeInvalidUndeclaredBehaviorMessage, nonLeadingSpreadError, preparseKey, writeInvalidSpreadTypeMessage; +var init_objectLiteral = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/objectLiteral.js"() { + init_out2(); + init_out(); + init_property(); + parseObjectLiteral = (def, ctx) => { + let spread; + const structure = {}; + const defEntries = stringAndSymbolicEntriesOf2(def); + for (const [k, v] of defEntries) { + const parsedKey = preparseKey(k); + if (parsedKey.kind === "spread") { + if (!isEmptyObject2(structure)) + return throwParseError2(nonLeadingSpreadError); + const operand = ctx.$.parseOwnDefinitionFormat(v, ctx); + if (operand.equals(intrinsic.object)) + continue; + if (!operand.hasKind("intersection") || // still error on attempts to spread proto nodes like ...Date + !operand.basis?.equals(intrinsic.object)) { + return throwParseError2(writeInvalidSpreadTypeMessage(operand.expression)); + } + spread = operand.structure; + continue; + } + if (parsedKey.kind === "undeclared") { + if (v !== "reject" && v !== "delete" && v !== "ignore") + throwParseError2(writeInvalidUndeclaredBehaviorMessage(v)); + structure.undeclared = v; + continue; + } + const parsedValue = parseProperty(v, ctx); + const parsedEntryKey = parsedKey; + if (parsedKey.kind === "required") { + if (!isArray(parsedValue)) { + appendNamedProp(structure, "required", { + key: parsedKey.normalized, + value: parsedValue + }, ctx); + } else { + appendNamedProp(structure, "optional", parsedValue[1] === "=" ? { + key: parsedKey.normalized, + value: parsedValue[0], + default: parsedValue[2] + } : { + key: parsedKey.normalized, + value: parsedValue[0] + }, ctx); + } + continue; + } + if (isArray(parsedValue)) { + if (parsedValue[1] === "?") + throwParseError2(invalidOptionalKeyKindMessage); + if (parsedValue[1] === "=") + throwParseError2(invalidDefaultableKeyKindMessage); + } + if (parsedKey.kind === "optional") { + appendNamedProp(structure, "optional", { + key: parsedKey.normalized, + value: parsedValue + }, ctx); + continue; + } + const signature = ctx.$.parseOwnDefinitionFormat(parsedEntryKey.normalized, ctx); + const normalized = normalizeIndex(signature, parsedValue, ctx.$); + if (normalized.index) + structure.index = append2(structure.index, normalized.index); + if (normalized.required) + structure.required = append2(structure.required, normalized.required); + } + const structureNode = ctx.$.node("structure", structure); + return ctx.$.parseSchema({ + domain: "object", + structure: spread?.merge(structureNode) ?? structureNode + }); + }; + appendNamedProp = (structure, kind, inner, ctx) => { + structure[kind] = append2( + // doesn't seem like this cast should be necessary + structure[kind], + ctx.$.node(kind, inner) + ); + }; + writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable2(actual)})`; + nonLeadingSpreadError = "Spread operator may only be used as the first key in an object"; + preparseKey = (key) => typeof key === "symbol" ? { kind: "required", normalized: key } : key[key.length - 1] === "?" ? key[key.length - 2] === Backslash2 ? { kind: "required", normalized: `${key.slice(0, -2)}?` } : { + kind: "optional", + normalized: key.slice(0, -1) + } : key[0] === "[" && key[key.length - 1] === "]" ? { kind: "index", normalized: key.slice(1, -1) } : key[0] === Backslash2 && key[1] === "[" && key[key.length - 1] === "]" ? { kind: "required", normalized: key.slice(1) } : key === "..." ? { kind: "spread" } : key === "+" ? { kind: "undeclared" } : { + kind: "required", + normalized: key === "\\..." ? "..." : key === "\\+" ? "+" : key + }; + writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/tupleExpressions.js +var maybeParseTupleExpression, parseKeyOfTuple, parseBranchTuple, parseArrayTuple, parseMorphTuple, writeMalformedFunctionalExpressionMessage, parseNarrowTuple, parseMetaTuple, defineIndexOneParsers, postfixParsers, infixParsers, indexOneParsers, isIndexOneExpression, defineIndexZeroParsers, indexZeroParsers, isIndexZeroExpression, writeInvalidConstructorMessage; +var init_tupleExpressions = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/tupleExpressions.js"() { + init_out2(); + init_out(); + init_validate(); + init_unenclosed(); + maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null; + parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof(); + parseBranchTuple = (def, ctx) => { + if (def[2] === void 0) + return throwParseError2(writeMissingRightOperandMessage(def[1], "")); + const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx); + const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx); + if (def[1] === "|") + return ctx.$.node("union", { branches: [l, r] }); + const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$); + if (result instanceof Disjoint) + return result.throw(); + return result; + }; + parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array(); + parseMorphTuple = (def, ctx) => { + if (typeof def[2] !== "function") { + return throwParseError2(writeMalformedFunctionalExpressionMessage("=>", def[2])); + } + return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]); + }; + writeMalformedFunctionalExpressionMessage = (operator, value2) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value2})`; + parseNarrowTuple = (def, ctx) => { + if (typeof def[2] !== "function") { + return throwParseError2(writeMalformedFunctionalExpressionMessage(":", def[2])); + } + return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]); + }; + parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]); + defineIndexOneParsers = (parsers) => parsers; + postfixParsers = defineIndexOneParsers({ + "[]": parseArrayTuple, + "?": () => throwParseError2(shallowOptionalMessage) + }); + infixParsers = defineIndexOneParsers({ + "|": parseBranchTuple, + "&": parseBranchTuple, + ":": parseNarrowTuple, + "=>": parseMorphTuple, + "|>": parseBranchTuple, + "@": parseMetaTuple, + // since object and tuple literals parse there via `parseProperty`, + // they must be shallow if parsed directly as a tuple expression + "=": () => throwParseError2(shallowDefaultableMessage) + }); + indexOneParsers = { ...postfixParsers, ...infixParsers }; + isIndexOneExpression = (def) => indexOneParsers[def[1]] !== void 0; + defineIndexZeroParsers = (parsers) => parsers; + indexZeroParsers = defineIndexZeroParsers({ + keyof: parseKeyOfTuple, + instanceof: (def, ctx) => { + if (typeof def[1] !== "function") { + return throwParseError2(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1]))); + } + const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError2(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor)))); + return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches }); + }, + "===": (def, ctx) => ctx.$.units(def.slice(1)) + }); + isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== void 0; + writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/tupleLiteral.js +var parseTupleLiteral, appendRequiredElement, appendOptionalElement, appendDefaultableElement, appendVariadicElement, appendSpreadBranch, writeNonArraySpreadMessage, multipleVariadicMesage, requiredPostOptionalMessage, optionalOrDefaultableAfterVariadicMessage, defaultablePostOptionalMessage; +var init_tupleLiteral = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/tupleLiteral.js"() { + init_out2(); + init_out(); + init_property(); + parseTupleLiteral = (def, ctx) => { + let sequences = [{}]; + let i = 0; + while (i < def.length) { + let spread = false; + if (def[i] === "..." && i < def.length - 1) { + spread = true; + i++; + } + const parsedProperty = parseProperty(def[i], ctx); + const [valueNode, operator, possibleDefaultValue] = !isArray(parsedProperty) ? [parsedProperty] : parsedProperty; + i++; + if (spread) { + if (!valueNode.extends($ark.intrinsic.Array)) + return throwParseError2(writeNonArraySpreadMessage(valueNode.expression)); + sequences = sequences.flatMap((base) => ( + // since appendElement mutates base, we have to shallow-ish clone it for each branch + valueNode.distribute((branch) => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)) + )); + } else { + sequences = sequences.map((base) => { + if (operator === "?") + return appendOptionalElement(base, valueNode); + if (operator === "=") + return appendDefaultableElement(base, valueNode, possibleDefaultValue); + return appendRequiredElement(base, valueNode); + }); + } + } + return ctx.$.parseSchema(sequences.map((sequence) => isEmptyObject2(sequence) ? { + proto: Array, + exactLength: 0 + } : { + proto: Array, + sequence + })); + }; + appendRequiredElement = (base, element) => { + if (base.defaultables || base.optionals) { + return throwParseError2(base.variadic ? ( + // e.g. [boolean = true, ...string[], number] + postfixAfterOptionalOrDefaultableMessage + ) : requiredPostOptionalMessage); + } + if (base.variadic) { + base.postfix = append2(base.postfix, element); + } else { + base.prefix = append2(base.prefix, element); + } + return base; + }; + appendOptionalElement = (base, element) => { + if (base.variadic) + return throwParseError2(optionalOrDefaultableAfterVariadicMessage); + base.optionals = append2(base.optionals, element); + return base; + }; + appendDefaultableElement = (base, element, value2) => { + if (base.variadic) + return throwParseError2(optionalOrDefaultableAfterVariadicMessage); + if (base.optionals) + return throwParseError2(defaultablePostOptionalMessage); + base.defaultables = append2(base.defaultables, [[element, value2]]); + return base; + }; + appendVariadicElement = (base, element) => { + if (base.postfix) + throwParseError2(multipleVariadicMesage); + if (base.variadic) { + if (!base.variadic.equals(element)) { + throwParseError2(multipleVariadicMesage); + } + } else { + base.variadic = element.internal; + } + return base; + }; + appendSpreadBranch = (base, branch) => { + const spread = branch.select({ method: "find", kind: "sequence" }); + if (!spread) { + return appendVariadicElement(base, $ark.intrinsic.unknown); + } + if (spread.prefix) + for (const node2 of spread.prefix) + appendRequiredElement(base, node2); + if (spread.optionals) + for (const node2 of spread.optionals) + appendOptionalElement(base, node2); + if (spread.variadic) + appendVariadicElement(base, spread.variadic); + if (spread.postfix) + for (const node2 of spread.postfix) + appendRequiredElement(base, node2); + return base; + }; + writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`; + multipleVariadicMesage = "A tuple may have at most one variadic element"; + requiredPostOptionalMessage = "A required element may not follow an optional element"; + optionalOrDefaultableAfterVariadicMessage = "An optional element may not follow a variadic element"; + defaultablePostOptionalMessage = "A defaultable element may not follow an optional element without a default"; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/definition.js +var parseCache, parseInnerDefinition, parseObject, parseStandardSchema, parseTuple, writeBadDefinitionTypeMessage; +var init_definition = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/definition.js"() { + init_out2(); + init_out(); + init_objectLiteral(); + init_string(); + init_tupleExpressions(); + init_tupleLiteral(); + parseCache = {}; + parseInnerDefinition = (def, ctx) => { + if (typeof def === "string") { + if (ctx.args && Object.keys(ctx.args).some((k) => def.includes(k))) { + return parseString(def, ctx); + } + const scopeCache = parseCache[ctx.$.name] ??= {}; + return scopeCache[def] ??= parseString(def, ctx); + } + return hasDomain2(def, "object") ? parseObject(def, ctx) : throwParseError2(writeBadDefinitionTypeMessage(domainOf2(def))); + }; + parseObject = (def, ctx) => { + const objectKind = objectKindOf2(def); + switch (objectKind) { + case void 0: + if (hasArkKind(def, "root")) + return def; + if ("~standard" in def) + return parseStandardSchema(def, ctx); + return parseObjectLiteral(def, ctx); + case "Array": + return parseTuple(def, ctx); + case "RegExp": + return ctx.$.node("intersection", { + domain: "string", + pattern: def + }, { prereduced: true }); + case "Function": { + const resolvedDef = isThunk(def) ? def() : def; + if (hasArkKind(resolvedDef, "root")) + return resolvedDef; + return throwParseError2(writeBadDefinitionTypeMessage("Function")); + } + default: + return throwParseError2(writeBadDefinitionTypeMessage(objectKind ?? printable2(def))); + } + }; + parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx2) => { + const result = def["~standard"].validate(v); + if (!result.issues) + return result.value; + for (const { message, path: path3 } of result.issues) { + if (path3) { + if (path3.length) { + ctx2.error({ + problem: uncapitalize(message), + relativePath: path3.map((k) => typeof k === "object" ? k.key : k) + }); + } else { + ctx2.error({ + message + }); + } + } else { + ctx2.error({ + message + }); + } + } + }); + parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx); + writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/type.js +var InternalTypeParser; +var init_type = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/type.js"() { + init_out2(); + init_out(); + InternalTypeParser = class extends Callable { + constructor($2) { + const attach = Object.assign( + { + errors: ArkErrors, + hkt: Hkt, + $: $2, + raw: $2.parse, + module: $2.constructor.module, + scope: $2.constructor.scope, + declare: $2.declare, + define: $2.define, + match: $2.match, + generic: $2.generic, + schema: $2.schema, + // this won't be defined during bootstrapping, but externally always will be + keywords: $2.ambient, + unit: $2.unit, + enumerated: $2.enumerated, + instanceOf: $2.instanceOf, + valueOf: $2.valueOf, + or: $2.or, + and: $2.and, + merge: $2.merge, + pipe: $2.pipe, + fn: $2.fn + }, + // also won't be defined during bootstrapping + $2.ambientAttachments + ); + super((...args3) => { + if (args3.length === 1) { + return $2.parse(args3[0]); + } + if (args3.length === 2 && typeof args3[0] === "string" && args3[0][0] === "<" && args3[0][args3[0].length - 1] === ">") { + const paramString = args3[0].slice(1, -1); + const params = $2.parseGenericParams(paramString, {}); + return new GenericRoot(params, args3[1], $2, $2, null); + } + return $2.parse(args3); + }, { + attach + }); + } + }; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/scope.js +var $arkTypeRegistry, InternalScope, scope, Scope; +var init_scope2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/scope.js"() { + init_out2(); + init_out(); + init_fn(); + init_generic2(); + init_match(); + init_validate(); + init_definition(); + init_type(); + $arkTypeRegistry = $ark; + InternalScope = class _InternalScope extends BaseScope { + get ambientAttachments() { + if (!$arkTypeRegistry.typeAttachments) + return; + return this.cacheGetter("ambientAttachments", flatMorph2($arkTypeRegistry.typeAttachments, (k, v) => [ + k, + this.bindReference(v) + ])); + } + preparseOwnAliasEntry(alias, def) { + const firstParamIndex = alias.indexOf("<"); + if (firstParamIndex === -1) { + if (hasArkKind(def, "module") || hasArkKind(def, "generic")) + return [alias, def]; + const qualifiedName = this.name === "ark" ? alias : alias === "root" ? this.name : `${this.name}.${alias}`; + const config2 = this.resolvedConfig.keywords?.[qualifiedName]; + if (config2) + def = [def, "@", config2]; + return [alias, def]; + } + if (alias[alias.length - 1] !== ">") { + throwParseError2(`'>' must be the last character of a generic declaration in a scope`); + } + const name = alias.slice(0, firstParamIndex); + const paramString = alias.slice(firstParamIndex + 1, -1); + return [ + name, + // use a thunk definition for the generic so that we can parse + // constraints within the current scope + () => { + const params = this.parseGenericParams(paramString, { alias: name }); + const generic2 = parseGeneric(params, def, this); + return generic2; + } + ]; + } + parseGenericParams(def, opts) { + return parseGenericParamName(new Scanner(def), [], this.createParseContext({ + ...opts, + def, + prefix: "generic" + })); + } + normalizeRootScopeValue(resolution) { + if (isThunk(resolution) && !hasArkKind(resolution, "generic")) + return resolution(); + return resolution; + } + preparseOwnDefinitionFormat(def, opts) { + return { + ...opts, + def, + prefix: opts.alias ?? "type" + }; + } + parseOwnDefinitionFormat(def, ctx) { + const isScopeAlias = ctx.alias && ctx.alias in this.aliases; + if (!isScopeAlias && !ctx.args) + ctx.args = { this: ctx.id }; + const result = parseInnerDefinition(def, ctx); + if (isArray(result)) { + if (result[1] === "=") + return throwParseError2(shallowDefaultableMessage); + if (result[1] === "?") + return throwParseError2(shallowOptionalMessage); + } + return result; + } + unit = (value2) => this.units([value2]); + valueOf = (tsEnum) => this.units(enumValues(tsEnum)); + enumerated = (...values) => this.units(values); + instanceOf = (ctor) => this.node("proto", { proto: ctor }, { prereduced: true }); + or = (...defs) => this.schema(defs.map((def) => this.parse(def))); + and = (...defs) => defs.reduce((node2, def) => node2.and(this.parse(def)), this.intrinsic.unknown); + merge = (...defs) => defs.reduce((node2, def) => node2.merge(this.parse(def)), this.intrinsic.object); + pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs); + fn = new InternalFnParser(this); + match = new InternalMatchParser(this); + declare = () => ({ + type: this.type + }); + define(def) { + return def; + } + type = new InternalTypeParser(this); + static scope = ((def, config2 = {}) => new _InternalScope(def, config2)); + static module = ((def, config2 = {}) => this.scope(def, config2).export()); + }; + scope = Object.assign(InternalScope.scope, { + define: (def) => def + }); + Scope = InternalScope; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/builtins.js +var MergeHkt, Merge, arkBuiltins; +var init_builtins = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/builtins.js"() { + init_out2(); + init_out(); + init_scope2(); + MergeHkt = class extends Hkt { + description = 'merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'; + }; + Merge = genericNode(["base", intrinsic.object], ["props", intrinsic.object])((args3) => args3.base.merge(args3.props), MergeHkt); + arkBuiltins = Scope.module({ + Key: intrinsic.key, + Merge + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/Array.js +var liftFromHkt, liftFrom, arkArray; +var init_Array = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/Array.js"() { + init_out2(); + init_out(); + init_scope2(); + liftFromHkt = class extends Hkt { + }; + liftFrom = genericNode("element")((args3) => { + const nonArrayElement = args3.element.exclude(intrinsic.Array); + const lifted = nonArrayElement.array(); + return nonArrayElement.rawOr(lifted).pipe(liftArray).distribute((branch) => branch.assertHasKind("morph").declareOut(lifted), rootSchema); + }, liftFromHkt); + arkArray = Scope.module({ + root: intrinsic.Array, + readonly: "root", + index: intrinsic.nonNegativeIntegerString, + liftFrom + }, { + name: "Array" + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/FormData.js +var value, parsedFormDataValue, parsed, arkFormData; +var init_FormData = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/FormData.js"() { + init_out2(); + init_out(); + init_scope2(); + value = rootSchema(["string", registry.FileConstructor]); + parsedFormDataValue = value.rawOr(value.array()); + parsed = rootSchema({ + meta: "an object representing parsed form data", + domain: "object", + index: { + signature: "string", + value: parsedFormDataValue + } + }); + arkFormData = Scope.module({ + root: ["instanceof", FormData], + value, + parsed, + parse: rootSchema({ + in: FormData, + morphs: (data) => { + const result = {}; + for (const [k, v] of data) { + if (k in result) { + const existing = result[k]; + if (typeof existing === "string" || existing instanceof registry.FileConstructor) + result[k] = [existing, v]; + else + existing.push(v); + } else + result[k] = v; + } + return result; + }, + declaredOut: parsed + }) + }, { + name: "FormData" + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/TypedArray.js +var TypedArray; +var init_TypedArray = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/TypedArray.js"() { + init_scope2(); + TypedArray = Scope.module({ + Int8: ["instanceof", Int8Array], + Uint8: ["instanceof", Uint8Array], + Uint8Clamped: ["instanceof", Uint8ClampedArray], + Int16: ["instanceof", Int16Array], + Uint16: ["instanceof", Uint16Array], + Int32: ["instanceof", Int32Array], + Uint32: ["instanceof", Uint32Array], + Float32: ["instanceof", Float32Array], + Float64: ["instanceof", Float64Array], + BigInt64: ["instanceof", BigInt64Array], + BigUint64: ["instanceof", BigUint64Array] + }, { + name: "TypedArray" + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/constructors.js +var omittedPrototypes, arkPrototypes; +var init_constructors = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/constructors.js"() { + init_out(); + init_scope2(); + init_Array(); + init_FormData(); + init_TypedArray(); + omittedPrototypes = { + Boolean: 1, + Number: 1, + String: 1 + }; + arkPrototypes = Scope.module({ + ...flatMorph2({ ...ecmascriptConstructors2, ...platformConstructors2 }, (k, v) => k in omittedPrototypes ? [] : [k, ["instanceof", v]]), + Array: arkArray, + TypedArray, + FormData: arkFormData + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/number.js +var epoch, integer, number; +var init_number = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/number.js"() { + init_out2(); + init_scope2(); + epoch = rootSchema({ + domain: { + domain: "number", + meta: "a number representing a Unix timestamp" + }, + divisor: { + rule: 1, + meta: `an integer representing a Unix timestamp` + }, + min: { + rule: -864e13, + meta: `a Unix timestamp after -8640000000000000` + }, + max: { + rule: 864e13, + meta: "a Unix timestamp before 8640000000000000" + }, + meta: "an integer representing a safe Unix timestamp" + }); + integer = rootSchema({ + domain: "number", + divisor: 1 + }); + number = Scope.module({ + root: intrinsic.number, + integer, + epoch, + safe: rootSchema({ + domain: { + domain: "number", + numberAllowsNaN: false + }, + min: Number.MIN_SAFE_INTEGER, + max: Number.MAX_SAFE_INTEGER + }), + NaN: ["===", Number.NaN], + Infinity: ["===", Number.POSITIVE_INFINITY], + NegativeInfinity: ["===", Number.NEGATIVE_INFINITY] + }, { + name: "number" + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/string.js +var regexStringNode, stringIntegerRoot, stringInteger, hex, base64, preformattedCapitalize, capitalize2, isLuhnValid, creditCardMatcher, creditCard, iso8601Matcher, isParsableDate, parsableDate, epochRoot, epoch2, isoRoot, iso, stringDate, email, ipv4Segment, ipv4Address, ipv4Matcher, ipv6Segment, ipv6Matcher, ip, jsonStringDescription, writeJsonSyntaxErrorProblem, jsonRoot, parseJson, json, preformattedLower, lower, normalizedForms, preformattedNodes, normalizeNodes, NFC, NFD, NFKC, NFKD, normalize, numericRoot, stringNumeric, regexPatternDescription, regex2, semverMatcher, semver, preformattedTrim, trim, preformattedUpper, upper, isParsableUrl, urlRoot, url, uuid, string; +var init_string2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/string.js"() { + init_out2(); + init_out(); + init_scope2(); + init_number(); + regexStringNode = (regex3, description, jsonSchemaFormat) => { + const schema2 = { + domain: "string", + pattern: { + rule: regex3.source, + flags: regex3.flags, + meta: description + } + }; + if (jsonSchemaFormat) + schema2.meta = { format: jsonSchemaFormat }; + return node("intersection", schema2); + }; + stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher2, "a well-formed integer string"); + stringInteger = Scope.module({ + root: stringIntegerRoot, + parse: rootSchema({ + in: stringIntegerRoot, + morphs: (s, ctx) => { + const parsed2 = Number.parseInt(s); + return Number.isSafeInteger(parsed2) ? parsed2 : ctx.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER"); + }, + declaredOut: intrinsic.integer + }) + }, { + name: "string.integer" + }); + hex = regexStringNode(/^[\dA-Fa-f]+$/, "hex characters only"); + base64 = Scope.module({ + root: regexStringNode(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/, "base64-encoded"), + url: regexStringNode(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/, "base64url-encoded") + }, { + name: "string.base64" + }); + preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized"); + capitalize2 = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1), + declaredOut: preformattedCapitalize + }), + preformatted: preformattedCapitalize + }, { + name: "string.capitalize" + }); + isLuhnValid = (creditCardInput) => { + const sanitized = creditCardInput.replace(/[ -]+/g, ""); + let sum = 0; + let digit; + let tmpNum; + let shouldDouble = false; + for (let i = sanitized.length - 1; i >= 0; i--) { + digit = sanitized.substring(i, i + 1); + tmpNum = Number.parseInt(digit, 10); + if (shouldDouble) { + tmpNum *= 2; + sum += tmpNum >= 10 ? tmpNum % 10 + 1 : tmpNum; + } else + sum += tmpNum; + shouldDouble = !shouldDouble; + } + return !!(sum % 10 === 0 ? sanitized : false); + }; + creditCardMatcher = /^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/; + creditCard = rootSchema({ + domain: "string", + pattern: { + meta: "a credit card number", + rule: creditCardMatcher.source + }, + predicate: { + meta: "a credit card number", + predicate: isLuhnValid + } + }); + iso8601Matcher = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; + isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf()); + parsableDate = rootSchema({ + domain: "string", + predicate: { + meta: "a parsable date", + predicate: isParsableDate + } + }).assertHasKind("intersection"); + epochRoot = stringInteger.root.internal.narrow((s, ctx) => { + const n = Number.parseInt(s); + const out = number.epoch(n); + if (out instanceof ArkErrors) { + ctx.errors.merge(out); + return false; + } + return true; + }).configure({ + description: "an integer string representing a safe Unix timestamp" + }, "self").assertHasKind("intersection"); + epoch2 = Scope.module({ + root: epochRoot, + parse: rootSchema({ + in: epochRoot, + morphs: (s) => new Date(s), + declaredOut: intrinsic.Date + }) + }, { + name: "string.date.epoch" + }); + isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"); + iso = Scope.module({ + root: isoRoot, + parse: rootSchema({ + in: isoRoot, + morphs: (s) => new Date(s), + declaredOut: intrinsic.Date + }) + }, { + name: "string.date.iso" + }); + stringDate = Scope.module({ + root: parsableDate, + parse: rootSchema({ + declaredIn: parsableDate, + in: "string", + morphs: (s, ctx) => { + const date2 = new Date(s); + if (Number.isNaN(date2.valueOf())) + return ctx.error("a parsable date"); + return date2; + }, + declaredOut: intrinsic.Date + }), + iso, + epoch: epoch2 + }, { + name: "string.date" + }); + email = regexStringNode( + // considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead + // which breaks some integrations e.g. fast-check + // regex based on: + // https://www.regular-expressions.info/email.html + /^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/, + "an email address", + "email" + ); + ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; + ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`; + ipv4Matcher = new RegExp(`^${ipv4Address}$`); + ipv6Segment = "(?:[0-9a-fA-F]{1,4})"; + ipv6Matcher = new RegExp(`^((?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`); + ip = Scope.module({ + root: ["v4 | v6", "@", "an IP address"], + v4: regexStringNode(ipv4Matcher, "an IPv4 address", "ipv4"), + v6: regexStringNode(ipv6Matcher, "an IPv6 address", "ipv6") + }, { + name: "string.ip" + }); + jsonStringDescription = "a JSON string"; + writeJsonSyntaxErrorProblem = (error41) => { + if (!(error41 instanceof SyntaxError)) + throw error41; + return `must be ${jsonStringDescription} (${error41})`; + }; + jsonRoot = rootSchema({ + meta: jsonStringDescription, + domain: "string", + predicate: { + meta: jsonStringDescription, + predicate: (s, ctx) => { + try { + JSON.parse(s); + return true; + } catch (e) { + return ctx.reject({ + code: "predicate", + expected: jsonStringDescription, + problem: writeJsonSyntaxErrorProblem(e) + }); + } + } + } + }); + parseJson = (s, ctx) => { + if (s.length === 0) { + return ctx.error({ + code: "predicate", + expected: jsonStringDescription, + actual: "empty" + }); + } + try { + return JSON.parse(s); + } catch (e) { + return ctx.error({ + code: "predicate", + expected: jsonStringDescription, + problem: writeJsonSyntaxErrorProblem(e) + }); + } + }; + json = Scope.module({ + root: jsonRoot, + parse: rootSchema({ + meta: "safe JSON string parser", + in: "string", + morphs: parseJson, + declaredOut: intrinsic.jsonObject + }) + }, { + name: "string.json" + }); + preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters"); + lower = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.toLowerCase(), + declaredOut: preformattedLower + }), + preformatted: preformattedLower + }, { + name: "string.lower" + }); + normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"]; + preformattedNodes = flatMorph2(normalizedForms, (i, form) => [ + form, + rootSchema({ + domain: "string", + predicate: (s) => s.normalize(form) === s, + meta: `${form}-normalized unicode` + }) + ]); + normalizeNodes = flatMorph2(normalizedForms, (i, form) => [ + form, + rootSchema({ + in: "string", + morphs: (s) => s.normalize(form), + declaredOut: preformattedNodes[form] + }) + ]); + NFC = Scope.module({ + root: normalizeNodes.NFC, + preformatted: preformattedNodes.NFC + }, { + name: "string.normalize.NFC" + }); + NFD = Scope.module({ + root: normalizeNodes.NFD, + preformatted: preformattedNodes.NFD + }, { + name: "string.normalize.NFD" + }); + NFKC = Scope.module({ + root: normalizeNodes.NFKC, + preformatted: preformattedNodes.NFKC + }, { + name: "string.normalize.NFKC" + }); + NFKD = Scope.module({ + root: normalizeNodes.NFKD, + preformatted: preformattedNodes.NFKD + }, { + name: "string.normalize.NFKD" + }); + normalize = Scope.module({ + root: "NFC", + NFC, + NFD, + NFKC, + NFKD + }, { + name: "string.normalize" + }); + numericRoot = regexStringNode(numericStringMatcher2, "a well-formed numeric string"); + stringNumeric = Scope.module({ + root: numericRoot, + parse: rootSchema({ + in: numericRoot, + morphs: (s) => Number.parseFloat(s), + declaredOut: intrinsic.number + }) + }, { + name: "string.numeric" + }); + regexPatternDescription = "a regex pattern"; + regex2 = rootSchema({ + domain: "string", + predicate: { + meta: regexPatternDescription, + predicate: (s, ctx) => { + try { + new RegExp(s); + return true; + } catch (e) { + return ctx.reject({ + code: "predicate", + expected: regexPatternDescription, + problem: String(e) + }); + } + } + }, + meta: { format: "regex" } + }); + semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/; + semver = regexStringNode(semverMatcher, "a semantic version (see https://semver.org/)"); + preformattedTrim = regexStringNode( + // no leading or trailing whitespace + /^\S.*\S$|^\S?$/, + "trimmed" + ); + trim = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.trim(), + declaredOut: preformattedTrim + }), + preformatted: preformattedTrim + }, { + name: "string.trim" + }); + preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters"); + upper = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.toUpperCase(), + declaredOut: preformattedUpper + }), + preformatted: preformattedUpper + }, { + name: "string.upper" + }); + isParsableUrl = (s) => URL.canParse(s); + urlRoot = rootSchema({ + domain: "string", + predicate: { + meta: "a URL string", + predicate: isParsableUrl + }, + // URL.canParse allows a subset of the RFC-3986 URI spec + // since there is no other serializable validation, best include a format + meta: { format: "uri" } + }); + url = Scope.module({ + root: urlRoot, + parse: rootSchema({ + declaredIn: urlRoot, + in: "string", + morphs: (s, ctx) => { + try { + return new URL(s); + } catch { + return ctx.error("a URL string"); + } + }, + declaredOut: rootSchema(URL) + }) + }, { + name: "string.url" + }); + uuid = Scope.module({ + // the meta tuple expression ensures the error message does not delegate + // to the individual branches, which are too detailed + root: [ + "versioned | nil | max", + "@", + { description: "a UUID", format: "uuid" } + ], + "#nil": "'00000000-0000-0000-0000-000000000000'", + "#max": "'ffffffff-ffff-ffff-ffff-ffffffffffff'", + "#versioned": /[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i, + v1: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv1"), + v2: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv2"), + v3: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv3"), + v4: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv4"), + v5: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv5"), + v6: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv6"), + v7: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv7"), + v8: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv8") + }, { + name: "string.uuid" + }); + string = Scope.module({ + root: intrinsic.string, + alpha: regexStringNode(/^[A-Za-z]*$/, "only letters"), + alphanumeric: regexStringNode(/^[\dA-Za-z]*$/, "only letters and digits 0-9"), + hex, + base64, + capitalize: capitalize2, + creditCard, + date: stringDate, + digits: regexStringNode(/^\d*$/, "only digits 0-9"), + email, + integer: stringInteger, + ip, + json, + lower, + normalize, + numeric: stringNumeric, + regex: regex2, + semver, + trim, + upper, + url, + uuid + }, { + name: "string" + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/ts.js +var arkTsKeywords, unknown, json2, object, RecordHkt, Record, PickHkt, Pick, OmitHkt, Omit, PartialHkt, Partial, RequiredHkt, Required2, ExcludeHkt, Exclude, ExtractHkt, Extract, arkTsGenerics; +var init_ts = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/ts.js"() { + init_out2(); + init_out(); + init_scope2(); + arkTsKeywords = Scope.module({ + bigint: intrinsic.bigint, + boolean: intrinsic.boolean, + false: intrinsic.false, + never: intrinsic.never, + null: intrinsic.null, + number: intrinsic.number, + object: intrinsic.object, + string: intrinsic.string, + symbol: intrinsic.symbol, + true: intrinsic.true, + unknown: intrinsic.unknown, + undefined: intrinsic.undefined + }); + unknown = Scope.module({ + root: intrinsic.unknown, + any: intrinsic.unknown + }, { + name: "unknown" + }); + json2 = Scope.module({ + root: intrinsic.jsonObject, + stringify: node("morph", { + in: intrinsic.jsonObject, + morphs: (data) => JSON.stringify(data), + declaredOut: intrinsic.string + }) + }, { + name: "object.json" + }); + object = Scope.module({ + root: intrinsic.object, + json: json2 + }, { + name: "object" + }); + RecordHkt = class extends Hkt { + description = 'instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'; + }; + Record = genericNode(["K", intrinsic.key], "V")((args3) => ({ + domain: "object", + index: { + signature: args3.K, + value: args3.V + } + }), RecordHkt); + PickHkt = class extends Hkt { + description = 'pick a set of properties from an object like `Pick(User, "name | age")`'; + }; + Pick = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args3) => args3.T.pick(args3.K), PickHkt); + OmitHkt = class extends Hkt { + description = 'omit a set of properties from an object like `Omit(User, "age")`'; + }; + Omit = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args3) => args3.T.omit(args3.K), OmitHkt); + PartialHkt = class extends Hkt { + description = "make all named properties of an object optional like `Partial(User)`"; + }; + Partial = genericNode(["T", intrinsic.object])((args3) => args3.T.partial(), PartialHkt); + RequiredHkt = class extends Hkt { + description = "make all named properties of an object required like `Required(User)`"; + }; + Required2 = genericNode(["T", intrinsic.object])((args3) => args3.T.required(), RequiredHkt); + ExcludeHkt = class extends Hkt { + description = 'exclude branches of a union like `Exclude("boolean", "true")`'; + }; + Exclude = genericNode("T", "U")((args3) => args3.T.exclude(args3.U), ExcludeHkt); + ExtractHkt = class extends Hkt { + description = 'extract branches of a union like `Extract("0 | false | 1", "number")`'; + }; + Extract = genericNode("T", "U")((args3) => args3.T.extract(args3.U), ExtractHkt); + arkTsGenerics = Scope.module({ + Exclude, + Extract, + Omit, + Partial, + Pick, + Record, + Required: Required2 + }); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/keywords.js +var ark, keywords, type, match, fn, generic, schema, define2, declare; +var init_keywords = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/keywords.js"() { + init_scope2(); + init_builtins(); + init_constructors(); + init_number(); + init_string2(); + init_ts(); + ark = scope({ + ...arkTsKeywords, + ...arkTsGenerics, + ...arkPrototypes, + ...arkBuiltins, + string, + number, + object, + unknown + }, { prereducedAliases: true, name: "ark" }); + keywords = ark.export(); + Object.assign($arkTypeRegistry.ambient, keywords); + $arkTypeRegistry.typeAttachments = { + string: keywords.string.root, + number: keywords.number.root, + bigint: keywords.bigint, + boolean: keywords.boolean, + symbol: keywords.symbol, + undefined: keywords.undefined, + null: keywords.null, + object: keywords.object.root, + unknown: keywords.unknown.root, + false: keywords.false, + true: keywords.true, + never: keywords.never, + arrayIndex: keywords.Array.index, + Key: keywords.Key, + Record: keywords.Record, + Array: keywords.Array.root, + Date: keywords.Date + }; + type = Object.assign( + ark.type, + // assign attachments newly parsed in keywords + // future scopes add these directly from the + // registry when their TypeParsers are instantiated + $arkTypeRegistry.typeAttachments + ); + match = ark.match; + fn = ark.fn; + generic = ark.generic; + schema = ark.schema; + define2 = ark.define; + declare = ark.declare; + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/module.js +var init_module2 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/module.js"() { + init_out2(); + } +}); + +// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/index.js +var init_out4 = __esm({ + "node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/index.js"() { + init_out2(); + init_out(); + init_out3(); + init_config2(); + init_generic2(); + init_keywords(); + init_module2(); + init_scope2(); + init_type(); + } +}); + +// external.ts +var ghPullfrogMcpName, agentsManifest, AgentName; +var init_external = __esm({ + "external.ts"() { + "use strict"; + init_out4(); + ghPullfrogMcpName = "gh_pullfrog"; + agentsManifest = { + claude: { + displayName: "Claude Code", + apiKeyNames: ["anthropic_api_key"], + url: "https://claude.com/claude-code" + }, + codex: { + displayName: "Codex CLI", + apiKeyNames: ["openai_api_key"], + url: "https://platform.openai.com/docs/guides/codex" + }, + cursor: { + displayName: "Cursor CLI", + apiKeyNames: ["cursor_api_key"], + url: "https://cursor.com/" + }, + gemini: { + displayName: "Gemini CLI", + apiKeyNames: ["google_api_key", "gemini_api_key"], + url: "https://ai.google.dev/gemini-api/docs" + }, + opencode: { + displayName: "OpenCode", + apiKeyNames: [], + // empty array means OpenCode accepts any API_KEY from environment + url: "https://opencode.ai" + } + }; + AgentName = type.enumerated(...Object.keys(agentsManifest)); + } +}); + +// utils/github.ts +import { createSign } from "node:crypto"; +function isGitHubActionsEnvironment() { + return Boolean(process.env.GITHUB_ACTIONS); +} +async function acquireTokenViaOIDC() { + log.info("Generating OIDC token..."); + const oidcToken = await core2.getIDToken("pullfrog-api"); + log.info("OIDC token generated successfully"); + const apiUrl = process.env.API_URL || "https://pullfrog.com"; + log.info("Exchanging OIDC token for installation token..."); + const timeoutMs = 5e3; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + try { + const tokenResponse = await fetch(`${apiUrl}/api/github/installation-token`, { + method: "POST", + headers: { + Authorization: `Bearer ${oidcToken}`, + "Content-Type": "application/json" + }, + signal: controller.signal + }); + clearTimeout(timeoutId); + if (!tokenResponse.ok) { + throw new Error(`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText}`); + } + const tokenData = await tokenResponse.json(); + log.info(`Installation token obtained for ${tokenData.repository || "all repositories"}`); + return tokenData.token; + } catch (error41) { + clearTimeout(timeoutId); + if (error41 instanceof Error && error41.name === "AbortError") { + throw new Error(`Token exchange timed out after ${timeoutMs}ms`); + } + throw error41; + } +} +async function acquireTokenViaGitHubApp() { + const repoContext = parseRepoContext(); + const config2 = { + appId: process.env.GITHUB_APP_ID, + privateKey: process.env.GITHUB_PRIVATE_KEY?.replace(/\\n/g, "\n"), + repoOwner: repoContext.owner, + repoName: repoContext.name + }; + const jwt = generateJWT(config2.appId, config2.privateKey); + const installationId = await findInstallationId(jwt, config2.repoOwner, config2.repoName); + const token = await createInstallationToken(jwt, installationId); + return token; +} +async function acquireNewToken() { + if (isGitHubActionsEnvironment()) { + return await acquireTokenViaOIDC(); + } else { + return await acquireTokenViaGitHubApp(); + } +} +async function setupGitHubInstallationToken() { + const acquiredToken = await acquireNewToken(); + core2.setSecret(acquiredToken); + githubInstallationToken = acquiredToken; + return acquiredToken; +} +function getGitHubInstallationToken() { + if (!githubInstallationToken) { + throw new Error("GitHub installation token not set. Call setupGitHubInstallationToken first."); + } + return githubInstallationToken; +} +async function revokeGitHubInstallationToken() { + if (!githubInstallationToken) { + return; + } + const token = githubInstallationToken; + githubInstallationToken = void 0; + const apiUrl = process.env.GITHUB_API_URL || "https://api.github.com"; + try { + await fetch(`${apiUrl}/installation/token`, { + method: "DELETE", + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${token}`, + "X-GitHub-Api-Version": "2022-11-28" + } + }); + log.info("Installation token revoked"); + } catch (error41) { + log.warning( + `Failed to revoke installation token: ${error41 instanceof Error ? error41.message : String(error41)}` + ); + } +} +function parseRepoContext() { + const githubRepo = process.env.GITHUB_REPOSITORY; + if (!githubRepo) { + throw new Error("GITHUB_REPOSITORY environment variable is required"); + } + const [owner, name] = githubRepo.split("/"); + if (!owner || !name) { + throw new Error(`Invalid GITHUB_REPOSITORY format: ${githubRepo}. Expected 'owner/repo'`); + } + return { owner, name }; +} +var core2, base64UrlEncode, generateJWT, githubRequest, checkRepositoryAccess, createInstallationToken, findInstallationId, githubInstallationToken; +var init_github = __esm({ + "utils/github.ts"() { + "use strict"; + core2 = __toESM(require_core(), 1); + init_cli(); + base64UrlEncode = (str) => { + return Buffer.from(str).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + }; + generateJWT = (appId, privateKey) => { + const now = Math.floor(Date.now() / 1e3); + const payload = { + iat: now - 60, + exp: now + 5 * 60, + iss: appId + }; + const header = { + alg: "RS256", + typ: "JWT" + }; + const encodedHeader = base64UrlEncode(JSON.stringify(header)); + const encodedPayload = base64UrlEncode(JSON.stringify(payload)); + const signaturePart = `${encodedHeader}.${encodedPayload}`; + const signature = createSign("RSA-SHA256").update(signaturePart).sign(privateKey, "base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + return `${signaturePart}.${signature}`; + }; + githubRequest = async (path3, options = {}) => { + const { method = "GET", headers = {}, body } = options; + const url2 = `https://api.github.com${path3}`; + const requestHeaders = { + Accept: "application/vnd.github.v3+json", + "User-Agent": "Pullfrog-Installation-Token-Generator/1.0", + ...headers + }; + const response = await fetch(url2, { + method, + headers: requestHeaders, + ...body && { body } + }); + if (!response.ok) { + const errorText = await response.text(); + throw new Error( + `GitHub API request failed: ${response.status} ${response.statusText} +${errorText}` + ); + } + return response.json(); + }; + checkRepositoryAccess = async (token, repoOwner, repoName) => { + try { + const response = await githubRequest("/installation/repositories", { + headers: { Authorization: `token ${token}` } + }); + return response.repositories.some( + (repo) => repo.owner.login === repoOwner && repo.name === repoName + ); + } catch { + return false; + } + }; + createInstallationToken = async (jwt, installationId) => { + const response = await githubRequest( + `/app/installations/${installationId}/access_tokens`, + { + method: "POST", + headers: { Authorization: `Bearer ${jwt}` } + } + ); + return response.token; + }; + findInstallationId = async (jwt, repoOwner, repoName) => { + const installations = await githubRequest("/app/installations", { + headers: { Authorization: `Bearer ${jwt}` } + }); + for (const installation of installations) { + try { + const tempToken = await createInstallationToken(jwt, installation.id); + const hasAccess = await checkRepositoryAccess(tempToken, repoOwner, repoName); + if (hasAccess) { + return installation.id; + } + } catch { + } + } + throw new Error( + `No installation found with access to ${repoOwner}/${repoName}. Ensure the GitHub App is installed on the target repository.` + ); + }; + } +}); + +// node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + if (typeof process === "object" && process.version !== void 0) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; +} +var init_universal_user_agent = __esm({ + "node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js"() { + } +}); + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js +function register3(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + if (!options) { + options = {}; + } + if (Array.isArray(name)) { + return name.reverse().reduce((callback, name2) => { + return register3.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(() => { + if (!state.registry[name]) { + return method(options); + } + return state.registry[name].reduce((method2, registered) => { + return registered.hook.bind(null, method2, options); + }, method)(); + }); +} +var init_register = __esm({ + "node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js"() { + } +}); + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js +function addHook(state, kind, name, hook2) { + const orig = hook2; + if (!state.registry[name]) { + state.registry[name] = []; + } + if (kind === "before") { + hook2 = (method, options) => { + return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); + }; + } + if (kind === "after") { + hook2 = (method, options) => { + let result; + return Promise.resolve().then(method.bind(null, options)).then((result_) => { + result = result_; + return orig(result, options); + }).then(() => { + return result; + }); + }; + } + if (kind === "error") { + hook2 = (method, options) => { + return Promise.resolve().then(method.bind(null, options)).catch((error41) => { + return orig(error41, options); + }); + }; + } + state.registry[name].push({ + hook: hook2, + orig + }); +} +var init_add = __esm({ + "node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js"() { + } +}); + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + const index = state.registry[name].map((registered) => { + return registered.orig; + }).indexOf(method); + if (index === -1) { + return; + } + state.registry[name].splice(index, 1); +} +var init_remove = __esm({ + "node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js"() { + } +}); + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js +function bindApi(hook2, state, name) { + const removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook2.api = { remove: removeHookRef }; + hook2.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach((kind) => { + const args3 = name ? [state, kind, name] : [state, kind]; + hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args3); + }); +} +function Singular() { + const singularHookName = Symbol("Singular"); + const singularHookState = { + registry: {} + }; + const singularHook = register3.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} +function Collection() { + const state = { + registry: {} + }; + const hook2 = register3.bind(null, state); + bindApi(hook2, state); + return hook2; +} +var bind, bindable, before_after_hook_default; +var init_before_after_hook = __esm({ + "node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js"() { + init_register(); + init_add(); + init_remove(); + bind = Function.bind; + bindable = bind.bind(bind); + before_after_hook_default = { Singular, Collection }; + } +}); + +// node_modules/.pnpm/@octokit+endpoint@11.0.1/node_modules/@octokit/endpoint/dist-bundle/index.js +function lowercaseKeys(object2) { + if (!object2) { + return {}; + } + return Object.keys(object2).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object2[key]; + return newObj; + }, {}); +} +function isPlainObject2(value2) { + if (typeof value2 !== "object" || value2 === null) return false; + if (Object.prototype.toString.call(value2) !== "[object Object]") return false; + const proto = Object.getPrototypeOf(value2); + if (proto === null) return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value2); +} +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject2(options[key])) { + if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); + else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url2] = route.split(" "); + options = Object.assign(url2 ? { method, url: url2 } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} +function addQueryParameters(url2, parameters) { + const separator2 = /\?/.test(url2) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url2; + } + return url2 + separator2 + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} +function omit2(object2, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object2)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object2[key]; + } + } + return result; +} +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue2(operator, value2, key) { + value2 = operator === "+" || operator === "#" ? encodeReserved(value2) : encodeUnreserved(value2); + if (key) { + return encodeUnreserved(key) + "=" + value2; + } else { + return value2; + } +} +function isDefined(value2) { + return value2 !== void 0 && value2 !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value2 = context[key], result = []; + if (isDefined(value2) && value2 !== "") { + if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") { + value2 = value2.toString(); + if (modifier && modifier !== "*") { + value2 = value2.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue2(operator, value2, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value2)) { + value2.filter(isDefined).forEach(function(value22) { + result.push( + encodeValue2(operator, value22, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value2).forEach(function(k) { + if (isDefined(value2[k])) { + result.push(encodeValue2(operator, value2[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value2)) { + value2.filter(isDefined).forEach(function(value22) { + tmp.push(encodeValue2(operator, value22)); + }); + } else { + Object.keys(value2).forEach(function(k) { + if (isDefined(value2[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue2(operator, value2[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value2)) { + result.push(encodeUnreserved(key)); + } + } else if (value2 === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value2 === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator2 = ","; + if (operator === "?") { + separator2 = "&"; + } else if (operator !== "#") { + separator2 = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator2); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} +function parse(options) { + let method = options.method.toUpperCase(); + let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit2(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url2); + url2 = parseUrl(url2).expand(parameters); + if (!/^http/.test(url2)) { + url2 = options.baseUrl + url2; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit2(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format2) => format2.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url2.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format2 = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format2}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url2 = addQueryParameters(url2, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url: url2, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} +var VERSION, userAgent, DEFAULTS, urlVariableRegex, endpoint; +var init_dist_bundle = __esm({ + "node_modules/.pnpm/@octokit+endpoint@11.0.1/node_modules/@octokit/endpoint/dist-bundle/index.js"() { + init_universal_user_agent(); + VERSION = "0.0.0-development"; + userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; + DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } + }; + urlVariableRegex = /\{[^{}}]+\}/g; + endpoint = withDefaults(null, DEFAULTS); + } +}); + // node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js var require_fast_content_type_parse = __commonJS({ "node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js"(exports, module) { @@ -25601,6 +36082,3594 @@ var require_fast_content_type_parse = __commonJS({ } }); +// node_modules/.pnpm/@octokit+request-error@7.0.1/node_modules/@octokit/request-error/dist-src/index.js +var RequestError; +var init_dist_src = __esm({ + "node_modules/.pnpm/@octokit+request-error@7.0.1/node_modules/@octokit/request-error/dist-src/index.js"() { + RequestError = class extends Error { + name; + /** + * http status code + */ + status; + /** + * Request options that lead to the error. + */ + request; + /** + * Response object if a response was received + */ + response; + constructor(message, statusCode, options) { + super(message); + this.name = "HttpError"; + this.status = Number.parseInt(statusCode); + if (Number.isNaN(this.status)) { + this.status = 0; + } + if ("response" in options) { + this.response = options.response; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? [ + name, + String(value2) + ]) + ); + let fetchResponse; + try { + fetchResponse = await fetch3(requestOptions.url, { + method: requestOptions.method, + body, + redirect: requestOptions.request?.redirect, + headers: requestHeaders, + signal: requestOptions.request?.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }); + } catch (error41) { + let message = "Unknown Error"; + if (error41 instanceof Error) { + if (error41.name === "AbortError") { + error41.status = 500; + throw error41; + } + message = error41.message; + if (error41.name === "TypeError" && "cause" in error41) { + if (error41.cause instanceof Error) { + message = error41.cause.message; + } else if (typeof error41.cause === "string") { + message = error41.cause; + } + } + } + const requestError = new RequestError(message, 500, { + request: requestOptions + }); + requestError.cause = error41; + throw requestError; + } + const status = fetchResponse.status; + const url2 = fetchResponse.url; + const responseHeaders = {}; + for (const [key, value2] of fetchResponse.headers) { + responseHeaders[key] = value2; + } + const octokitResponse = { + url: url2, + status, + headers: responseHeaders, + data: "" + }; + if ("deprecation" in responseHeaders) { + const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log2.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return octokitResponse; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return octokitResponse; + } + throw new RequestError(fetchResponse.statusText, status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status === 304) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError("Not modified", status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status >= 400) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError(toErrorMessage(octokitResponse.data), status, { + response: octokitResponse, + request: requestOptions + }); + } + octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; + return octokitResponse; +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (!contentType) { + return response.text().catch(() => ""); + } + const mimetype = (0, import_fast_content_type_parse.safeParse)(contentType); + if (isJSONResponse(mimetype)) { + let text = ""; + try { + text = await response.text(); + return JSON.parse(text); + } catch (err) { + return text; + } + } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { + return response.text().catch(() => ""); + } else { + return response.arrayBuffer().catch(() => new ArrayBuffer(0)); + } +} +function isJSONResponse(mimetype) { + return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; +} +function toErrorMessage(data) { + if (typeof data === "string") { + return data; + } + if (data instanceof ArrayBuffer) { + return "Unknown error"; + } + if ("message" in data) { + const suffix2 = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; + return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix2}` : `${data.message}${suffix2}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} +function withDefaults2(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults2.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults2.bind(null, endpoint2) + }); +} +var import_fast_content_type_parse, VERSION2, defaults_default, request; +var init_dist_bundle2 = __esm({ + "node_modules/.pnpm/@octokit+request@10.0.5/node_modules/@octokit/request/dist-bundle/index.js"() { + init_dist_bundle(); + init_universal_user_agent(); + import_fast_content_type_parse = __toESM(require_fast_content_type_parse(), 1); + init_dist_src(); + VERSION2 = "10.0.5"; + defaults_default = { + headers: { + "user-agent": `octokit-request.js/${VERSION2} ${getUserAgent()}` + } + }; + request = withDefaults2(endpoint, defaults_default); + } +}); + +// node_modules/.pnpm/@octokit+graphql@9.0.2/node_modules/@octokit/graphql/dist-bundle/index.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +function graphql(request2, query2, options) { + if (options) { + if (typeof query2 === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query2 === "string" ? Object.assign({ query: query2 }, options) : query2; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} +function withDefaults3(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query2, options) => { + return graphql(newRequest, query2, options); + }; + return Object.assign(newApi, { + defaults: withDefaults3.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} +function withCustomRequest(customRequest) { + return withDefaults3(customRequest, { + method: "POST", + url: "/graphql" + }); +} +var VERSION3, GraphqlResponseError, NON_VARIABLE_OPTIONS, FORBIDDEN_VARIABLE_OPTIONS, GHES_V3_SUFFIX_REGEX, graphql2; +var init_dist_bundle3 = __esm({ + "node_modules/.pnpm/@octokit+graphql@9.0.2/node_modules/@octokit/graphql/dist-bundle/index.js"() { + init_dist_bundle2(); + init_universal_user_agent(); + VERSION3 = "0.0.0-development"; + GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + name = "GraphqlResponseError"; + errors; + data; + }; + NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType", + "operationName" + ]; + FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; + GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; + graphql2 = withDefaults3(request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}` + }, + method: "POST", + url: "/graphql" + }); + } +}); + +// node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js +async function auth(token) { + const isApp = isJWT(token); + const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); + const isUserToServer = token.startsWith("ghu_"); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} +async function hook(token, request2, route, parameters) { + const endpoint2 = request2.endpoint.merge( + route, + parameters + ); + endpoint2.headers.authorization = withAuthorizationPrefix(token); + return request2(endpoint2); +} +var b64url, sep, jwtRE, isJWT, createTokenAuth; +var init_dist_bundle4 = __esm({ + "node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js"() { + b64url = "(?:[a-zA-Z0-9_-]+)"; + sep = "\\."; + jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); + isJWT = jwtRE.test.bind(jwtRE); + createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); + }; + } +}); + +// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/version.js +var VERSION4; +var init_version = __esm({ + "node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/version.js"() { + VERSION4 = "7.0.5"; + } +}); + +// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/index.js +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop; + } + if (typeof logger.info !== "function") { + logger.info = noop; + } + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; + } + if (typeof logger.error !== "function") { + logger.error = consoleError; + } + return logger; +} +var noop, consoleWarn, consoleError, userAgentTrail, Octokit; +var init_dist_src2 = __esm({ + "node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/index.js"() { + init_universal_user_agent(); + init_before_after_hook(); + init_dist_bundle2(); + init_dist_bundle3(); + init_dist_bundle4(); + init_version(); + noop = () => { + }; + consoleWarn = console.warn.bind(console); + consoleError = console.error.bind(console); + userAgentTrail = `octokit-core.js/${VERSION4} ${getUserAgent()}`; + Octokit = class { + static VERSION = VERSION4; + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args3) { + const options = args3[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static plugins = []; + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + }; + return NewOctokit; + } + constructor(options = {}) { + const hook2 = new before_after_hook_default.Collection(); + const requestDefaults = { + baseUrl: request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook2.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = request.defaults(requestDefaults); + this.graphql = withCustomRequest(this.request).defaults(requestDefaults); + this.log = createLogger(options.log); + this.hook = hook2; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth2 = createTokenAuth(options.auth); + hook2.wrap("request", auth2.hook); + this.auth = auth2; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth2 = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook2.wrap("request", auth2.hook); + this.auth = auth2; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } + // assigned during constructor + request; + graphql; + log; + hook; + // TODO: type `octokit.auth` based on passed options.authStrategy + auth; + }; + } +}); + +// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/version.js +var VERSION5; +var init_version2 = __esm({ + "node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/version.js"() { + VERSION5 = "6.0.0"; + } +}); + +// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/index.js +function requestLog(octokit) { + octokit.hook.wrap("request", (request2, options) => { + octokit.log.debug("request", options); + const start = Date.now(); + const requestOptions = octokit.request.endpoint.parse(options); + const path3 = requestOptions.url.replace(options.baseUrl, ""); + return request2(options).then((response) => { + const requestId = response.headers["x-github-request-id"]; + octokit.log.info( + `${requestOptions.method} ${path3} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` + ); + return response; + }).catch((error41) => { + const requestId = error41.response?.headers["x-github-request-id"] || "UNKNOWN"; + octokit.log.error( + `${requestOptions.method} ${path3} - ${error41.status} with id ${requestId} in ${Date.now() - start}ms` + ); + throw error41; + }); + }); +} +var init_dist_src3 = __esm({ + "node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/index.js"() { + init_version2(); + requestLog.VERSION = VERSION5; + } +}); + +// node_modules/.pnpm/@octokit+plugin-paginate-rest@13.2.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } + const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); + if (!responseNeedsNormalization) return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + const totalCommits = response.data.total_commits; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + delete response.data.total_commits; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + response.data.total_commits = totalCommits; + return response; +} +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 headers = options.headers; + let url2 = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url2) return { done: true }; + try { + const response = await requestMethod({ method, url: url2, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url2 = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + if (!url2 && "total_commits" in normalizedResponse.data) { + const parsedUrl = new URL(normalizedResponse.url); + const params = parsedUrl.searchParams; + const page = parseInt(params.get("page") || "1", 10); + const per_page = parseInt(params.get("per_page") || "250", 10); + if (page * per_page < normalizedResponse.data.total_commits) { + params.set("page", String(page + 1)); + url2 = parsedUrl.toString(); + } + } + return { value: normalizedResponse }; + } catch (error41) { + if (error41.status !== 409) throw error41; + url2 = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + }) + }; +} +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +var VERSION6, composePaginateRest; +var init_dist_bundle5 = __esm({ + "node_modules/.pnpm/@octokit+plugin-paginate-rest@13.2.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js"() { + VERSION6 = "0.0.0-development"; + composePaginateRest = Object.assign(paginate, { + iterator + }); + paginateRest.VERSION = VERSION6; + } +}); + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js +var VERSION7; +var init_version3 = __esm({ + "node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js"() { + VERSION7 = "16.1.0"; + } +}); + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js +var Endpoints, endpoints_default; +var init_endpoints = __esm({ + "node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js"() { + Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addRepoAccessToSelfHostedRunnerGroupInOrg: [ + "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], + createOrUpdateEnvironmentSecret: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + deleteHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + getHostedRunnersGithubOwnedImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/github-owned" + ], + getHostedRunnersLimitsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/limits" + ], + getHostedRunnersMachineSpecsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/machine-sizes" + ], + getHostedRunnersPartnerImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/partner" + ], + getHostedRunnersPlatformsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/platforms" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + listGithubHostedRunnersInGroupForOrg: [ + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" + ], + listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + updateHostedRunnerForOrg: [ + "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubBillingUsageReportOrg: [ + "GET /organizations/{org}/settings/billing/usage" + ], + getGithubBillingUsageReportUser: [ + "GET /users/{username}/settings/billing/usage" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + campaigns: { + createCampaign: ["POST /orgs/{org}/campaigns"], + deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], + getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], + listOrgCampaigns: ["GET /orgs/{org}/campaigns"], + updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + commitAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" + ], + createAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" + ], + createVariantAnalysis: [ + "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" + ], + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + deleteCodeqlDatabase: [ + "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getAutofix: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + getVariantAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" + ], + getVariantAnalysisRepoTask: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" + ], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codeSecurity: { + attachConfiguration: [ + "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" + ], + attachEnterpriseConfiguration: [ + "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" + ], + createConfiguration: ["POST /orgs/{org}/code-security/configurations"], + createConfigurationForEnterprise: [ + "POST /enterprises/{enterprise}/code-security/configurations" + ], + deleteConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" + ], + deleteConfigurationForEnterprise: [ + "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ], + detachConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/detach" + ], + getConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}" + ], + getConfigurationForRepository: [ + "GET /repos/{owner}/{repo}/code-security-configuration" + ], + getConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations" + ], + getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], + getDefaultConfigurations: [ + "GET /orgs/{org}/code-security/configurations/defaults" + ], + getDefaultConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/defaults" + ], + getRepositoriesForConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" + ], + getRepositoriesForEnterpriseConfiguration: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" + ], + getSingleConfigurationForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ], + setConfigurationAsDefault: [ + "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" + ], + setConfigurationAsDefaultForEnterprise: [ + "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" + ], + updateConfiguration: [ + "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" + ], + updateEnterpriseConfiguration: [ + "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], + copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + credentials: { revoke: ["POST /credentials/revoke"] }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + repositoryAccessForOrg: [ + "GET /organizations/{org}/dependabot/repository-access" + ], + setRepositoryAccessDefaultLevel: [ + "PUT /organizations/{org}/dependabot/repository-access/default-level" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ], + updateRepositoryAccessForOrg: [ + "PATCH /organizations/{org}/dependabot/repository-access" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + hostedCompute: { + createNetworkConfigurationForOrg: [ + "POST /orgs/{org}/settings/network-configurations" + ], + deleteNetworkConfigurationFromOrg: [ + "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkConfigurationForOrg: [ + "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkSettingsForOrg: [ + "GET /orgs/{org}/settings/network-settings/{network_settings_id}" + ], + listNetworkConfigurationsForOrg: [ + "GET /orgs/{org}/settings/network-configurations" + ], + updateNetworkConfigurationForOrg: [ + "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addBlockedByDependency: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + addSubIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listDependenciesBlockedBy: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + listDependenciesBlocking: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" + ], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + listSubIssues: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeDependencyBlockedBy: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + removeSubIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" + ], + reprioritizeSubIssue: [ + "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" + } + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createArtifactStorageRecord: [ + "POST /orgs/{org}/artifacts/metadata/storage-record" + ], + createInvitation: ["POST /orgs/{org}/invitations"], + createIssueType: ["POST /orgs/{org}/issue-types"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], + deleteAttestationsById: [ + "DELETE /orgs/{org}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /orgs/{org}/attestations/digest/{subject_digest}" + ], + deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], + getOrgRulesetVersion: [ + "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" + ], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listArtifactStorageRecords: [ + "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" + ], + listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listIssueTypes: ["GET /orgs/{org}/issue-types"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: [ + "GET /orgs/{org}/security-managers", + {}, + { + deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" + } + ], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" + } + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + privateRegistries: { + createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], + deleteOrgPrivateRegistry: [ + "DELETE /orgs/{org}/private-registries/{secret_name}" + ], + getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], + getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], + listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], + updateOrgPrivateRegistry: [ + "PATCH /orgs/{org}/private-registries/{secret_name}" + ] + }, + projects: { + addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], + addItemForUser: ["POST /users/{user_id}/projectsV2/{project_number}/items"], + deleteItemForOrg: [ + "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + deleteItemForUser: [ + "DELETE /users/{user_id}/projectsV2/{project_number}/items/{item_id}" + ], + getFieldForOrg: [ + "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" + ], + getFieldForUser: [ + "GET /users/{user_id}/projectsV2/{project_number}/fields/{field_id}" + ], + getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], + getForUser: ["GET /users/{user_id}/projectsV2/{project_number}"], + getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], + getUserItem: [ + "GET /users/{user_id}/projectsV2/{project_number}/items/{item_id}" + ], + listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], + listFieldsForUser: [ + "GET /users/{user_id}/projectsV2/{project_number}/fields" + ], + listForOrg: ["GET /orgs/{org}/projectsV2"], + listForUser: ["GET /users/{username}/projectsV2"], + listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], + listItemsForUser: [ + "GET /users/{user_id}/projectsV2/{project_number}/items" + ], + updateItemForOrg: [ + "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + updateItemForUser: [ + "PATCH /users/{user_id}/projectsV2/{project_number}/items/{item_id}" + ] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkPrivateVulnerabilityReporting: [ + "GET /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAttestation: ["POST /repos/{owner}/{repo}/attestations"], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesetHistory: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" + ], + getRepoRulesetVersion: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" + ], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAttestations: [ + "GET /repos/{owner}/{repo}/attestations/{subject_digest}" + ], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: [ + "GET /search/issues", + {}, + { + deprecated: "octokit.rest.search.issuesAndPullRequests() is deprecated, see https://docs.github.com/rest/search/search#search-issues-and-pull-requests" + } + ], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + createPushProtectionBypass: [ + "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + listOrgPatternConfigs: [ + "GET /orgs/{org}/secret-scanning/pattern-configurations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + updateOrgPatternConfigs: [ + "PATCH /orgs/{org}/secret-scanning/pattern-configurations" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteAttestationsBulk: [ + "POST /users/{username}/attestations/delete-request" + ], + deleteAttestationsById: [ + "DELETE /users/{username}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /users/{username}/attestations/digest/{subject_digest}" + ], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getById: ["GET /user/{account_id}"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } + }; + endpoints_default = Endpoints; + } +}); + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope2 of endpointMethodsMap.keys()) { + newMethods[scope2] = new Proxy({ octokit, scope: scope2, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope2, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args3) { + let options = requestWithDefaults.endpoint.merge(...args3); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope2}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args3); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope2}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args3); + } + return Object.assign(withDecorations, requestWithDefaults); +} +var endpointMethodsMap, handler; +var init_endpoints_to_methods = __esm({ + "node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js"() { + init_endpoints(); + endpointMethodsMap = /* @__PURE__ */ new Map(); + for (const [scope2, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint2] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint2; + const [method, url2] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url: url2 + }, + defaults + ); + if (!endpointMethodsMap.has(scope2)) { + endpointMethodsMap.set(scope2, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope2).set(methodName, { + scope: scope2, + methodName, + endpointDefaults, + decorations + }); + } + } + handler = { + has({ scope: scope2 }, methodName) { + return endpointMethodsMap.get(scope2).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope: scope2 }) { + return [...endpointMethodsMap.get(scope2).keys()]; + }, + set(target, methodName, value2) { + return target.cache[methodName] = value2; + }, + get({ octokit, scope: scope2, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope2).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope2, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); + } + return cache[methodName]; + } + }; + } +}); + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +var init_dist_src4 = __esm({ + "node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js"() { + init_version3(); + init_endpoints_to_methods(); + restEndpointMethods.VERSION = VERSION7; + legacyRestEndpointMethods.VERSION = VERSION7; + } +}); + +// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/version.js +var VERSION8; +var init_version4 = __esm({ + "node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/version.js"() { + VERSION8 = "22.0.0"; + } +}); + +// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/index.js +var Octokit2; +var init_dist_src5 = __esm({ + "node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/index.js"() { + init_dist_src2(); + init_dist_src3(); + init_dist_bundle5(); + init_dist_src4(); + init_version4(); + Octokit2 = Octokit.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults( + { + userAgent: `octokit-rest.js/${VERSION8}` + } + ); + } +}); + +// ../utils/github/leapingComment.ts +var LEAPING_INTO_ACTION_PREFIX; +var init_leapingComment = __esm({ + "../utils/github/leapingComment.ts"() { + "use strict"; + LEAPING_INTO_ACTION_PREFIX = "Leaping into action"; + } +}); + +// utils/api.ts +async function fetchWorkflowRunInfo(runId) { + const apiUrl = process.env.API_URL || "https://pullfrog.com"; + const timeoutMs = 5e3; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetch(`${apiUrl}/api/workflow-run/${runId}`, { + method: "GET", + headers: { + "Content-Type": "application/json" + }, + signal: controller.signal + }); + clearTimeout(timeoutId); + if (!response.ok) { + return { progressCommentId: null, issueNumber: null }; + } + const data = await response.json(); + return data; + } catch { + clearTimeout(timeoutId); + return { progressCommentId: null, issueNumber: null }; + } +} +async function fetchRepoSettings({ + token, + repoContext +}) { + const settings = await getRepoSettings(token, repoContext); + return settings; +} +async function getRepoSettings(token, repoContext) { + const apiUrl = process.env.API_URL || "https://pullfrog.com"; + const timeoutMs = 5e3; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetch( + `${apiUrl}/api/repo/${repoContext.owner}/${repoContext.name}/settings`, + { + method: "GET", + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json" + }, + signal: controller.signal + } + ); + clearTimeout(timeoutId); + if (!response.ok) { + return DEFAULT_REPO_SETTINGS; + } + const settings = await response.json(); + if (settings === null) { + return DEFAULT_REPO_SETTINGS; + } + return settings; + } catch { + clearTimeout(timeoutId); + return DEFAULT_REPO_SETTINGS; + } +} +var DEFAULT_REPO_SETTINGS; +var init_api = __esm({ + "utils/api.ts"() { + "use strict"; + DEFAULT_REPO_SETTINGS = { + defaultAgent: null, + webAccessLevel: "full_access", + webAccessAllowTrusted: false, + webAccessDomains: "", + modes: [] + }; + } +}); + +// mcp/shared.ts +function initMcpContext(state) { + mcpInitContext = state; +} +function getMcpContext() { + if (!mcpInitContext) { + throw new Error("MCP context not initialized. Call initializeMcpContext first."); + } + return { + ...mcpInitContext, + ...parseRepoContext(), + octokit: new Octokit2({ + auth: getGitHubInstallationToken() + }) + }; +} +function isProgressCommentDisabled() { + return mcpInitContext?.payload.disableProgressComment === true; +} +function sanitizeSchema(schema2) { + if (!schema2 || typeof schema2 !== "object") { + return schema2; + } + if (Array.isArray(schema2)) { + return schema2.map(sanitizeSchema); + } + if (schema2.anyOf && Array.isArray(schema2.anyOf) && schema2.anyOf.length > 0) { + const enumValues2 = []; + let allAreEnumObjects = true; + for (const item of schema2.anyOf) { + if (item && typeof item === "object" && Array.isArray(item.enum)) { + const stringEnums = item.enum.filter((v) => typeof v === "string"); + if (stringEnums.length > 0) { + enumValues2.push(...stringEnums); + } else { + allAreEnumObjects = false; + break; + } + } else { + allAreEnumObjects = false; + break; + } + } + if (allAreEnumObjects && enumValues2.length > 0) { + const uniqueEnums = [...new Set(enumValues2)]; + const result = { + type: "string", + enum: uniqueEnums + }; + if (schema2.description) { + result.description = schema2.description; + } + return result; + } + } + const sanitized = {}; + for (const [key, value2] of Object.entries(schema2)) { + if (key === "$schema") { + continue; + } + if (key === "anyOf" && schema2.anyOf) { + continue; + } + if (key === "$defs") { + sanitized.definitions = sanitizeSchema(value2); + continue; + } + sanitized[key] = sanitizeSchema(value2); + } + return sanitized; +} +function wrapSchema(schema2) { + const originalToJsonSchema = schema2.toJsonSchema?.bind(schema2); + if (!originalToJsonSchema) { + return schema2; + } + return new Proxy(schema2, { + get(target, prop) { + if (prop === "toJsonSchema") { + return () => { + const originalSchema = originalToJsonSchema(); + return sanitizeSchema(originalSchema); + }; + } + return target[prop]; + } + }); +} +function sanitizeTool(tool2) { + if (!tool2.parameters) { + return tool2; + } + const wrappedSchema = wrapSchema(tool2.parameters); + return { + ...tool2, + parameters: wrappedSchema + }; +} +var mcpInitContext, tool, addTools, contextualize, handleToolSuccess, handleToolError; +var init_shared3 = __esm({ + "mcp/shared.ts"() { + "use strict"; + init_dist_src5(); + init_github(); + tool = (toolDef) => toolDef; + addTools = (server, tools) => { + const shouldSanitize = mcpInitContext?.agentName === "gemini" || mcpInitContext?.agentName === "opencode"; + for (const tool2 of tools) { + const processedTool = shouldSanitize ? sanitizeTool(tool2) : tool2; + server.addTool(processedTool); + } + return server; + }; + contextualize = (executor) => { + return async (params) => { + try { + const ctx = getMcpContext(); + const result = await executor(params, ctx); + return handleToolSuccess(result); + } catch (error41) { + return handleToolError(error41); + } + }; + }; + handleToolSuccess = (data) => { + return { + content: [ + { + type: "text", + text: JSON.stringify(data, null, 2) + } + ] + }; + }; + handleToolError = (error41) => { + const errorMessage = error41 instanceof Error ? error41.message : String(error41); + return { + content: [ + { + type: "text", + text: `Error: ${errorMessage}` + } + ], + isError: true + }; + }; + } +}); + +// mcp/comment.ts +var comment_exports = {}; +__export(comment_exports, { + Comment: () => Comment, + CreateCommentTool: () => CreateCommentTool, + EditComment: () => EditComment, + EditCommentTool: () => EditCommentTool, + ReplyToReviewComment: () => ReplyToReviewComment, + ReplyToReviewCommentTool: () => ReplyToReviewCommentTool, + ReportProgress: () => ReportProgress, + ReportProgressTool: () => ReportProgressTool, + ensureProgressCommentUpdated: () => ensureProgressCommentUpdated, + reportProgress: () => reportProgress, + wasProgressCommentUpdated: () => wasProgressCommentUpdated +}); +function buildCommentFooter(payload) { + const repoContext = parseRepoContext(); + const runId = process.env.GITHUB_RUN_ID; + const agentName = payload.agent; + const agentInfo = agentName ? agentsManifest[agentName] : null; + const agentDisplayName = agentInfo?.displayName || "Unknown agent"; + const agentUrl = agentInfo?.url || "https://pullfrog.com"; + const workflowRunPart = runId ? `[View workflow run](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})` : "View workflow run"; + return ` +${PULLFROG_DIVIDER} +Pullfrog  \uFF5C Triggered by [Pullfrog](https://pullfrog.com) \uFF5C Using [${agentDisplayName}](${agentUrl}) \uFF5C ${workflowRunPart} \uFF5C [\u{1D54F}](https://x.com/pullfrogai)`; +} +function stripExistingFooter(body) { + const dividerIndex = body.indexOf(PULLFROG_DIVIDER); + if (dividerIndex === -1) { + return body; + } + return body.substring(0, dividerIndex).trimEnd(); +} +function addFooter(body, payload) { + const bodyWithoutFooter = stripExistingFooter(body); + const footer = buildCommentFooter(payload); + return `${bodyWithoutFooter}${footer}`; +} +function getProgressCommentIdFromEnv() { + const envCommentId = process.env.PULLFROG_PROGRESS_COMMENT_ID; + if (envCommentId) { + const parsed2 = parseInt(envCommentId, 10); + if (!Number.isNaN(parsed2)) { + return parsed2; + } + } + return null; +} +function getProgressCommentId() { + if (!progressCommentIdInitialized) { + progressCommentId = getProgressCommentIdFromEnv(); + progressCommentIdInitialized = true; + } + return progressCommentId; +} +function setProgressCommentId(id) { + progressCommentId = id; + progressCommentIdInitialized = true; +} +async function reportProgress({ body }) { + const ctx = getMcpContext(); + const bodyWithFooter = addFooter(body, ctx.payload); + const existingCommentId = getProgressCommentId(); + if (existingCommentId) { + const result2 = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.owner, + repo: ctx.name, + comment_id: existingCommentId, + body: bodyWithFooter + }); + progressCommentWasUpdated = true; + return { + commentId: result2.data.id, + url: result2.data.html_url, + body: result2.data.body || "", + action: "updated" + }; + } + const issueNumber = ctx.payload.event.issue_number; + if (issueNumber === void 0) { + throw new Error("cannot create progress comment: no issue_number found in the payload event"); + } + const result = await ctx.octokit.rest.issues.createComment({ + owner: ctx.owner, + repo: ctx.name, + issue_number: issueNumber, + body: bodyWithFooter + }); + setProgressCommentId(result.data.id); + progressCommentWasUpdated = true; + return { + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body || "", + action: "created" + }; +} +function wasProgressCommentUpdated() { + return progressCommentWasUpdated; +} +async function ensureProgressCommentUpdated(payload) { + if (progressCommentWasUpdated) { + return; + } + let existingCommentId = getProgressCommentId(); + if (!existingCommentId) { + const runId2 = process.env.GITHUB_RUN_ID; + if (runId2) { + try { + const workflowRunInfo = await fetchWorkflowRunInfo(runId2); + if (workflowRunInfo.progressCommentId) { + existingCommentId = parseInt(workflowRunInfo.progressCommentId, 10); + if (!Number.isNaN(existingCommentId)) { + process.env.PULLFROG_PROGRESS_COMMENT_ID = workflowRunInfo.progressCommentId; + } + } + } catch { + } + } + } + if (!existingCommentId) { + return; + } + const repoContext = parseRepoContext(); + const token = getGitHubInstallationToken(); + const octokit = new Octokit2({ auth: token }); + try { + const existingComment = await octokit.rest.issues.getComment({ + owner: repoContext.owner, + repo: repoContext.name, + comment_id: existingCommentId + }); + const commentBody = existingComment.data.body || ""; + if (!commentBody.startsWith(LEAPING_INTO_ACTION_PREFIX)) { + return; + } + } catch { + return; + } + let resolvedPayload; + try { + const ctx = getMcpContext(); + resolvedPayload = ctx.payload; + } catch { + resolvedPayload = payload; + } + const runId = process.env.GITHUB_RUN_ID; + const workflowRunLink = runId ? `[workflow](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})` : "workflow"; + const errorMessage = `\u274C this run croaked + +The workflow encountered an error before any progress could be reported. Please check the ${workflowRunLink} for details.`; + const body = resolvedPayload ? addFooter(errorMessage, resolvedPayload) : errorMessage; + await octokit.rest.issues.updateComment({ + owner: repoContext.owner, + repo: repoContext.name, + comment_id: existingCommentId, + body + }); +} +var PULLFROG_DIVIDER, Comment, CreateCommentTool, EditComment, EditCommentTool, progressCommentId, progressCommentIdInitialized, progressCommentWasUpdated, ReportProgress, ReportProgressTool, ReplyToReviewComment, ReplyToReviewCommentTool; +var init_comment = __esm({ + "mcp/comment.ts"() { + "use strict"; + init_dist_src5(); + init_out4(); + init_leapingComment(); + init_external(); + init_api(); + init_github(); + init_shared3(); + PULLFROG_DIVIDER = ""; + Comment = type({ + issueNumber: type.number.describe("the issue number to comment on"), + body: type.string.describe("the comment body content") + }); + CreateCommentTool = tool({ + name: "create_issue_comment", + description: "Create a comment on a GitHub issue", + parameters: Comment, + execute: contextualize(async ({ issueNumber, body }, ctx) => { + const bodyWithFooter = addFooter(body, ctx.payload); + const result = await ctx.octokit.rest.issues.createComment({ + owner: ctx.owner, + repo: ctx.name, + issue_number: issueNumber, + body: bodyWithFooter + }); + return { + success: true, + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body + }; + }) + }); + EditComment = type({ + commentId: type.number.describe("the ID of the comment to edit"), + body: type.string.describe("the new comment body content") + }); + EditCommentTool = tool({ + name: "edit_issue_comment", + description: "Edit a GitHub issue comment by its ID", + parameters: EditComment, + execute: contextualize(async ({ commentId, body }, ctx) => { + const bodyWithFooter = addFooter(body, ctx.payload); + const result = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.owner, + repo: ctx.name, + comment_id: commentId, + body: bodyWithFooter + }); + return { + success: true, + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body, + updatedAt: result.data.updated_at + }; + }) + }); + progressCommentId = null; + progressCommentIdInitialized = false; + progressCommentWasUpdated = false; + ReportProgress = type({ + body: type.string.describe("the progress update content to share") + }); + ReportProgressTool = tool({ + name: "report_progress", + description: "Share progress on the associated GitHub issue/PR. Call this to post updates as you work. The first call creates a comment, subsequent calls update it. Use this throughout your work to keep stakeholders informed.", + parameters: ReportProgress, + execute: contextualize(async ({ body }) => { + const result = await reportProgress({ body }); + return { + success: true, + ...result + }; + }) + }); + ReplyToReviewComment = type({ + pull_number: type.number.describe("the pull request number"), + comment_id: type.number.describe("the ID of the review comment to reply to"), + body: type.string.describe("the reply text explaining how the feedback was addressed") + }); + ReplyToReviewCommentTool = tool({ + name: "reply_to_review_comment", + description: "Reply to a PR review comment thread explaining how the feedback was addressed. Use this after addressing each review comment to provide specific context about the changes made.", + parameters: ReplyToReviewComment, + execute: contextualize(async ({ pull_number, comment_id, body }, ctx) => { + const bodyWithFooter = addFooter(body, ctx.payload); + const result = await ctx.octokit.rest.pulls.createReplyForReviewComment({ + owner: ctx.owner, + repo: ctx.name, + pull_number, + comment_id, + body: bodyWithFooter + }); + return { + success: true, + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body, + in_reply_to_id: result.data.in_reply_to_id + }; + }) + }); + } +}); + // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js var util2, objectUtil2, ZodParsedType2, getParsedType2; var init_util = __esm({ @@ -25980,7 +40049,7 @@ function getErrorMap2() { return overrideErrorMap2; } var overrideErrorMap2; -var init_errors = __esm({ +var init_errors3 = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js"() { init_en(); overrideErrorMap2 = en_default2; @@ -26010,7 +40079,7 @@ function addIssueToContext2(ctx, issueData) { var makeIssue2, EMPTY_PATH2, ParseStatus2, INVALID2, DIRTY2, OK2, isAborted2, isDirty2, isValid2, isAsync2; var init_parseUtil = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js"() { - init_errors(); + init_errors3(); init_en(); makeIssue2 = (params) => { const { data, path: path3, errorMaps, issueData } = params; @@ -26317,7 +40386,7 @@ var ParseInputLazyPath2, handleResult2, ZodType2, cuidRegex2, cuid2Regex2, ulidR var init_types = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js"() { init_ZodError(); - init_errors(); + init_errors3(); init_errorUtil(); init_parseUtil(); init_util(); @@ -29688,9 +43757,9 @@ __export(external_exports, { util: () => util2, void: () => voidType2 }); -var init_external = __esm({ +var init_external2 = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js"() { - init_errors(); + init_errors3(); init_parseUtil(); init_typeAliases(); init_util(); @@ -29702,8 +43771,8 @@ var init_external = __esm({ // node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js var init_zod = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js"() { - init_external(); - init_external(); + init_external2(); + init_external2(); } }); @@ -59545,7 +73614,7 @@ function prettifyError(error41) { return lines.join("\n"); } var initializer, $ZodError, $ZodRealError; -var init_errors2 = __esm({ +var init_errors4 = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js"() { init_core(); init_util2(); @@ -59578,10 +73647,10 @@ var init_errors2 = __esm({ // node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js var _parse, parse3, _parseAsync, parseAsync, _safeParse, safeParse2, _safeParseAsync, safeParseAsync; -var init_parse = __esm({ +var init_parse2 = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js"() { init_core(); - init_errors2(); + init_errors4(); init_util2(); _parse = (_Err) => (schema2, value2, _ctx, _params) => { const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; @@ -60590,7 +74659,7 @@ var init_schemas = __esm({ init_checks(); init_core(); init_doc(); - init_parse(); + init_parse2(); init_regexes(); init_util2(); init_versions(); @@ -67941,7 +82010,7 @@ function _stringFormat(Class2, format2, fnOrRegex, _params = {}) { return inst; } var TimePrecision; -var init_api = __esm({ +var init_api2 = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js"() { init_checks(); init_schemas(); @@ -67967,8 +82036,8 @@ function _function(params) { var $ZodFunction; var init_function = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/function.js"() { - init_api(); - init_parse(); + init_api2(); + init_parse2(); init_schemas(); init_schemas(); $ZodFunction = class { @@ -69062,8 +83131,8 @@ __export(core_exports2, { var init_core2 = __esm({ "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/index.js"() { init_core(); - init_parse(); - init_errors2(); + init_parse2(); + init_errors4(); init_schemas(); init_checks(); init_versions(); @@ -69073,7 +83142,7 @@ var init_core2 = __esm({ init_registries(); init_doc(); init_function(); - init_api(); + init_api2(); init_to_json_schema(); init_json_schema(); } @@ -69352,7 +83421,7 @@ function parseDateDef(def, refs, overrideDateStrategy) { } } var integerDateParser; -var init_date = __esm({ +var init_date2 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() { init_errorMessages(); integerDateParser = (def, refs) => { @@ -69399,7 +83468,7 @@ function parseDefaultDef(_def, refs) { default: _def.defaultValue() }; } -var init_default = __esm({ +var init_default2 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() { init_parseDef(); } @@ -69465,7 +83534,7 @@ function parseIntersectionDef(def, refs) { } : void 0; } var isJsonSchema7AllOfType; -var init_intersection = __esm({ +var init_intersection2 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() { init_parseDef(); isJsonSchema7AllOfType = (type2) => { @@ -69776,7 +83845,7 @@ function stringifyRegExpWithFlags(regex3, refs) { return pattern; } var emojiRegex4, zodPatterns, ALPHA_NUMERIC2; -var init_string = __esm({ +var init_string3 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() { init_errorMessages(); emojiRegex4 = void 0; @@ -69886,7 +83955,7 @@ var init_record = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() { init_zod(); init_parseDef(); - init_string(); + init_string3(); init_branded(); init_any(); } @@ -70025,7 +84094,7 @@ function parseUnionDef(def, refs) { return asAnyOf(def, refs); } var primitiveMappings, asAnyOf; -var init_union = __esm({ +var init_union2 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() { init_parseDef(); primitiveMappings = { @@ -70079,7 +84148,7 @@ function parseNullableDef(def, refs) { var init_nullable = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() { init_parseDef(); - init_union(); + init_union2(); } }); @@ -70131,7 +84200,7 @@ function parseNumberDef(def, refs) { } return res; } -var init_number = __esm({ +var init_number2 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() { init_errorMessages(); } @@ -70214,7 +84283,7 @@ var init_object = __esm({ // node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js var parseOptionalDef; -var init_optional = __esm({ +var init_optional2 = __esm({ "node_modules/.pnpm/zod-to-json-schema@3.24.6_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() { init_parseDef(); init_any(); @@ -70377,28 +84446,28 @@ var init_selectParser = __esm({ init_boolean(); init_branded(); init_catch(); - init_date(); - init_default(); + init_date2(); + init_default2(); init_effects(); init_enum(); - init_intersection(); + init_intersection2(); init_literal(); init_map(); init_nativeEnum(); init_never(); init_null(); init_nullable(); - init_number(); + init_number2(); init_object(); - init_optional(); + init_optional2(); init_pipeline(); init_promise(); init_record(); init_set(); - init_string(); + init_string3(); init_tuple(); init_undefined(); - init_union(); + init_union2(); init_unknown(); init_readonly(); selectParser = (def, typeName, refs) => { @@ -70682,29 +84751,29 @@ var init_esm = __esm({ init_boolean(); init_branded(); init_catch(); - init_date(); - init_default(); + init_date2(); + init_default2(); init_effects(); init_enum(); - init_intersection(); + init_intersection2(); init_literal(); init_map(); init_nativeEnum(); init_never(); init_null(); init_nullable(); - init_number(); + init_number2(); init_object(); - init_optional(); + init_optional2(); init_pipeline(); init_promise(); init_readonly(); init_record(); init_set(); - init_string(); + init_string3(); init_tuple(); init_undefined(); - init_union(); + init_union2(); init_unknown(); init_selectParser(); init_zodToJsonSchema(); @@ -83327,7 +97396,7 @@ function query({ // package.json var package_default = { name: "@pullfrog/action", - version: "0.0.130", + version: "0.0.131", type: "module", files: [ "index.js", @@ -83400,276 +97469,8 @@ var package_default = { } }; -// utils/cli.ts -var core = __toESM(require_core(), 1); -var import_table = __toESM(require_src(), 1); -var isGitHubActions = !!process.env.GITHUB_ACTIONS; -var isDebugEnabled = () => process.env.LOG_LEVEL === "debug"; -function startGroup2(name) { - if (isGitHubActions) { - core.startGroup(name); - } else { - console.group(name); - } -} -function endGroup2() { - if (isGitHubActions) { - core.endGroup(); - } else { - console.groupEnd(); - } -} -function boxString(text, options) { - const { title, maxWidth = 80, indent: indent2 = "", padding = 1 } = options || {}; - const lines = text.trim().split("\n"); - const wrappedLines = []; - for (const line of lines) { - if (line.length <= maxWidth - padding * 2) { - wrappedLines.push(line); - } else { - const words = line.split(" "); - let currentLine = ""; - for (const word of words) { - const testLine = currentLine ? `${currentLine} ${word}` : word; - if (testLine.length <= maxWidth - padding * 2) { - currentLine = testLine; - } else { - if (currentLine) { - wrappedLines.push(currentLine); - currentLine = ""; - } - const maxLineLength2 = maxWidth - padding * 2; - let remainingWord = word; - while (remainingWord.length > maxLineLength2) { - wrappedLines.push(remainingWord.substring(0, maxLineLength2)); - remainingWord = remainingWord.substring(maxLineLength2); - } - currentLine = remainingWord; - } - } - if (currentLine) { - wrappedLines.push(currentLine); - } - } - } - const maxLineLength = Math.max(...wrappedLines.map((line) => line.length)); - const contentBoxWidth = maxLineLength + padding * 2; - const titleLineLength = title ? ` ${title} `.length : 0; - const boxWidth = Math.max(contentBoxWidth, titleLineLength); - let result = ""; - if (title) { - const titleLine = ` ${title} `; - const titlePadding = Math.max(0, boxWidth - titleLine.length); - result += `${indent2}\u250C${titleLine}${"\u2500".repeat(titlePadding)}\u2510 -`; - } - if (!title) { - result += `${indent2}\u250C${"\u2500".repeat(boxWidth)}\u2510 -`; - } - for (const line of wrappedLines) { - const paddedLine = line.padEnd(maxLineLength); - result += `${indent2}\u2502${" ".repeat(padding)}${paddedLine}${" ".repeat(padding)}\u2502 -`; - } - result += `${indent2}\u2514${"\u2500".repeat(boxWidth)}\u2518`; - return result; -} -function box(text, options) { - const boxContent = boxString(text, options); - core.info(boxContent); - if (isGitHubActions) { - core.summary.addRaw(`\`\`\` -${text} -\`\`\` -`); - } -} -async function summaryTable(rows, options) { - const { title } = options || {}; - const formattedRows = rows.map( - (row) => row.map((cell) => { - if (typeof cell === "string") { - return { data: cell }; - } - return cell; - }) - ); - if (isGitHubActions) { - const summary2 = core.summary; - if (title) { - summary2.addRaw(`**${title}** - -`); - } - summary2.addTable(formattedRows); - } - if (title) { - core.info(` -${title}`); - } - const tableText = formattedRows.map((row) => row.map((cell) => cell.data).join(" | ")).join("\n"); - core.info(` -${tableText} -`); -} -async function printTable(rows, options) { - const { title } = options || {}; - const tableData = rows.map( - (row) => row.map((cell) => { - if (typeof cell === "string") { - return cell; - } - return cell.data; - }) - ); - const formatted = (0, import_table.table)(tableData); - if (title) { - core.info(` -${title}`); - } - core.info(` -${formatted} -`); - if (isGitHubActions) { - if (title) { - core.summary.addRaw(`**${title}** - -`); - } - core.summary.addRaw(`\`\`\` -${formatted} -\`\`\` -`); - } -} -function separator(length = 50) { - const separatorText = "\u2500".repeat(length); - core.info(separatorText); - if (isGitHubActions) { - core.summary.addRaw(`--- -`); - } -} -var log = { - /** - * Print info message - */ - info: (message) => { - core.info(message); - if (isGitHubActions) { - core.summary.addRaw(`${message} -`); - } - }, - /** - * Print warning message - */ - warning: (message) => { - core.warning(message); - if (isGitHubActions) { - core.summary.addRaw(`\u26A0\uFE0F ${message} -`); - } - }, - /** - * Print error message - */ - error: (message) => { - core.error(message); - if (isGitHubActions) { - core.summary.addRaw(`\u274C ${message} -`); - } - }, - /** - * Print success message - */ - success: (message) => { - const successMessage = `\u2705 ${message}`; - core.info(successMessage); - if (isGitHubActions) { - core.summary.addRaw(`${successMessage} -`); - } - }, - /** - * Print debug message (only if LOG_LEVEL=debug) - */ - debug: (message) => { - if (isDebugEnabled()) { - if (isGitHubActions) { - core.debug(message); - } else { - core.info(`[DEBUG] ${message}`); - } - } - }, - /** - * Print a formatted box with text - */ - box, - /** - * Add a table to GitHub Actions job summary (rich formatting) - * Only use this once at the end of execution - */ - summaryTable, - /** - * Print a formatted table using the table package - */ - table: printTable, - /** - * Print a separator line - */ - separator, - /** - * Write all accumulated summary content to the job summary - * Call this at the end of execution to finalize the summary - */ - writeSummary: async () => { - if (isGitHubActions) { - await core.summary.write(); - } - }, - /** - * Start a collapsed group (GitHub Actions) or regular group (local) - */ - startGroup: startGroup2, - /** - * End a collapsed group - */ - endGroup: endGroup2, - /** - * Log tool call information to console with formatted output - */ - toolCall: ({ toolName, input }) => { - let output = `\u2192 ${toolName} -`; - const inputFormatted = formatJsonValue(input); - if (inputFormatted !== "{}") { - output += formatIndentedField("input", inputFormatted); - } - log.info(output.trimEnd()); - } -}; -function formatJsonValue(value2) { - const compact = JSON.stringify(value2); - return compact.length > 80 || compact.includes("\n") ? JSON.stringify(value2, null, 2) : compact; -} -function formatIndentedField(label, content) { - if (!content.includes("\n")) { - return ` ${label}: ${content} -`; - } - const lines = content.split("\n"); - let formatted = ` ${label}: ${lines[0]} -`; - for (let i = 1; i < lines.length; i++) { - formatted += ` ${lines[i]} -`; - } - return formatted; -} +// agents/claude.ts +init_cli(); // ../node_modules/.pnpm/@toon-format+toon@1.0.0/node_modules/@toon-format/toon/dist/index.js var LIST_ITEM_MARKER = "-"; @@ -84053,8504 +97854,11 @@ function resolveOptions(options) { }; } -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/arrays.js -var liftArray = (data) => Array.isArray(data) ? data : [data]; -var spliterate = (arr, predicate) => { - const result = [[], []]; - for (const item of arr) { - if (predicate(item)) - result[0].push(item); - else - result[1].push(item); - } - return result; -}; -var ReadonlyArray2 = Array; -var includes = (array, element) => array.includes(element); -var range = (length, offset = 0) => [...new Array(length)].map((_, i) => i + offset); -var append2 = (to, value2, opts) => { - if (to === void 0) { - return value2 === void 0 ? [] : Array.isArray(value2) ? value2 : [value2]; - } - if (opts?.prepend) { - if (Array.isArray(value2)) - to.unshift(...value2); - else - to.unshift(value2); - } else { - if (Array.isArray(value2)) - to.push(...value2); - else - to.push(value2); - } - return to; -}; -var conflatenate = (to, elementOrList) => { - if (elementOrList === void 0 || elementOrList === null) - return to ?? []; - if (to === void 0 || to === null) - return liftArray(elementOrList); - return to.concat(elementOrList); -}; -var conflatenateAll = (...elementsOrLists) => elementsOrLists.reduce(conflatenate, []); -var appendUnique = (to, value2, opts) => { - if (to === void 0) - return Array.isArray(value2) ? value2 : [value2]; - const isEqual = opts?.isEqual ?? ((l, r) => l === r); - for (const v of liftArray(value2)) - if (!to.some((existing) => isEqual(existing, v))) - to.push(v); - return to; -}; -var groupBy = (array, discriminant) => array.reduce((result, item) => { - const key = item[discriminant]; - result[key] = append2(result[key], item); - return result; -}, {}); -var arrayEquals = (l, r, opts) => l.length === r.length && l.every(opts?.isEqual ? (lItem, i) => opts.isEqual(lItem, r[i]) : (lItem, i) => lItem === r[i]); - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/domain.js -var hasDomain2 = (data, kind) => domainOf2(data) === kind; -var domainOf2 = (data) => { - const builtinType = typeof data; - return builtinType === "object" ? data === null ? "null" : "object" : builtinType === "function" ? "object" : builtinType; -}; -var domainDescriptions2 = { - boolean: "boolean", - null: "null", - undefined: "undefined", - bigint: "a bigint", - number: "a number", - object: "an object", - string: "a string", - symbol: "a symbol" -}; -var jsTypeOfDescriptions2 = { - ...domainDescriptions2, - function: "a function" -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/errors.js -var InternalArktypeError = class extends Error { -}; -var throwInternalError2 = (message) => throwError(message, InternalArktypeError); -var throwError = (message, ctor = Error) => { - throw new ctor(message); -}; -var ParseError = class extends Error { - name = "ParseError"; -}; -var throwParseError2 = (message) => throwError(message, ParseError); -var noSuggest2 = (s) => ` ${s}`; -var ZeroWidthSpace2 = "\u200B"; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/flatMorph.js -var flatMorph2 = (o, flatMapEntry) => { - const result = {}; - const inputIsArray = Array.isArray(o); - let outputShouldBeArray = false; - for (const [i, entry] of Object.entries(o).entries()) { - const mapped = inputIsArray ? flatMapEntry(i, entry[1]) : flatMapEntry(...entry, i); - outputShouldBeArray ||= typeof mapped[0] === "number"; - const flattenedEntries = Array.isArray(mapped[0]) || mapped.length === 0 ? ( - // if we have an empty array (for filtering) or an array with - // another array as its first element, treat it as a list - mapped - ) : [mapped]; - for (const [k, v] of flattenedEntries) { - if (typeof k === "object") - result[k.group] = append2(result[k.group], v); - else - result[k] = v; - } - } - return outputShouldBeArray ? Object.values(result) : result; -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/records.js -var entriesOf = Object.entries; -var isKeyOf2 = (k, o) => k in o; -var hasKey = (o, k) => k in o; -var DynamicBase = class { - constructor(properties) { - Object.assign(this, properties); - } -}; -var NoopBase2 = class { -}; -var CastableBase = class extends NoopBase2 { -}; -var splitByKeys = (o, leftKeys) => { - const l = {}; - const r = {}; - let k; - for (k in o) { - if (k in leftKeys) - l[k] = o[k]; - else - r[k] = o[k]; - } - return [l, r]; -}; -var omit = (o, keys) => splitByKeys(o, keys)[1]; -var isEmptyObject2 = (o) => Object.keys(o).length === 0; -var stringAndSymbolicEntriesOf2 = (o) => [ - ...Object.entries(o), - ...Object.getOwnPropertySymbols(o).map((k) => [k, o[k]]) -]; -var defineProperties = (base, merged) => ( - // declared like this to avoid https://github.com/microsoft/TypeScript/issues/55049 - Object.defineProperties(base, Object.getOwnPropertyDescriptors(merged)) -); -var withAlphabetizedKeys = (o) => { - const keys = Object.keys(o).sort(); - const result = {}; - for (let i = 0; i < keys.length; i++) - result[keys[i]] = o[keys[i]]; - return result; -}; -var unset2 = noSuggest2(`unset${ZeroWidthSpace2}`); -var enumValues = (tsEnum) => Object.values(tsEnum).filter((v) => { - if (typeof v === "number") - return true; - return typeof tsEnum[v] !== "number"; -}); - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/objectKinds.js -var ecmascriptConstructors2 = { - Array, - Boolean, - Date, - Error, - Function, - Map, - Number, - Promise, - RegExp, - Set, - String, - WeakMap, - WeakSet -}; -var FileConstructor2 = globalThis.File ?? Blob; -var platformConstructors2 = { - ArrayBuffer, - Blob, - File: FileConstructor2, - FormData, - Headers, - Request, - Response, - URL -}; -var typedArrayConstructors2 = { - Int8Array, - Uint8Array, - Uint8ClampedArray, - Int16Array, - Uint16Array, - Int32Array, - Uint32Array, - Float32Array, - Float64Array, - BigInt64Array, - BigUint64Array -}; -var builtinConstructors2 = { - ...ecmascriptConstructors2, - ...platformConstructors2, - ...typedArrayConstructors2, - String, - Number, - Boolean -}; -var objectKindOf2 = (data) => { - let prototype = Object.getPrototypeOf(data); - while (prototype?.constructor && (!isKeyOf2(prototype.constructor.name, builtinConstructors2) || !(data instanceof builtinConstructors2[prototype.constructor.name]))) - prototype = Object.getPrototypeOf(prototype); - const name = prototype?.constructor?.name; - if (name === void 0 || name === "Object") - return void 0; - return name; -}; -var objectKindOrDomainOf = (data) => typeof data === "object" && data !== null ? objectKindOf2(data) ?? "object" : domainOf2(data); -var isArray = Array.isArray; -var ecmascriptDescriptions2 = { - Array: "an array", - Function: "a function", - Date: "a Date", - RegExp: "a RegExp", - Error: "an Error", - Map: "a Map", - Set: "a Set", - String: "a String object", - Number: "a Number object", - Boolean: "a Boolean object", - Promise: "a Promise", - WeakMap: "a WeakMap", - WeakSet: "a WeakSet" -}; -var platformDescriptions2 = { - ArrayBuffer: "an ArrayBuffer instance", - Blob: "a Blob instance", - File: "a File instance", - FormData: "a FormData instance", - Headers: "a Headers instance", - Request: "a Request instance", - Response: "a Response instance", - URL: "a URL instance" -}; -var typedArrayDescriptions2 = { - Int8Array: "an Int8Array", - Uint8Array: "a Uint8Array", - Uint8ClampedArray: "a Uint8ClampedArray", - Int16Array: "an Int16Array", - Uint16Array: "a Uint16Array", - Int32Array: "an Int32Array", - Uint32Array: "a Uint32Array", - Float32Array: "a Float32Array", - Float64Array: "a Float64Array", - BigInt64Array: "a BigInt64Array", - BigUint64Array: "a BigUint64Array" -}; -var objectKindDescriptions2 = { - ...ecmascriptDescriptions2, - ...platformDescriptions2, - ...typedArrayDescriptions2 -}; -var getBuiltinNameOfConstructor2 = (ctor) => { - const constructorName = Object(ctor).name ?? null; - return constructorName && isKeyOf2(constructorName, builtinConstructors2) && builtinConstructors2[constructorName] === ctor ? constructorName : null; -}; -var constructorExtends = (ctor, base) => { - let current = ctor.prototype; - while (current !== null) { - if (current === base.prototype) - return true; - current = Object.getPrototypeOf(current); - } - return false; -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/clone.js -var deepClone = (input) => _clone(input, /* @__PURE__ */ new Map()); -var _clone = (input, seen) => { - if (typeof input !== "object" || input === null) - return input; - if (seen?.has(input)) - return seen.get(input); - const builtinConstructorName = getBuiltinNameOfConstructor2(input.constructor); - if (builtinConstructorName === "Date") - return new Date(input.getTime()); - if (builtinConstructorName && builtinConstructorName !== "Array") - return input; - const cloned = Array.isArray(input) ? input.slice() : Object.create(Object.getPrototypeOf(input)); - const propertyDescriptors = Object.getOwnPropertyDescriptors(input); - if (seen) { - seen.set(input, cloned); - for (const k in propertyDescriptors) { - const desc = propertyDescriptors[k]; - if ("get" in desc || "set" in desc) - continue; - desc.value = _clone(desc.value, seen); - } - } - Object.defineProperties(cloned, propertyDescriptors); - return cloned; -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/functions.js -var cached2 = (thunk) => { - let result = unset2; - return () => result === unset2 ? result = thunk() : result; -}; -var isThunk = (value2) => typeof value2 === "function" && value2.length === 0; -var DynamicFunction = class extends Function { - constructor(...args3) { - const params = args3.slice(0, -1); - const body = args3[args3.length - 1]; - try { - super(...params, body); - } catch (e) { - return throwInternalError2(`Encountered an unexpected error while compiling your definition: - Message: ${e} - Source: (${args3.slice(0, -1)}) => { - ${args3[args3.length - 1]} - }`); - } - } -}; -var Callable = class { - constructor(fn2, ...[opts]) { - return Object.assign(Object.setPrototypeOf(fn2.bind(opts?.bind ?? this), this.constructor.prototype), opts?.attach); - } -}; -var envHasCsp2 = cached2(() => { - try { - return new Function("return false")(); - } catch { - return true; - } -}); - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/generics.js -var brand2 = noSuggest2("brand"); -var inferred2 = noSuggest2("arkInferred"); - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/hkt.js -var args2 = noSuggest2("args"); -var Hkt = class { - constructor() { - } -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/isomorphic.js -var fileName2 = () => { - try { - const error41 = new Error(); - const stackLine = error41.stack?.split("\n")[2]?.trim() || ""; - const filePath = stackLine.match(/\(?(.+?)(?::\d+:\d+)?\)?$/)?.[1] || "unknown"; - return filePath.replace(/^file:\/\//, ""); - } catch { - return "unknown"; - } -}; -var env2 = globalThis.process?.env ?? {}; -var isomorphic2 = { - fileName: fileName2, - env: env2 -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/strings.js -var capitalize = (s) => s[0].toUpperCase() + s.slice(1); -var uncapitalize = (s) => s[0].toLowerCase() + s.slice(1); -var anchoredRegex2 = (regex3) => new RegExp(anchoredSource2(regex3), typeof regex3 === "string" ? "" : regex3.flags); -var anchoredSource2 = (regex3) => { - const source = typeof regex3 === "string" ? regex3 : regex3.source; - return `^(?:${source})$`; -}; -var RegexPatterns2 = { - negativeLookahead: (pattern) => `(?!${pattern})`, - nonCapturingGroup: (pattern) => `(?:${pattern})` -}; -var Backslash2 = "\\"; -var whitespaceChars2 = { - " ": 1, - "\n": 1, - " ": 1 -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/numbers.js -var anchoredNegativeZeroPattern2 = /^-0\.?0*$/.source; -var positiveIntegerPattern2 = /[1-9]\d*/.source; -var looseDecimalPattern2 = /\.\d+/.source; -var strictDecimalPattern2 = /\.\d*[1-9]/.source; -var createNumberMatcher2 = (opts) => anchoredRegex2(RegexPatterns2.negativeLookahead(anchoredNegativeZeroPattern2) + RegexPatterns2.nonCapturingGroup("-?" + RegexPatterns2.nonCapturingGroup(RegexPatterns2.nonCapturingGroup("0|" + positiveIntegerPattern2) + RegexPatterns2.nonCapturingGroup(opts.decimalPattern) + "?") + (opts.allowDecimalOnly ? "|" + opts.decimalPattern : "") + "?")); -var wellFormedNumberMatcher2 = createNumberMatcher2({ - decimalPattern: strictDecimalPattern2, - allowDecimalOnly: false -}); -var isWellFormedNumber2 = wellFormedNumberMatcher2.test.bind(wellFormedNumberMatcher2); -var numericStringMatcher2 = createNumberMatcher2({ - decimalPattern: looseDecimalPattern2, - allowDecimalOnly: true -}); -var isNumericString2 = numericStringMatcher2.test.bind(numericStringMatcher2); -var numberLikeMatcher = /^-?\d*\.?\d*$/; -var isNumberLike = (s) => s.length !== 0 && numberLikeMatcher.test(s); -var wellFormedIntegerMatcher2 = anchoredRegex2(RegexPatterns2.negativeLookahead("^-0$") + "-?" + RegexPatterns2.nonCapturingGroup(RegexPatterns2.nonCapturingGroup("0|" + positiveIntegerPattern2))); -var isWellFormedInteger2 = wellFormedIntegerMatcher2.test.bind(wellFormedIntegerMatcher2); -var integerLikeMatcher2 = /^-?\d+$/; -var isIntegerLike2 = integerLikeMatcher2.test.bind(integerLikeMatcher2); -var numericLiteralDescriptions = { - number: "a number", - bigint: "a bigint", - integer: "an integer" -}; -var writeMalformedNumericLiteralMessage = (def, kind) => `'${def}' was parsed as ${numericLiteralDescriptions[kind]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`; -var isWellFormed = (def, kind) => kind === "number" ? isWellFormedNumber2(def) : isWellFormedInteger2(def); -var parseKind = (def, kind) => kind === "number" ? Number(def) : Number.parseInt(def); -var isKindLike = (def, kind) => kind === "number" ? isNumberLike(def) : isIntegerLike2(def); -var tryParseNumber = (token, options) => parseNumeric(token, "number", options); -var tryParseWellFormedNumber = (token, options) => parseNumeric(token, "number", { ...options, strict: true }); -var tryParseInteger = (token, options) => parseNumeric(token, "integer", options); -var parseNumeric = (token, kind, options) => { - const value2 = parseKind(token, kind); - if (!Number.isNaN(value2)) { - if (isKindLike(token, kind)) { - if (options?.strict) { - return isWellFormed(token, kind) ? value2 : throwParseError2(writeMalformedNumericLiteralMessage(token, kind)); - } - return value2; - } - } - return options?.errorOnFail ? throwParseError2(options?.errorOnFail === true ? `Failed to parse ${numericLiteralDescriptions[kind]} from '${token}'` : options?.errorOnFail) : void 0; -}; -var tryParseWellFormedBigint = (def) => { - if (def[def.length - 1] !== "n") - return; - const maybeIntegerLiteral = def.slice(0, -1); - let value2; - try { - value2 = BigInt(maybeIntegerLiteral); - } catch { - return; - } - if (wellFormedIntegerMatcher2.test(maybeIntegerLiteral)) - return value2; - if (integerLikeMatcher2.test(maybeIntegerLiteral)) { - return throwParseError2(writeMalformedNumericLiteralMessage(def, "bigint")); - } -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/registry.js -var arkUtilVersion2 = "0.56.0"; -var initialRegistryContents2 = { - version: arkUtilVersion2, - filename: isomorphic2.fileName(), - FileConstructor: FileConstructor2 -}; -var registry = initialRegistryContents2; -var namesByResolution = /* @__PURE__ */ new Map(); -var nameCounts = /* @__PURE__ */ Object.create(null); -var register2 = (value2) => { - const existingName = namesByResolution.get(value2); - if (existingName) - return existingName; - let name = baseNameFor(value2); - if (nameCounts[name]) - name = `${name}${nameCounts[name]++}`; - else - nameCounts[name] = 1; - registry[name] = value2; - namesByResolution.set(value2, name); - return name; -}; -var isDotAccessible2 = (keyName) => /^[$A-Z_a-z][\w$]*$/.test(keyName); -var baseNameFor = (value2) => { - switch (typeof value2) { - case "object": { - if (value2 === null) - break; - const prefix = objectKindOf2(value2) ?? "object"; - return prefix[0].toLowerCase() + prefix.slice(1); - } - case "function": - return isDotAccessible2(value2.name) ? value2.name : "fn"; - case "symbol": - return value2.description && isDotAccessible2(value2.description) ? value2.description : "symbol"; - } - return throwInternalError2(`Unexpected attempt to register serializable value of type ${domainOf2(value2)}`); -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/primitive.js -var serializePrimitive2 = (value2) => typeof value2 === "string" ? JSON.stringify(value2) : typeof value2 === "bigint" ? `${value2}n` : `${value2}`; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/serialize.js -var snapshot = (data, opts = {}) => _serialize(data, { - onUndefined: `$ark.undefined`, - onBigInt: (n) => `$ark.bigint-${n}`, - ...opts -}, []); -var printable2 = (data, opts) => { - switch (domainOf2(data)) { - case "object": - const o = data; - const ctorName = o.constructor?.name ?? "Object"; - return ctorName === "Object" || ctorName === "Array" ? opts?.quoteKeys === false ? stringifyUnquoted(o, opts?.indent ?? 0, "") : JSON.stringify(_serialize(o, printableOpts, []), null, opts?.indent) : stringifyUnquoted(o, opts?.indent ?? 0, ""); - case "symbol": - return printableOpts.onSymbol(data); - default: - return serializePrimitive2(data); - } -}; -var stringifyUnquoted = (value2, indent2, currentIndent) => { - if (typeof value2 === "function") - return printableOpts.onFunction(value2); - if (typeof value2 !== "object" || value2 === null) - return serializePrimitive2(value2); - const nextIndent = currentIndent + " ".repeat(indent2); - if (Array.isArray(value2)) { - if (value2.length === 0) - return "[]"; - const items = value2.map((item) => stringifyUnquoted(item, indent2, nextIndent)).join(",\n" + nextIndent); - return indent2 ? `[ -${nextIndent}${items} -${currentIndent}]` : `[${items}]`; - } - const ctorName = value2.constructor?.name ?? "Object"; - if (ctorName === "Object") { - const keyValues = stringAndSymbolicEntriesOf2(value2).map(([key, val]) => { - const stringifiedKey = typeof key === "symbol" ? printableOpts.onSymbol(key) : isDotAccessible2(key) ? key : JSON.stringify(key); - const stringifiedValue = stringifyUnquoted(val, indent2, nextIndent); - return `${nextIndent}${stringifiedKey}: ${stringifiedValue}`; - }); - if (keyValues.length === 0) - return "{}"; - return indent2 ? `{ -${keyValues.join(",\n")} -${currentIndent}}` : `{${keyValues.join(", ")}}`; - } - if (value2 instanceof Date) - return describeCollapsibleDate(value2); - if ("expression" in value2 && typeof value2.expression === "string") - return value2.expression; - return ctorName; -}; -var printableOpts = { - onCycle: () => "(cycle)", - onSymbol: (v) => `Symbol(${register2(v)})`, - onFunction: (v) => `Function(${register2(v)})` -}; -var _serialize = (data, opts, seen) => { - switch (domainOf2(data)) { - case "object": { - const o = data; - if ("toJSON" in o && typeof o.toJSON === "function") - return o.toJSON(); - if (typeof o === "function") - return printableOpts.onFunction(o); - if (seen.includes(o)) - return "(cycle)"; - const nextSeen = [...seen, o]; - if (Array.isArray(o)) - return o.map((item) => _serialize(item, opts, nextSeen)); - if (o instanceof Date) - return o.toDateString(); - const result = {}; - for (const k in o) - result[k] = _serialize(o[k], opts, nextSeen); - for (const s of Object.getOwnPropertySymbols(o)) { - result[opts.onSymbol?.(s) ?? s.toString()] = _serialize(o[s], opts, nextSeen); - } - return result; - } - case "symbol": - return printableOpts.onSymbol(data); - case "bigint": - return opts.onBigInt?.(data) ?? `${data}n`; - case "undefined": - return opts.onUndefined ?? "undefined"; - case "string": - return data.replace(/\\/g, "\\\\"); - default: - return data; - } -}; -var describeCollapsibleDate = (date2) => { - const year = date2.getFullYear(); - const month = date2.getMonth(); - const dayOfMonth = date2.getDate(); - const hours = date2.getHours(); - const minutes = date2.getMinutes(); - const seconds = date2.getSeconds(); - const milliseconds = date2.getMilliseconds(); - if (month === 0 && dayOfMonth === 1 && hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0) - return `${year}`; - const datePortion = `${months[month]} ${dayOfMonth}, ${year}`; - if (hours === 0 && minutes === 0 && seconds === 0 && milliseconds === 0) - return datePortion; - let timePortion = date2.toLocaleTimeString(); - const suffix2 = timePortion.endsWith(" AM") || timePortion.endsWith(" PM") ? timePortion.slice(-3) : ""; - if (suffix2) - timePortion = timePortion.slice(0, -suffix2.length); - if (milliseconds) - timePortion += `.${pad(milliseconds, 3)}`; - else if (timeWithUnnecessarySeconds.test(timePortion)) - timePortion = timePortion.slice(0, -3); - return `${timePortion + suffix2}, ${datePortion}`; -}; -var months = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" -]; -var timeWithUnnecessarySeconds = /:\d\d:00$/; -var pad = (value2, length) => String(value2).padStart(length, "0"); - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/path.js -var appendStringifiedKey = (path3, prop, ...[opts]) => { - const stringifySymbol = opts?.stringifySymbol ?? printable2; - let propAccessChain = path3; - switch (typeof prop) { - case "string": - propAccessChain = isDotAccessible2(prop) ? path3 === "" ? prop : `${path3}.${prop}` : `${path3}[${JSON.stringify(prop)}]`; - break; - case "number": - propAccessChain = `${path3}[${prop}]`; - break; - case "symbol": - propAccessChain = `${path3}[${stringifySymbol(prop)}]`; - break; - default: - if (opts?.stringifyNonKey) - propAccessChain = `${path3}[${opts.stringifyNonKey(prop)}]`; - else { - throwParseError2(`${printable2(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`); - } - } - return propAccessChain; -}; -var stringifyPath = (path3, ...opts) => path3.reduce((s, k) => appendStringifiedKey(s, k, ...opts), ""); -var ReadonlyPath = class extends ReadonlyArray2 { - // alternate strategy for caching since the base object is frozen - cache = {}; - constructor(...items) { - super(); - this.push(...items); - } - toJSON() { - if (this.cache.json) - return this.cache.json; - this.cache.json = []; - for (let i = 0; i < this.length; i++) { - this.cache.json.push(typeof this[i] === "symbol" ? printable2(this[i]) : this[i]); - } - return this.cache.json; - } - stringify() { - if (this.cache.stringify) - return this.cache.stringify; - return this.cache.stringify = stringifyPath(this); - } - stringifyAncestors() { - if (this.cache.stringifyAncestors) - return this.cache.stringifyAncestors; - let propString = ""; - const result = [propString]; - for (const path3 of this) { - propString = appendStringifiedKey(propString, path3); - result.push(propString); - } - return this.cache.stringifyAncestors = result; - } -}; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/scanner.js -var Scanner = class { - chars; - i; - def; - constructor(def) { - this.def = def; - this.chars = [...def]; - this.i = 0; - } - /** Get lookahead and advance scanner by one */ - shift() { - return this.chars[this.i++] ?? ""; - } - get lookahead() { - return this.chars[this.i] ?? ""; - } - get nextLookahead() { - return this.chars[this.i + 1] ?? ""; - } - get length() { - return this.chars.length; - } - shiftUntil(condition) { - let shifted = ""; - while (this.lookahead) { - if (condition(this, shifted)) - break; - else - shifted += this.shift(); - } - return shifted; - } - shiftUntilEscapable(condition) { - let shifted = ""; - while (this.lookahead) { - if (this.lookahead === Backslash2) { - this.shift(); - if (condition(this, shifted)) - shifted += this.shift(); - else if (this.lookahead === Backslash2) - shifted += this.shift(); - else - shifted += `${Backslash2}${this.shift()}`; - } else if (condition(this, shifted)) - break; - else - shifted += this.shift(); - } - return shifted; - } - shiftUntilLookahead(charOrSet) { - return typeof charOrSet === "string" ? this.shiftUntil((s) => s.lookahead === charOrSet) : this.shiftUntil((s) => s.lookahead in charOrSet); - } - shiftUntilNonWhitespace() { - return this.shiftUntil(() => !(this.lookahead in whitespaceChars2)); - } - jumpToIndex(i) { - this.i = i < 0 ? this.length + i : i; - } - jumpForward(count) { - this.i += count; - } - get location() { - return this.i; - } - get unscanned() { - return this.chars.slice(this.i, this.length).join(""); - } - get scanned() { - return this.chars.slice(0, this.i).join(""); - } - sliceChars(start, end) { - return this.chars.slice(start, end).join(""); - } - lookaheadIs(char) { - return this.lookahead === char; - } - lookaheadIsIn(tokens) { - return this.lookahead in tokens; - } -}; -var writeUnmatchedGroupCloseMessage = (char, unscanned) => `Unmatched ${char}${unscanned === "" ? "" : ` before ${unscanned}`}`; -var writeUnclosedGroupMessage = (missingChar) => `Missing ${missingChar}`; - -// node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/traits.js -var implementedTraits2 = noSuggest2("implementedTraits"); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/registry.js -var _registryName = "$ark"; -var suffix = 2; -while (_registryName in globalThis) - _registryName = `$ark${suffix++}`; -var registryName = _registryName; -globalThis[registryName] = registry; -var $ark = registry; -var reference = (name) => `${registryName}.${name}`; -var registeredReference = (value2) => reference(register2(value2)); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/compile.js -var CompiledFunction = class extends CastableBase { - argNames; - body = ""; - constructor(...args3) { - super(); - this.argNames = args3; - for (const arg of args3) { - if (arg in this) { - throw new Error(`Arg name '${arg}' would overwrite an existing property on FunctionBody`); - } - ; - this[arg] = arg; - } - } - indentation = 0; - indent() { - this.indentation += 4; - return this; - } - dedent() { - this.indentation -= 4; - return this; - } - prop(key, optional = false) { - return compileLiteralPropAccess(key, optional); - } - index(key, optional = false) { - return indexPropAccess(`${key}`, optional); - } - line(statement) { - ; - this.body += `${" ".repeat(this.indentation)}${statement} -`; - return this; - } - const(identifier, expression) { - this.line(`const ${identifier} = ${expression}`); - return this; - } - let(identifier, expression) { - return this.line(`let ${identifier} = ${expression}`); - } - set(identifier, expression) { - return this.line(`${identifier} = ${expression}`); - } - if(condition, then) { - return this.block(`if (${condition})`, then); - } - elseIf(condition, then) { - return this.block(`else if (${condition})`, then); - } - else(then) { - return this.block("else", then); - } - /** Current index is "i" */ - for(until, body, initialValue = 0) { - return this.block(`for (let i = ${initialValue}; ${until}; i++)`, body); - } - /** Current key is "k" */ - forIn(object2, body) { - return this.block(`for (const k in ${object2})`, body); - } - block(prefix, contents, suffix2 = "") { - this.line(`${prefix} {`); - this.indent(); - contents(this); - this.dedent(); - return this.line(`}${suffix2}`); - } - return(expression = "") { - return this.line(`return ${expression}`); - } - write(name = "anonymous", indent2 = 0) { - return `${name}(${this.argNames.join(", ")}) { ${indent2 ? this.body.split("\n").map((l) => " ".repeat(indent2) + `${l}`).join("\n") : this.body} }`; - } - compile() { - return new DynamicFunction(...this.argNames, this.body); - } -}; -var compileSerializedValue = (value2) => hasDomain2(value2, "object") || typeof value2 === "symbol" ? registeredReference(value2) : serializePrimitive2(value2); -var compileLiteralPropAccess = (key, optional = false) => { - if (typeof key === "string" && isDotAccessible2(key)) - return `${optional ? "?" : ""}.${key}`; - return indexPropAccess(serializeLiteralKey(key), optional); -}; -var serializeLiteralKey = (key) => typeof key === "symbol" ? registeredReference(key) : JSON.stringify(key); -var indexPropAccess = (key, optional = false) => `${optional ? "?." : ""}[${key}]`; -var NodeCompiler = class extends CompiledFunction { - traversalKind; - optimistic; - constructor(ctx) { - super("data", "ctx"); - this.traversalKind = ctx.kind; - this.optimistic = ctx.optimistic === true; - } - invoke(node2, opts) { - const arg = opts?.arg ?? this.data; - const requiresContext = typeof node2 === "string" ? true : this.requiresContextFor(node2); - const id = typeof node2 === "string" ? node2 : node2.id; - if (requiresContext) - return `${this.referenceToId(id, opts)}(${arg}, ${this.ctx})`; - return `${this.referenceToId(id, opts)}(${arg})`; - } - referenceToId(id, opts) { - const invokedKind = opts?.kind ?? this.traversalKind; - const base = `this.${id}${invokedKind}`; - return opts?.bind ? `${base}.bind(${opts?.bind})` : base; - } - requiresContextFor(node2) { - return this.traversalKind === "Apply" || node2.allowsRequiresContext; - } - initializeErrorCount() { - return this.const("errorCount", "ctx.currentErrorCount"); - } - returnIfFail() { - return this.if("ctx.currentErrorCount > errorCount", () => this.return()); - } - returnIfFailFast() { - return this.if("ctx.failFast && ctx.currentErrorCount > errorCount", () => this.return()); - } - traverseKey(keyExpression, accessExpression, node2) { - const requiresContext = this.requiresContextFor(node2); - if (requiresContext) - this.line(`${this.ctx}.path.push(${keyExpression})`); - this.check(node2, { - arg: accessExpression - }); - if (requiresContext) - this.line(`${this.ctx}.path.pop()`); - return this; - } - check(node2, opts) { - return this.traversalKind === "Allows" ? this.if(`!${this.invoke(node2, opts)}`, () => this.return(false)) : this.line(this.invoke(node2, opts)); - } -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/utils.js -var makeRootAndArrayPropertiesMutable = (o) => ( - // this cast should not be required, but it seems TS is referencing - // the wrong parameters here? - flatMorph2(o, (k, v) => [k, isArray(v) ? [...v] : v]) -); -var arkKind = noSuggest2("arkKind"); -var hasArkKind = (value2, kind) => value2?.[arkKind] === kind; -var isNode = (value2) => hasArkKind(value2, "root") || hasArkKind(value2, "constraint"); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/implement.js -var basisKinds = ["unit", "proto", "domain"]; -var structuralKinds = [ - "required", - "optional", - "index", - "sequence" -]; -var prestructuralKinds = [ - "pattern", - "divisor", - "exactLength", - "max", - "min", - "maxLength", - "minLength", - "before", - "after" -]; -var refinementKinds = [ - ...prestructuralKinds, - "structure", - "predicate" -]; -var constraintKinds = [...refinementKinds, ...structuralKinds]; -var rootKinds = [ - "alias", - "union", - "morph", - "unit", - "intersection", - "proto", - "domain" -]; -var nodeKinds = [...rootKinds, ...constraintKinds]; -var constraintKeys = flatMorph2(constraintKinds, (i, kind) => [kind, 1]); -var structureKeys = flatMorph2([...structuralKinds, "undeclared"], (i, k) => [k, 1]); -var precedenceByKind = flatMorph2(nodeKinds, (i, kind) => [kind, i]); -var isNodeKind = (value2) => typeof value2 === "string" && value2 in precedenceByKind; -var precedenceOfKind = (kind) => precedenceByKind[kind]; -var schemaKindsRightOf = (kind) => rootKinds.slice(precedenceOfKind(kind) + 1); -var unionChildKinds = [ - ...schemaKindsRightOf("union"), - "alias" -]; -var morphChildKinds = [ - ...schemaKindsRightOf("morph"), - "alias" -]; -var defaultValueSerializer = (v) => { - if (typeof v === "string" || typeof v === "boolean" || v === null) - return v; - if (typeof v === "number") { - if (Number.isNaN(v)) - return "NaN"; - if (v === Number.POSITIVE_INFINITY) - return "Infinity"; - if (v === Number.NEGATIVE_INFINITY) - return "-Infinity"; - return v; - } - return compileSerializedValue(v); -}; -var compileObjectLiteral = (ctx) => { - let result = "{ "; - for (const [k, v] of Object.entries(ctx)) - result += `${k}: ${compileSerializedValue(v)}, `; - return result + " }"; -}; -var implementNode = (_) => { - const implementation23 = _; - if (implementation23.hasAssociatedError) { - implementation23.defaults.expected ??= (ctx) => "description" in ctx ? ctx.description : implementation23.defaults.description(ctx); - implementation23.defaults.actual ??= (data) => printable2(data); - implementation23.defaults.problem ??= (ctx) => `must be ${ctx.expected}${ctx.actual ? ` (was ${ctx.actual})` : ""}`; - implementation23.defaults.message ??= (ctx) => { - if (ctx.path.length === 0) - return ctx.problem; - const problemWithLocation = `${ctx.propString} ${ctx.problem}`; - if (problemWithLocation[0] === "[") { - return `value at ${problemWithLocation}`; - } - return problemWithLocation; - }; - } - return implementation23; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/toJsonSchema.js -var ToJsonSchemaError = class extends Error { - name = "ToJsonSchemaError"; - code; - context; - constructor(code, context) { - super(printable2(context, { quoteKeys: false, indent: 4 })); - this.code = code; - this.context = context; - } - hasCode(code) { - return this.code === code; - } -}; -var defaultConfig = { - target: "draft-2020-12", - dialect: "https://json-schema.org/draft/2020-12/schema", - useRefs: false, - fallback: { - arrayObject: (ctx) => ToJsonSchema.throw("arrayObject", ctx), - arrayPostfix: (ctx) => ToJsonSchema.throw("arrayPostfix", ctx), - defaultValue: (ctx) => ToJsonSchema.throw("defaultValue", ctx), - domain: (ctx) => ToJsonSchema.throw("domain", ctx), - morph: (ctx) => ToJsonSchema.throw("morph", ctx), - patternIntersection: (ctx) => ToJsonSchema.throw("patternIntersection", ctx), - predicate: (ctx) => ToJsonSchema.throw("predicate", ctx), - proto: (ctx) => ToJsonSchema.throw("proto", ctx), - symbolKey: (ctx) => ToJsonSchema.throw("symbolKey", ctx), - unit: (ctx) => ToJsonSchema.throw("unit", ctx), - date: (ctx) => ToJsonSchema.throw("date", ctx) - } -}; -var ToJsonSchema = { - Error: ToJsonSchemaError, - throw: (...args3) => { - throw new ToJsonSchema.Error(...args3); - }, - throwInternalOperandError: (kind, schema2) => throwInternalError2(`Unexpected JSON Schema input for ${kind}: ${printable2(schema2)}`), - defaultConfig -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/config.js -$ark.config ??= {}; -var configureSchema = (config2) => { - const result = Object.assign($ark.config, mergeConfigs($ark.config, config2)); - if ($ark.resolvedConfig) - $ark.resolvedConfig = mergeConfigs($ark.resolvedConfig, result); - return result; -}; -var mergeConfigs = (base, merged) => { - if (!merged) - return base; - const result = { ...base }; - let k; - for (k in merged) { - const keywords2 = { ...base.keywords }; - if (k === "keywords") { - for (const flatAlias in merged[k]) { - const v = merged.keywords[flatAlias]; - if (v === void 0) - continue; - keywords2[flatAlias] = typeof v === "string" ? { description: v } : v; - } - result.keywords = keywords2; - } else if (k === "toJsonSchema") { - result[k] = mergeToJsonSchemaConfigs(base.toJsonSchema, merged.toJsonSchema); - } else if (isNodeKind(k)) { - result[k] = // not casting this makes TS compute a very inefficient - // type that is not needed - { - ...base[k], - ...merged[k] - }; - } else - result[k] = merged[k]; - } - return result; -}; -var jsonSchemaTargetToDialect = { - "draft-2020-12": "https://json-schema.org/draft/2020-12/schema", - "draft-07": "http://json-schema.org/draft-07/schema#" -}; -var mergeToJsonSchemaConfigs = ((baseConfig, mergedConfig) => { - if (!baseConfig) - return resolveTargetToDialect(mergedConfig ?? {}, void 0); - if (!mergedConfig) - return baseConfig; - const result = { ...baseConfig }; - let k; - for (k in mergedConfig) { - if (k === "fallback") { - result.fallback = mergeFallbacks(baseConfig.fallback, mergedConfig.fallback); - } else - result[k] = mergedConfig[k]; - } - return resolveTargetToDialect(result, mergedConfig); -}); -var resolveTargetToDialect = (opts, userOpts) => { - if (userOpts?.dialect !== void 0) - return opts; - if (userOpts?.target !== void 0) { - return { - ...opts, - dialect: jsonSchemaTargetToDialect[userOpts.target] - }; - } - return opts; -}; -var mergeFallbacks = (base, merged) => { - base = normalizeFallback(base); - merged = normalizeFallback(merged); - const result = {}; - let code; - for (code in ToJsonSchema.defaultConfig.fallback) { - result[code] = merged[code] ?? merged.default ?? base[code] ?? base.default ?? ToJsonSchema.defaultConfig.fallback[code]; - } - return result; -}; -var normalizeFallback = (fallback) => typeof fallback === "function" ? { default: fallback } : fallback ?? {}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/errors.js -var ArkError = class _ArkError extends CastableBase { - [arkKind] = "error"; - path; - data; - nodeConfig; - input; - ctx; - // TS gets confused by , so internally we just use the base type for input - constructor({ prefixPath, relativePath, ...input }, ctx) { - super(); - this.input = input; - this.ctx = ctx; - defineProperties(this, input); - const data = ctx.data; - if (input.code === "union") { - input.errors = input.errors.flatMap((innerError) => { - const flat = innerError.hasCode("union") ? innerError.errors : [innerError]; - if (!prefixPath && !relativePath) - return flat; - return flat.map((e) => e.transform((e2) => ({ - ...e2, - path: conflatenateAll(prefixPath, e2.path, relativePath) - }))); - }); - } - this.nodeConfig = ctx.config[this.code]; - const basePath = [...input.path ?? ctx.path]; - if (relativePath) - basePath.push(...relativePath); - if (prefixPath) - basePath.unshift(...prefixPath); - this.path = new ReadonlyPath(...basePath); - this.data = "data" in input ? input.data : data; - } - transform(f) { - return new _ArkError(f({ - data: this.data, - path: this.path, - ...this.input - }), this.ctx); - } - hasCode(code) { - return this.code === code; - } - get propString() { - return stringifyPath(this.path); - } - get expected() { - if (this.input.expected) - return this.input.expected; - const config2 = this.meta?.expected ?? this.nodeConfig.expected; - return typeof config2 === "function" ? config2(this.input) : config2; - } - get actual() { - if (this.input.actual) - return this.input.actual; - const config2 = this.meta?.actual ?? this.nodeConfig.actual; - return typeof config2 === "function" ? config2(this.data) : config2; - } - get problem() { - if (this.input.problem) - return this.input.problem; - const config2 = this.meta?.problem ?? this.nodeConfig.problem; - return typeof config2 === "function" ? config2(this) : config2; - } - get message() { - if (this.input.message) - return this.input.message; - const config2 = this.meta?.message ?? this.nodeConfig.message; - return typeof config2 === "function" ? config2(this) : config2; - } - get flat() { - return this.hasCode("intersection") ? [...this.errors] : [this]; - } - toJSON() { - return { - data: this.data, - path: this.path, - ...this.input, - expected: this.expected, - actual: this.actual, - problem: this.problem, - message: this.message - }; - } - toString() { - return this.message; - } - throw() { - throw this; - } -}; -var ArkErrors = class _ArkErrors extends ReadonlyArray2 { - [arkKind] = "errors"; - ctx; - constructor(ctx) { - super(); - this.ctx = ctx; - } - /** - * Errors by a pathString representing their location. - */ - byPath = /* @__PURE__ */ Object.create(null); - /** - * {@link byPath} flattened so that each value is an array of ArkError instances at that path. - * - * ✅ Since "intersection" errors will be flattened to their constituent `.errors`, - * they will never be directly present in this representation. - */ - get flatByPath() { - return flatMorph2(this.byPath, (k, v) => [k, v.flat]); - } - /** - * {@link byPath} flattened so that each value is an array of problem strings at that path. - */ - get flatProblemsByPath() { - return flatMorph2(this.byPath, (k, v) => [k, v.flat.map((e) => e.problem)]); - } - /** - * All pathStrings at which errors are present mapped to the errors occuring - * at that path or any nested path within it. - */ - byAncestorPath = /* @__PURE__ */ Object.create(null); - count = 0; - mutable = this; - /** - * Throw a TraversalError based on these errors. - */ - throw() { - throw this.toTraversalError(); - } - /** - * Converts ArkErrors to TraversalError, a subclass of `Error` suitable for throwing with nice - * formatting. - */ - toTraversalError() { - return new TraversalError(this); - } - /** - * Append an ArkError to this array, ignoring duplicates. - */ - add(error41) { - const existing = this.byPath[error41.propString]; - if (existing) { - if (error41 === existing) - return; - if (existing.hasCode("union") && existing.errors.length === 0) - return; - const errorIntersection = error41.hasCode("union") && error41.errors.length === 0 ? error41 : new ArkError({ - code: "intersection", - errors: existing.hasCode("intersection") ? [...existing.errors, error41] : [existing, error41] - }, this.ctx); - const existingIndex = this.indexOf(existing); - this.mutable[existingIndex === -1 ? this.length : existingIndex] = errorIntersection; - this.byPath[error41.propString] = errorIntersection; - this.addAncestorPaths(error41); - } else { - this.byPath[error41.propString] = error41; - this.addAncestorPaths(error41); - this.mutable.push(error41); - } - this.count++; - } - transform(f) { - const result = new _ArkErrors(this.ctx); - for (const e of this) - result.add(f(e)); - return result; - } - /** - * Add all errors from an ArkErrors instance, ignoring duplicates and - * prefixing their paths with that of the current Traversal. - */ - merge(errors) { - for (const e of errors) { - this.add(new ArkError({ ...e, path: [...this.ctx.path, ...e.path] }, this.ctx)); - } - } - /** - * @internal - */ - affectsPath(path3) { - if (this.length === 0) - return false; - return ( - // this would occur if there is an existing error at a prefix of path - // e.g. the path is ["foo", "bar"] and there is an error at ["foo"] - path3.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path - // e.g. the path is ["foo"] and there is an error at ["foo", "bar"] - path3.stringify() in this.byAncestorPath - ); - } - /** - * A human-readable summary of all errors. - */ - get summary() { - return this.toString(); - } - /** - * Alias of this ArkErrors instance for StandardSchema compatibility. - */ - get issues() { - return this; - } - toJSON() { - return [...this.map((e) => e.toJSON())]; - } - toString() { - return this.join("\n"); - } - addAncestorPaths(error41) { - for (const propString of error41.path.stringifyAncestors()) { - this.byAncestorPath[propString] = append2(this.byAncestorPath[propString], error41); - } - } -}; -var TraversalError = class extends Error { - name = "TraversalError"; - constructor(errors) { - if (errors.length === 1) - super(errors.summary); - else - super("\n" + errors.map((error41) => ` \u2022 ${indent(error41)}`).join("\n")); - Object.defineProperty(this, "arkErrors", { - value: errors, - enumerable: false - }); - } -}; -var indent = (error41) => error41.toString().split("\n").join("\n "); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/traversal.js -var Traversal = class { - /** - * #### the path being validated or morphed - * - * ✅ array indices represented as numbers - * ⚠️ mutated during traversal - use `path.slice(0)` to snapshot - * 🔗 use {@link propString} for a stringified version - */ - path = []; - /** - * #### {@link ArkErrors} that will be part of this traversal's finalized result - * - * ✅ will always be an empty array for a valid traversal - */ - errors = new ArkErrors(this); - /** - * #### the original value being traversed - */ - root; - /** - * #### configuration for this traversal - * - * ✅ options can affect traversal results and error messages - * ✅ defaults < global config < scope config - * ✅ does not include options configured on individual types - */ - config; - queuedMorphs = []; - branches = []; - seen = {}; - constructor(root2, config2) { - this.root = root2; - this.config = config2; - } - /** - * #### the data being validated or morphed - * - * ✅ extracted from {@link root} at {@link path} - */ - get data() { - let result = this.root; - for (const segment of this.path) - result = result?.[segment]; - return result; - } - /** - * #### a string representing {@link path} - * - * @propString - */ - get propString() { - return stringifyPath(this.path); - } - /** - * #### add an {@link ArkError} and return `false` - * - * ✅ useful for predicates like `.narrow` - */ - reject(input) { - this.error(input); - return false; - } - /** - * #### add an {@link ArkError} from a description and return `false` - * - * ✅ useful for predicates like `.narrow` - * 🔗 equivalent to {@link reject}({ expected }) - */ - mustBe(expected) { - this.error(expected); - return false; - } - error(input) { - const errCtx = typeof input === "object" ? input.code ? input : { ...input, code: "predicate" } : { code: "predicate", expected: input }; - return this.errorFromContext(errCtx); - } - /** - * #### whether {@link currentBranch} (or the traversal root, outside a union) has one or more errors - */ - hasError() { - return this.currentErrorCount !== 0; - } - get currentBranch() { - return this.branches[this.branches.length - 1]; - } - queueMorphs(morphs) { - const input = { - path: new ReadonlyPath(...this.path), - morphs - }; - if (this.currentBranch) - this.currentBranch.queuedMorphs.push(input); - else - this.queuedMorphs.push(input); - } - finalize(onFail) { - if (this.queuedMorphs.length) { - if (typeof this.root === "object" && this.root !== null && this.config.clone) - this.root = this.config.clone(this.root); - this.applyQueuedMorphs(); - } - if (this.hasError()) - return onFail ? onFail(this.errors) : this.errors; - return this.root; - } - get currentErrorCount() { - return this.currentBranch ? this.currentBranch.error ? 1 : 0 : this.errors.count; - } - get failFast() { - return this.branches.length !== 0; - } - pushBranch() { - this.branches.push({ - error: void 0, - queuedMorphs: [] - }); - } - popBranch() { - return this.branches.pop(); - } - /** - * @internal - * Convenience for casting from InternalTraversal to Traversal - * for cases where the extra methods on the external type are expected, e.g. - * a morph or predicate. - */ - get external() { - return this; - } - errorFromNodeContext(input) { - return this.errorFromContext(input); - } - errorFromContext(errCtx) { - const error41 = new ArkError(errCtx, this); - if (this.currentBranch) - this.currentBranch.error = error41; - else - this.errors.add(error41); - return error41; - } - applyQueuedMorphs() { - while (this.queuedMorphs.length) { - const queuedMorphs = this.queuedMorphs; - this.queuedMorphs = []; - for (const { path: path3, morphs } of queuedMorphs) { - if (this.errors.affectsPath(path3)) - continue; - this.applyMorphsAtPath(path3, morphs); - } - } - } - applyMorphsAtPath(path3, morphs) { - const key = path3[path3.length - 1]; - let parent; - if (key !== void 0) { - parent = this.root; - for (let pathIndex = 0; pathIndex < path3.length - 1; pathIndex++) - parent = parent[path3[pathIndex]]; - } - for (const morph of morphs) { - this.path = [...path3]; - const morphIsNode = isNode(morph); - const result = morph(parent === void 0 ? this.root : parent[key], this); - if (result instanceof ArkError) { - if (!this.errors.includes(result)) - this.errors.add(result); - break; - } - if (result instanceof ArkErrors) { - if (!morphIsNode) { - this.errors.merge(result); - } - this.queuedMorphs = []; - break; - } - if (parent === void 0) - this.root = result; - else - parent[key] = result; - this.applyQueuedMorphs(); - } - } -}; -var traverseKey = (key, fn2, ctx) => { - if (!ctx) - return fn2(); - ctx.path.push(key); - const result = fn2(); - ctx.path.pop(); - return result; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/node.js -var BaseNode = class extends Callable { - attachments; - $; - onFail; - includesTransform; - includesContextualPredicate; - isCyclic; - allowsRequiresContext; - rootApplyStrategy; - contextFreeMorph; - rootApply; - referencesById; - shallowReferences; - flatRefs; - flatMorphs; - allows; - get shallowMorphs() { - return []; - } - constructor(attachments, $2) { - super((data, pipedFromCtx, onFail = this.onFail) => { - if (pipedFromCtx) { - this.traverseApply(data, pipedFromCtx); - return pipedFromCtx.hasError() ? pipedFromCtx.errors : pipedFromCtx.data; - } - return this.rootApply(data, onFail); - }, { attach: attachments }); - this.attachments = attachments; - this.$ = $2; - this.onFail = this.meta.onFail ?? this.$.resolvedConfig.onFail; - this.includesTransform = this.hasKind("morph") || this.hasKind("structure") && this.structuralMorph !== void 0 || this.hasKind("sequence") && this.inner.defaultables !== void 0; - this.includesContextualPredicate = this.hasKind("predicate") && this.inner.predicate.length !== 1; - this.isCyclic = this.kind === "alias"; - this.referencesById = { [this.id]: this }; - this.shallowReferences = this.hasKind("structure") ? [this, ...this.children] : this.children.reduce((acc, child) => appendUniqueNodes(acc, child.shallowReferences), [this]); - const isStructural = this.isStructural(); - this.flatRefs = []; - this.flatMorphs = []; - for (let i = 0; i < this.children.length; i++) { - this.includesTransform ||= this.children[i].includesTransform; - this.includesContextualPredicate ||= this.children[i].includesContextualPredicate; - this.isCyclic ||= this.children[i].isCyclic; - if (!isStructural) { - const childFlatRefs = this.children[i].flatRefs; - for (let j = 0; j < childFlatRefs.length; j++) { - const childRef = childFlatRefs[j]; - if (!this.flatRefs.some((existing) => flatRefsAreEqual(existing, childRef))) { - this.flatRefs.push(childRef); - for (const branch of childRef.node.branches) { - if (branch.hasKind("morph") || branch.hasKind("intersection") && branch.structure?.structuralMorph !== void 0) { - this.flatMorphs.push({ - path: childRef.path, - propString: childRef.propString, - node: branch - }); - } - } - } - } - } - Object.assign(this.referencesById, this.children[i].referencesById); - } - this.flatRefs.sort((l, r) => l.path.length > r.path.length ? 1 : l.path.length < r.path.length ? -1 : l.propString > r.propString ? 1 : l.propString < r.propString ? -1 : l.node.expression < r.node.expression ? -1 : 1); - this.allowsRequiresContext = this.includesContextualPredicate || this.isCyclic; - this.rootApplyStrategy = !this.allowsRequiresContext && this.flatMorphs.length === 0 ? this.shallowMorphs.length === 0 ? "allows" : this.shallowMorphs.every((morph) => morph.length === 1 || morph.name === "$arkStructuralMorph") ? this.hasKind("union") ? ( - // multiple morphs not yet supported for optimistic compilation - this.branches.some((branch) => branch.shallowMorphs.length > 1) ? "contextual" : "branchedOptimistic" - ) : this.shallowMorphs.length > 1 ? "contextual" : "optimistic" : "contextual" : "contextual"; - this.rootApply = this.createRootApply(); - this.allows = this.allowsRequiresContext ? (data) => this.traverseAllows(data, new Traversal(data, this.$.resolvedConfig)) : (data) => this.traverseAllows(data); - } - createRootApply() { - switch (this.rootApplyStrategy) { - case "allows": - return (data, onFail) => { - if (this.allows(data)) - return data; - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - case "contextual": - return (data, onFail) => { - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - case "optimistic": - this.contextFreeMorph = this.shallowMorphs[0]; - const clone2 = this.$.resolvedConfig.clone; - return (data, onFail) => { - if (this.allows(data)) { - return this.contextFreeMorph(clone2 && (typeof data === "object" && data !== null || typeof data === "function") ? clone2(data) : data); - } - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - case "branchedOptimistic": - return this.createBranchedOptimisticRootApply(); - default: - this.rootApplyStrategy; - return throwInternalError2(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`); - } - } - compiledMeta = compileMeta(this.metaJson); - cacheGetter(name, value2) { - Object.defineProperty(this, name, { value: value2 }); - return value2; - } - get description() { - return this.cacheGetter("description", this.meta?.description ?? this.$.resolvedConfig[this.kind].description(this)); - } - // we don't cache this currently since it can be updated once a scope finishes - // resolving cyclic references, although it may be possible to ensure it is cached safely - get references() { - return Object.values(this.referencesById); - } - precedence = precedenceOfKind(this.kind); - precompilation; - // defined as an arrow function since it is often detached, e.g. when passing to tRPC - // otherwise, would run into issues with this binding - assert = (data, pipedFromCtx) => this(data, pipedFromCtx, (errors) => errors.throw()); - traverse(data, pipedFromCtx) { - return this(data, pipedFromCtx, null); - } - /** rawIn should be used internally instead */ - get in() { - return this.cacheGetter("in", this.rawIn.isRoot() ? this.$.finalize(this.rawIn) : this.rawIn); - } - get rawIn() { - return this.cacheGetter("rawIn", this.getIo("in")); - } - /** rawOut should be used internally instead */ - get out() { - return this.cacheGetter("out", this.rawOut.isRoot() ? this.$.finalize(this.rawOut) : this.rawOut); - } - get rawOut() { - return this.cacheGetter("rawOut", this.getIo("out")); - } - // Should be refactored to use transform - // https://github.com/arktypeio/arktype/issues/1020 - getIo(ioKind) { - if (!this.includesTransform) - return this; - const ioInner = {}; - for (const [k, v] of this.innerEntries) { - const keySchemaImplementation = this.impl.keys[k]; - if (keySchemaImplementation.reduceIo) - keySchemaImplementation.reduceIo(ioKind, ioInner, v); - else if (keySchemaImplementation.child) { - const childValue = v; - ioInner[k] = isArray(childValue) ? childValue.map((child) => ioKind === "in" ? child.rawIn : child.rawOut) : ioKind === "in" ? childValue.rawIn : childValue.rawOut; - } else - ioInner[k] = v; - } - return this.$.node(this.kind, ioInner); - } - toJSON() { - return this.json; - } - toString() { - return `Type<${this.expression}>`; - } - equals(r) { - const rNode = isNode(r) ? r : this.$.parseDefinition(r); - return this.innerHash === rNode.innerHash; - } - ifEquals(r) { - return this.equals(r) ? this : void 0; - } - hasKind(kind) { - return this.kind === kind; - } - assertHasKind(kind) { - if (this.kind !== kind) - throwError(`${this.kind} node was not of asserted kind ${kind}`); - return this; - } - hasKindIn(...kinds) { - return kinds.includes(this.kind); - } - assertHasKindIn(...kinds) { - if (!includes(kinds, this.kind)) - throwError(`${this.kind} node was not one of asserted kinds ${kinds}`); - return this; - } - isBasis() { - return includes(basisKinds, this.kind); - } - isConstraint() { - return includes(constraintKinds, this.kind); - } - isStructural() { - return includes(structuralKinds, this.kind); - } - isRefinement() { - return includes(refinementKinds, this.kind); - } - isRoot() { - return includes(rootKinds, this.kind); - } - isUnknown() { - return this.hasKind("intersection") && this.children.length === 0; - } - isNever() { - return this.hasKind("union") && this.children.length === 0; - } - hasUnit(value2) { - return this.hasKind("unit") && this.allows(value2); - } - hasOpenIntersection() { - return this.impl.intersectionIsOpen; - } - get nestableExpression() { - return this.expression; - } - select(selector) { - const normalized = NodeSelector.normalize(selector); - return this._select(normalized); - } - _select(selector) { - let nodes = NodeSelector.applyBoundary[selector.boundary ?? "references"](this); - if (selector.kind) - nodes = nodes.filter((n) => n.kind === selector.kind); - if (selector.where) - nodes = nodes.filter(selector.where); - return NodeSelector.applyMethod[selector.method ?? "filter"](nodes, this, selector); - } - transform(mapper, opts) { - return this._transform(mapper, this._createTransformContext(opts)); - } - _createTransformContext(opts) { - return { - root: this, - selected: void 0, - seen: {}, - path: [], - parseOptions: { - prereduced: opts?.prereduced ?? false - }, - undeclaredKeyHandling: void 0, - ...opts - }; - } - _transform(mapper, ctx) { - const $2 = ctx.bindScope ?? this.$; - if (ctx.seen[this.id]) - return this.$.lazilyResolve(ctx.seen[this.id]); - if (ctx.shouldTransform?.(this, ctx) === false) - return this; - let transformedNode; - ctx.seen[this.id] = () => transformedNode; - if (this.hasKind("structure") && this.undeclared !== ctx.undeclaredKeyHandling) { - ctx = { - ...ctx, - undeclaredKeyHandling: this.undeclared - }; - } - const innerWithTransformedChildren = flatMorph2(this.inner, (k, v) => { - if (!this.impl.keys[k].child) - return [k, v]; - const children = v; - if (!isArray(children)) { - const transformed2 = children._transform(mapper, ctx); - return transformed2 ? [k, transformed2] : []; - } - if (children.length === 0) - return [k, v]; - const transformed = children.flatMap((n) => { - const transformedChild = n._transform(mapper, ctx); - return transformedChild ?? []; - }); - return transformed.length ? [k, transformed] : []; - }); - delete ctx.seen[this.id]; - const innerWithMeta = Object.assign(innerWithTransformedChildren, { - meta: this.meta - }); - const transformedInner = ctx.selected && !ctx.selected.includes(this) ? innerWithMeta : mapper(this.kind, innerWithMeta, ctx); - if (transformedInner === null) - return null; - if (isNode(transformedInner)) - return transformedNode = transformedInner; - const transformedKeys = Object.keys(transformedInner); - const hasNoTypedKeys = transformedKeys.length === 0 || transformedKeys.length === 1 && transformedKeys[0] === "meta"; - if (hasNoTypedKeys && // if inner was previously an empty object (e.g. unknown) ensure it is not pruned - !isEmptyObject2(this.inner)) - return null; - if ((this.kind === "required" || this.kind === "optional" || this.kind === "index") && !("value" in transformedInner)) { - return ctx.undeclaredKeyHandling ? { ...transformedInner, value: $ark.intrinsic.unknown } : null; - } - if (this.kind === "morph") { - ; - transformedInner.in ??= $ark.intrinsic.unknown; - } - return transformedNode = $2.node(this.kind, transformedInner, ctx.parseOptions); - } - configureReferences(meta, selector = "references") { - const normalized = NodeSelector.normalize(selector); - const mapper = typeof meta === "string" ? (kind, inner) => ({ - ...inner, - meta: { ...inner.meta, description: meta } - }) : typeof meta === "function" ? (kind, inner) => ({ ...inner, meta: meta(inner.meta) }) : (kind, inner) => ({ - ...inner, - meta: { ...inner.meta, ...meta } - }); - if (normalized.boundary === "self") { - return this.$.node(this.kind, mapper(this.kind, { ...this.inner, meta: this.meta })); - } - const rawSelected = this._select(normalized); - const selected = rawSelected && liftArray(rawSelected); - const shouldTransform = normalized.boundary === "child" ? (node2, ctx) => ctx.root.children.includes(node2) : normalized.boundary === "shallow" ? (node2) => node2.kind !== "structure" : () => true; - return this.$.finalize(this.transform(mapper, { - shouldTransform, - selected - })); - } -}; -var NodeSelector = { - applyBoundary: { - self: (node2) => [node2], - child: (node2) => [...node2.children], - shallow: (node2) => [...node2.shallowReferences], - references: (node2) => [...node2.references] - }, - applyMethod: { - filter: (nodes) => nodes, - assertFilter: (nodes, from, selector) => { - if (nodes.length === 0) - throwError(writeSelectAssertionMessage(from, selector)); - return nodes; - }, - find: (nodes) => nodes[0], - assertFind: (nodes, from, selector) => { - if (nodes.length === 0) - throwError(writeSelectAssertionMessage(from, selector)); - return nodes[0]; - } - }, - normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf2(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector } -}; -var writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable2(selector)}.`; -var typePathToPropString = (path3) => stringifyPath(path3, { - stringifyNonKey: (node2) => node2.expression -}); -var referenceMatcher = /"(\$ark\.[^"]+)"/g; -var compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, "$1"); -var flatRef = (path3, node2) => ({ - path: path3, - node: node2, - propString: typePathToPropString(path3) -}); -var flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node); -var appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, { - isEqual: flatRefsAreEqual -}); -var appendUniqueNodes = (existing, refs) => appendUnique(existing, refs, { - isEqual: (l, r) => l.equals(r) -}); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/disjoint.js -var Disjoint = class _Disjoint extends Array { - static init(kind, l, r, ctx) { - return new _Disjoint({ - kind, - l, - r, - path: ctx?.path ?? [], - optional: ctx?.optional ?? false - }); - } - add(kind, l, r, ctx) { - this.push({ - kind, - l, - r, - path: ctx?.path ?? [], - optional: ctx?.optional ?? false - }); - return this; - } - get summary() { - return this.describeReasons(); - } - describeReasons() { - if (this.length === 1) { - const { path: path3, l, r } = this[0]; - const pathString = stringifyPath(path3); - return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`); - } - return `The following intersections result in unsatisfiable types: -\u2022 ${this.map(({ path: path3, l, r }) => `${path3}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`; - } - throw() { - return throwParseError2(this.describeReasons()); - } - invert() { - const result = this.map((entry) => ({ - ...entry, - l: entry.r, - r: entry.l - })); - if (!(result instanceof _Disjoint)) - return new _Disjoint(...result); - return result; - } - withPrefixKey(key, kind) { - return this.map((entry) => ({ - ...entry, - path: [key, ...entry.path], - optional: entry.optional || kind === "optional" - })); - } - toNeverIfDisjoint() { - return $ark.intrinsic.never; - } -}; -var describeReasons = (l, r) => `${describeReason(l)} and ${describeReason(r)}`; -var describeReason = (value2) => isNode(value2) ? value2.expression : isArray(value2) ? value2.map(describeReason).join(" | ") || "never" : String(value2); -var writeUnsatisfiableExpressionError = (expression) => `${expression} results in an unsatisfiable type`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/intersections.js -var intersectionCache = {}; -var intersectNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { - $: $2, - invert: false, - pipe: false -}); -var pipeNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { - $: $2, - invert: false, - pipe: true -}); -var intersectOrPipeNodes = ((l, r, ctx) => { - const operator = ctx.pipe ? "|>" : "&"; - const lrCacheKey = `${l.hash}${operator}${r.hash}`; - if (intersectionCache[lrCacheKey] !== void 0) - return intersectionCache[lrCacheKey]; - if (!ctx.pipe) { - const rlCacheKey = `${r.hash}${operator}${l.hash}`; - if (intersectionCache[rlCacheKey] !== void 0) { - const rlResult = intersectionCache[rlCacheKey]; - const lrResult = rlResult instanceof Disjoint ? rlResult.invert() : rlResult; - intersectionCache[lrCacheKey] = lrResult; - return lrResult; - } - } - const isPureIntersection = !ctx.pipe || !l.includesTransform && !r.includesTransform; - if (isPureIntersection && l.equals(r)) - return l; - let result = isPureIntersection ? _intersectNodes(l, r, ctx) : l.hasKindIn(...rootKinds) ? ( - // if l is a RootNode, r will be as well - _pipeNodes(l, r, ctx) - ) : _intersectNodes(l, r, ctx); - if (isNode(result)) { - if (l.equals(result)) - result = l; - else if (r.equals(result)) - result = r; - } - intersectionCache[lrCacheKey] = result; - return result; -}); -var _intersectNodes = (l, r, ctx) => { - const leftmostKind = l.precedence < r.precedence ? l.kind : r.kind; - const implementation23 = l.impl.intersections[r.kind] ?? r.impl.intersections[l.kind]; - if (implementation23 === void 0) { - return null; - } else if (leftmostKind === l.kind) - return implementation23(l, r, ctx); - else { - let result = implementation23(r, l, { ...ctx, invert: !ctx.invert }); - if (result instanceof Disjoint) - result = result.invert(); - return result; - } -}; -var _pipeNodes = (l, r, ctx) => l.includesTransform || r.includesTransform ? ctx.invert ? pipeMorphed(r, l, ctx) : pipeMorphed(l, r, ctx) : _intersectNodes(l, r, ctx); -var pipeMorphed = (from, to, ctx) => from.distribute((fromBranch) => _pipeMorphed(fromBranch, to, ctx), (results) => { - const viableBranches = results.filter(isNode); - if (viableBranches.length === 0) - return Disjoint.init("union", from.branches, to.branches); - if (viableBranches.length < from.branches.length || !from.branches.every((branch, i) => branch.rawIn.equals(viableBranches[i].rawIn))) - return ctx.$.parseSchema(viableBranches); - let meta; - if (viableBranches.length === 1) { - const onlyBranch = viableBranches[0]; - if (!meta) - return onlyBranch; - return ctx.$.node("morph", { - ...onlyBranch.inner, - in: onlyBranch.rawIn.configure(meta, "self") - }); - } - const schema2 = { - branches: viableBranches - }; - if (meta) - schema2.meta = meta; - return ctx.$.parseSchema(schema2); -}); -var _pipeMorphed = (from, to, ctx) => { - const fromIsMorph = from.hasKind("morph"); - if (fromIsMorph) { - const morphs = [...from.morphs]; - if (from.lastMorphIfNode) { - const outIntersection = intersectOrPipeNodes(from.lastMorphIfNode, to, ctx); - if (outIntersection instanceof Disjoint) - return outIntersection; - morphs[morphs.length - 1] = outIntersection; - } else - morphs.push(to); - return ctx.$.node("morph", { - morphs, - in: from.inner.in - }); - } - if (to.hasKind("morph")) { - const inTersection = intersectOrPipeNodes(from, to.rawIn, ctx); - if (inTersection instanceof Disjoint) - return inTersection; - return ctx.$.node("morph", { - morphs: [to], - in: inTersection - }); - } - return ctx.$.node("morph", { - morphs: [to], - in: from - }); -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/constraint.js -var BaseConstraint = class extends BaseNode { - constructor(attachments, $2) { - super(attachments, $2); - Object.defineProperty(this, arkKind, { - value: "constraint", - enumerable: false - }); - } - impliedSiblings; - intersect(r) { - return intersectNodesRoot(this, r, this.$); - } -}; -var InternalPrimitiveConstraint = class extends BaseConstraint { - traverseApply = (data, ctx) => { - if (!this.traverseAllows(data, ctx)) - ctx.errorFromNodeContext(this.errorContext); - }; - compile(js) { - if (js.traversalKind === "Allows") - js.return(this.compiledCondition); - else { - js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); - } - } - get errorContext() { - return { - code: this.kind, - description: this.description, - meta: this.meta, - ...this.inner - }; - } - get compiledErrorContext() { - return compileObjectLiteral(this.errorContext); - } -}; -var constraintKeyParser = (kind) => (schema2, ctx) => { - if (isArray(schema2)) { - if (schema2.length === 0) { - return; - } - const nodes = schema2.map((schema3) => ctx.$.node(kind, schema3)); - if (kind === "predicate") - return nodes; - return nodes.sort((l, r) => l.hash < r.hash ? -1 : 1); - } - const child = ctx.$.node(kind, schema2); - return child.hasOpenIntersection() ? [child] : child; -}; -var intersectConstraints = (s) => { - const head = s.r.shift(); - if (!head) { - let result = s.l.length === 0 && s.kind === "structure" ? $ark.intrinsic.unknown.internal : s.ctx.$.node(s.kind, Object.assign(s.baseInner, unflattenConstraints(s.l)), { prereduced: true }); - for (const root2 of s.roots) { - if (result instanceof Disjoint) - return result; - result = intersectOrPipeNodes(root2, result, s.ctx); - } - return result; - } - let matched = false; - for (let i = 0; i < s.l.length; i++) { - const result = intersectOrPipeNodes(s.l[i], head, s.ctx); - if (result === null) - continue; - if (result instanceof Disjoint) - return result; - if (result.isRoot()) { - s.roots.push(result); - s.l.splice(i); - return intersectConstraints(s); - } - if (!matched) { - s.l[i] = result; - matched = true; - } else if (!s.l.includes(result)) { - return throwInternalError2(`Unexpectedly encountered multiple distinct intersection results for refinement ${head}`); - } - } - if (!matched) - s.l.push(head); - if (s.kind === "intersection") { - if (head.impliedSiblings) - for (const node2 of head.impliedSiblings) - appendUnique(s.r, node2); - } - return intersectConstraints(s); -}; -var flattenConstraints = (inner) => { - const result = Object.entries(inner).flatMap(([k, v]) => k in constraintKeys ? v : []).sort((l, r) => l.precedence < r.precedence ? -1 : l.precedence > r.precedence ? 1 : l.kind === "predicate" && r.kind === "predicate" ? 0 : l.hash < r.hash ? -1 : 1); - return result; -}; -var unflattenConstraints = (constraints) => { - const inner = {}; - for (const constraint of constraints) { - if (constraint.hasOpenIntersection()) { - inner[constraint.kind] = append2(inner[constraint.kind], constraint); - } else { - if (inner[constraint.kind]) { - return throwInternalError2(`Unexpected intersection of closed refinements of kind ${constraint.kind}`); - } - inner[constraint.kind] = constraint; - } - } - return inner; -}; -var throwInvalidOperandError = (...args3) => throwParseError2(writeInvalidOperandMessage(...args3)); -var writeInvalidOperandMessage = (kind, expected, actual) => { - const actualDescription = actual.hasKind("morph") ? "a morph" : actual.isUnknown() ? "unknown" : actual.exclude(expected).defaultShortDescription; - return `${capitalize(kind)} operand must be ${expected.description} (was ${actualDescription})`; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/generic.js -var parseGeneric = (paramDefs, bodyDef, $2) => new GenericRoot(paramDefs, bodyDef, $2, $2, null); -var LazyGenericBody = class extends Callable { -}; -var GenericRoot = class extends Callable { - [arkKind] = "generic"; - paramDefs; - bodyDef; - $; - arg$; - baseInstantiation; - hkt; - description; - constructor(paramDefs, bodyDef, $2, arg$, hkt) { - super((...args3) => { - const argNodes = flatMorph2(this.names, (i, name) => { - const arg = this.arg$.parse(args3[i]); - if (!arg.extends(this.constraints[i])) { - throwParseError2(writeUnsatisfiedParameterConstraintMessage(name, this.constraints[i].expression, arg.expression)); - } - return [name, arg]; - }); - if (this.defIsLazy()) { - const def = this.bodyDef(argNodes); - return this.$.parse(def); - } - return this.$.parse(bodyDef, { args: argNodes }); - }); - this.paramDefs = paramDefs; - this.bodyDef = bodyDef; - this.$ = $2; - this.arg$ = arg$; - this.hkt = hkt; - this.description = hkt ? new hkt().description ?? `a generic type for ${hkt.constructor.name}` : "a generic type"; - this.baseInstantiation = this(...this.constraints); - } - defIsLazy() { - return this.bodyDef instanceof LazyGenericBody; - } - cacheGetter(name, value2) { - Object.defineProperty(this, name, { value: value2 }); - return value2; - } - get json() { - return this.cacheGetter("json", { - params: this.params.map((param) => param[1].isUnknown() ? param[0] : [param[0], param[1].json]), - body: snapshot(this.bodyDef) - }); - } - get params() { - return this.cacheGetter("params", this.paramDefs.map((param) => typeof param === "string" ? [param, $ark.intrinsic.unknown] : [param[0], this.$.parse(param[1])])); - } - get names() { - return this.cacheGetter("names", this.params.map((e) => e[0])); - } - get constraints() { - return this.cacheGetter("constraints", this.params.map((e) => e[1])); - } - get internal() { - return this; - } - get referencesById() { - return this.baseInstantiation.internal.referencesById; - } - get references() { - return this.baseInstantiation.internal.references; - } -}; -var writeUnsatisfiedParameterConstraintMessage = (name, constraint, arg) => `${name} must be assignable to ${constraint} (was ${arg})`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/predicate.js -var implementation = implementNode({ - kind: "predicate", - hasAssociatedError: true, - collapsibleKey: "predicate", - keys: { - predicate: {} - }, - normalize: (schema2) => typeof schema2 === "function" ? { predicate: schema2 } : schema2, - defaults: { - description: (node2) => `valid according to ${node2.predicate.name || "an anonymous predicate"}` - }, - intersectionIsOpen: true, - intersections: { - // as long as the narrows in l and r are individually safe to check - // in the order they're specified, checking them in the order - // resulting from this intersection should also be safe. - predicate: () => null - } -}); -var PredicateNode = class extends BaseConstraint { - serializedPredicate = registeredReference(this.predicate); - compiledCondition = `${this.serializedPredicate}(data, ctx)`; - compiledNegation = `!${this.compiledCondition}`; - impliedBasis = null; - expression = this.serializedPredicate; - traverseAllows = this.predicate; - errorContext = { - code: "predicate", - description: this.description, - meta: this.meta - }; - compiledErrorContext = compileObjectLiteral(this.errorContext); - traverseApply = (data, ctx) => { - const errorCount = ctx.currentErrorCount; - if (!this.predicate(data, ctx.external) && ctx.currentErrorCount === errorCount) - ctx.errorFromNodeContext(this.errorContext); - }; - compile(js) { - if (js.traversalKind === "Allows") { - js.return(this.compiledCondition); - return; - } - js.initializeErrorCount(); - js.if( - // only add the default error if the predicate didn't add one itself - `${this.compiledNegation} && ctx.currentErrorCount === errorCount`, - () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) - ); - } - reduceJsonSchema(base, ctx) { - return ctx.fallback.predicate({ - code: "predicate", - base, - predicate: this.predicate - }); - } -}; -var Predicate = { - implementation, - Node: PredicateNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/divisor.js -var implementation2 = implementNode({ - kind: "divisor", - collapsibleKey: "rule", - keys: { - rule: { - parse: (divisor) => Number.isInteger(divisor) ? divisor : throwParseError2(writeNonIntegerDivisorMessage(divisor)) - } - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - hasAssociatedError: true, - defaults: { - description: (node2) => node2.rule === 1 ? "an integer" : node2.rule === 2 ? "even" : `a multiple of ${node2.rule}` - }, - intersections: { - divisor: (l, r, ctx) => ctx.$.node("divisor", { - rule: Math.abs(l.rule * r.rule / greatestCommonDivisor(l.rule, r.rule)) - }) - }, - obviatesBasisDescription: true -}); -var DivisorNode = class extends InternalPrimitiveConstraint { - traverseAllows = (data) => data % this.rule === 0; - compiledCondition = `data % ${this.rule} === 0`; - compiledNegation = `data % ${this.rule} !== 0`; - impliedBasis = $ark.intrinsic.number.internal; - expression = `% ${this.rule}`; - reduceJsonSchema(schema2) { - schema2.type = "integer"; - if (this.rule === 1) - return schema2; - schema2.multipleOf = this.rule; - return schema2; - } -}; -var Divisor = { - implementation: implementation2, - Node: DivisorNode -}; -var writeNonIntegerDivisorMessage = (divisor) => `divisor must be an integer (was ${divisor})`; -var greatestCommonDivisor = (l, r) => { - let previous; - let greatestCommonDivisor2 = l; - let current = r; - while (current !== 0) { - previous = current; - current = greatestCommonDivisor2 % current; - greatestCommonDivisor2 = previous; - } - return greatestCommonDivisor2; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/range.js -var BaseRange = class extends InternalPrimitiveConstraint { - boundOperandKind = operandKindsByBoundKind[this.kind]; - compiledActual = this.boundOperandKind === "value" ? `data` : this.boundOperandKind === "length" ? `data.length` : `data.valueOf()`; - comparator = compileComparator(this.kind, this.exclusive); - numericLimit = this.rule.valueOf(); - expression = `${this.comparator} ${this.rule}`; - compiledCondition = `${this.compiledActual} ${this.comparator} ${this.numericLimit}`; - compiledNegation = `${this.compiledActual} ${negatedComparators[this.comparator]} ${this.numericLimit}`; - // we need to compute stringLimit before errorContext, which references it - // transitively through description for date bounds - stringLimit = this.boundOperandKind === "date" ? dateLimitToString(this.numericLimit) : `${this.numericLimit}`; - limitKind = this.comparator["0"] === "<" ? "upper" : "lower"; - isStricterThan(r) { - const thisLimitIsStricter = this.limitKind === "upper" ? this.numericLimit < r.numericLimit : this.numericLimit > r.numericLimit; - return thisLimitIsStricter || this.numericLimit === r.numericLimit && this.exclusive === true && !r.exclusive; - } - overlapsRange(r) { - if (this.isStricterThan(r)) - return false; - if (this.numericLimit === r.numericLimit && (this.exclusive || r.exclusive)) - return false; - return true; - } - overlapIsUnit(r) { - return this.numericLimit === r.numericLimit && !this.exclusive && !r.exclusive; - } -}; -var negatedComparators = { - "<": ">=", - "<=": ">", - ">": "<=", - ">=": "<" -}; -var boundKindPairsByLower = { - min: "max", - minLength: "maxLength", - after: "before" -}; -var parseExclusiveKey = { - // omit key with value false since it is the default - parse: (flag) => flag || void 0 -}; -var createLengthSchemaNormalizer = (kind) => (schema2) => { - if (typeof schema2 === "number") - return { rule: schema2 }; - const { exclusive, ...normalized } = schema2; - return exclusive ? { - ...normalized, - rule: kind === "minLength" ? normalized.rule + 1 : normalized.rule - 1 - } : normalized; -}; -var createDateSchemaNormalizer = (kind) => (schema2) => { - if (typeof schema2 === "number" || typeof schema2 === "string" || schema2 instanceof Date) - return { rule: schema2 }; - const { exclusive, ...normalized } = schema2; - if (!exclusive) - return normalized; - const numericLimit = typeof normalized.rule === "number" ? normalized.rule : typeof normalized.rule === "string" ? new Date(normalized.rule).valueOf() : normalized.rule.valueOf(); - return exclusive ? { - ...normalized, - rule: kind === "after" ? numericLimit + 1 : numericLimit - 1 - } : normalized; -}; -var parseDateLimit = (limit) => typeof limit === "string" || typeof limit === "number" ? new Date(limit) : limit; -var writeInvalidLengthBoundMessage = (kind, limit) => `${kind} bound must be a positive integer (was ${limit})`; -var createLengthRuleParser = (kind) => (limit) => { - if (!Number.isInteger(limit) || limit < 0) - throwParseError2(writeInvalidLengthBoundMessage(kind, limit)); - return limit; -}; -var operandKindsByBoundKind = { - min: "value", - max: "value", - minLength: "length", - maxLength: "length", - after: "date", - before: "date" -}; -var compileComparator = (kind, exclusive) => `${isKeyOf2(kind, boundKindPairsByLower) ? ">" : "<"}${exclusive ? "" : "="}`; -var dateLimitToString = (limit) => typeof limit === "string" ? limit : new Date(limit).toLocaleString(); -var writeUnboundableMessage = (root2) => `Bounded expression ${root2} must be exactly one of number, string, Array, or Date`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/after.js -var implementation3 = implementNode({ - kind: "after", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: parseDateLimit, - serialize: (schema2) => schema2.toISOString() - } - }, - normalize: createDateSchemaNormalizer("after"), - defaults: { - description: (node2) => `${node2.collapsibleLimitString} or later`, - actual: describeCollapsibleDate - }, - intersections: { - after: (l, r) => l.isStricterThan(r) ? l : r - } -}); -var AfterNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.Date.internal; - collapsibleLimitString = describeCollapsibleDate(this.rule); - traverseAllows = (data) => data >= this.rule; - reduceJsonSchema(base, ctx) { - return ctx.fallback.date({ code: "date", base, after: this.rule }); - } -}; -var After = { - implementation: implementation3, - Node: AfterNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/before.js -var implementation4 = implementNode({ - kind: "before", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: parseDateLimit, - serialize: (schema2) => schema2.toISOString() - } - }, - normalize: createDateSchemaNormalizer("before"), - defaults: { - description: (node2) => `${node2.collapsibleLimitString} or earlier`, - actual: describeCollapsibleDate - }, - intersections: { - before: (l, r) => l.isStricterThan(r) ? l : r, - after: (before, after, ctx) => before.overlapsRange(after) ? before.overlapIsUnit(after) ? ctx.$.node("unit", { unit: before.rule }) : null : Disjoint.init("range", before, after) - } -}); -var BeforeNode = class extends BaseRange { - collapsibleLimitString = describeCollapsibleDate(this.rule); - traverseAllows = (data) => data <= this.rule; - impliedBasis = $ark.intrinsic.Date.internal; - reduceJsonSchema(base, ctx) { - return ctx.fallback.date({ code: "date", base, before: this.rule }); - } -}; -var Before = { - implementation: implementation4, - Node: BeforeNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/exactLength.js -var implementation5 = implementNode({ - kind: "exactLength", - collapsibleKey: "rule", - keys: { - rule: { - parse: createLengthRuleParser("exactLength") - } - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - hasAssociatedError: true, - defaults: { - description: (node2) => `exactly length ${node2.rule}`, - actual: (data) => `${data.length}` - }, - intersections: { - exactLength: (l, r, ctx) => Disjoint.init("unit", ctx.$.node("unit", { unit: l.rule }), ctx.$.node("unit", { unit: r.rule }), { path: ["length"] }), - minLength: (exactLength, minLength) => exactLength.rule >= minLength.rule ? exactLength : Disjoint.init("range", exactLength, minLength), - maxLength: (exactLength, maxLength) => exactLength.rule <= maxLength.rule ? exactLength : Disjoint.init("range", exactLength, maxLength) - } -}); -var ExactLengthNode = class extends InternalPrimitiveConstraint { - traverseAllows = (data) => data.length === this.rule; - compiledCondition = `data.length === ${this.rule}`; - compiledNegation = `data.length !== ${this.rule}`; - impliedBasis = $ark.intrinsic.lengthBoundable.internal; - expression = `== ${this.rule}`; - reduceJsonSchema(schema2) { - switch (schema2.type) { - case "string": - schema2.minLength = this.rule; - schema2.maxLength = this.rule; - return schema2; - case "array": - schema2.minItems = this.rule; - schema2.maxItems = this.rule; - return schema2; - default: - return ToJsonSchema.throwInternalOperandError("exactLength", schema2); - } - } -}; -var ExactLength = { - implementation: implementation5, - Node: ExactLengthNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/max.js -var implementation6 = implementNode({ - kind: "max", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: {}, - exclusive: parseExclusiveKey - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - defaults: { - description: (node2) => { - if (node2.rule === 0) - return node2.exclusive ? "negative" : "non-positive"; - return `${node2.exclusive ? "less than" : "at most"} ${node2.rule}`; - } - }, - intersections: { - max: (l, r) => l.isStricterThan(r) ? l : r, - min: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("unit", { unit: max.rule }) : null : Disjoint.init("range", max, min) - }, - obviatesBasisDescription: true -}); -var MaxNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.number.internal; - traverseAllows = this.exclusive ? (data) => data < this.rule : (data) => data <= this.rule; - reduceJsonSchema(schema2) { - if (this.exclusive) - schema2.exclusiveMaximum = this.rule; - else - schema2.maximum = this.rule; - return schema2; - } -}; -var Max = { - implementation: implementation6, - Node: MaxNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/maxLength.js -var implementation7 = implementNode({ - kind: "maxLength", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: createLengthRuleParser("maxLength") - } - }, - reduce: (inner, $2) => inner.rule === 0 ? $2.node("exactLength", inner) : void 0, - normalize: createLengthSchemaNormalizer("maxLength"), - defaults: { - description: (node2) => `at most length ${node2.rule}`, - actual: (data) => `${data.length}` - }, - intersections: { - maxLength: (l, r) => l.isStricterThan(r) ? l : r, - minLength: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("exactLength", { rule: max.rule }) : null : Disjoint.init("range", max, min) - } -}); -var MaxLengthNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.lengthBoundable.internal; - traverseAllows = (data) => data.length <= this.rule; - reduceJsonSchema(schema2) { - switch (schema2.type) { - case "string": - schema2.maxLength = this.rule; - return schema2; - case "array": - schema2.maxItems = this.rule; - return schema2; - default: - return ToJsonSchema.throwInternalOperandError("maxLength", schema2); - } - } -}; -var MaxLength = { - implementation: implementation7, - Node: MaxLengthNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/min.js -var implementation8 = implementNode({ - kind: "min", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: {}, - exclusive: parseExclusiveKey - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - defaults: { - description: (node2) => { - if (node2.rule === 0) - return node2.exclusive ? "positive" : "non-negative"; - return `${node2.exclusive ? "more than" : "at least"} ${node2.rule}`; - } - }, - intersections: { - min: (l, r) => l.isStricterThan(r) ? l : r - }, - obviatesBasisDescription: true -}); -var MinNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.number.internal; - traverseAllows = this.exclusive ? (data) => data > this.rule : (data) => data >= this.rule; - reduceJsonSchema(schema2) { - if (this.exclusive) - schema2.exclusiveMinimum = this.rule; - else - schema2.minimum = this.rule; - return schema2; - } -}; -var Min = { - implementation: implementation8, - Node: MinNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/minLength.js -var implementation9 = implementNode({ - kind: "minLength", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: createLengthRuleParser("minLength") - } - }, - reduce: (inner) => inner.rule === 0 ? ( - // a minimum length of zero is trivially satisfied - $ark.intrinsic.unknown - ) : void 0, - normalize: createLengthSchemaNormalizer("minLength"), - defaults: { - description: (node2) => node2.rule === 1 ? "non-empty" : `at least length ${node2.rule}`, - // avoid default message like "must be non-empty (was 0)" - actual: (data) => data.length === 0 ? "" : `${data.length}` - }, - intersections: { - minLength: (l, r) => l.isStricterThan(r) ? l : r - } -}); -var MinLengthNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.lengthBoundable.internal; - traverseAllows = (data) => data.length >= this.rule; - reduceJsonSchema(schema2) { - switch (schema2.type) { - case "string": - schema2.minLength = this.rule; - return schema2; - case "array": - schema2.minItems = this.rule; - return schema2; - default: - return ToJsonSchema.throwInternalOperandError("minLength", schema2); - } - } -}; -var MinLength = { - implementation: implementation9, - Node: MinLengthNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/kinds.js -var boundImplementationsByKind = { - min: Min.implementation, - max: Max.implementation, - minLength: MinLength.implementation, - maxLength: MaxLength.implementation, - exactLength: ExactLength.implementation, - after: After.implementation, - before: Before.implementation -}; -var boundClassesByKind = { - min: Min.Node, - max: Max.Node, - minLength: MinLength.Node, - maxLength: MaxLength.Node, - exactLength: ExactLength.Node, - after: After.Node, - before: Before.Node -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/pattern.js -var implementation10 = implementNode({ - kind: "pattern", - collapsibleKey: "rule", - keys: { - rule: {}, - flags: {} - }, - normalize: (schema2) => typeof schema2 === "string" ? { rule: schema2 } : schema2 instanceof RegExp ? schema2.flags ? { rule: schema2.source, flags: schema2.flags } : { rule: schema2.source } : schema2, - obviatesBasisDescription: true, - obviatesBasisExpression: true, - hasAssociatedError: true, - intersectionIsOpen: true, - defaults: { - description: (node2) => `matched by ${node2.rule}` - }, - intersections: { - // for now, non-equal regex are naively intersected: - // https://github.com/arktypeio/arktype/issues/853 - pattern: () => null - } -}); -var PatternNode = class extends InternalPrimitiveConstraint { - instance = new RegExp(this.rule, this.flags); - expression = `${this.instance}`; - traverseAllows = this.instance.test.bind(this.instance); - compiledCondition = `${this.expression}.test(data)`; - compiledNegation = `!${this.compiledCondition}`; - impliedBasis = $ark.intrinsic.string.internal; - reduceJsonSchema(base, ctx) { - if (base.pattern) { - return ctx.fallback.patternIntersection({ - code: "patternIntersection", - base, - pattern: this.rule - }); - } - base.pattern = this.rule; - return base; - } -}; -var Pattern = { - implementation: implementation10, - Node: PatternNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/parse.js -var schemaKindOf = (schema2, allowedKinds) => { - const kind = discriminateRootKind(schema2); - if (allowedKinds && !allowedKinds.includes(kind)) { - return throwParseError2(`Root of kind ${kind} should be one of ${allowedKinds}`); - } - return kind; -}; -var discriminateRootKind = (schema2) => { - if (hasArkKind(schema2, "root")) - return schema2.kind; - if (typeof schema2 === "string") { - return schema2[0] === "$" ? "alias" : schema2 in domainDescriptions2 ? "domain" : "proto"; - } - if (typeof schema2 === "function") - return "proto"; - if (typeof schema2 !== "object" || schema2 === null) - return throwParseError2(writeInvalidSchemaMessage(schema2)); - if ("morphs" in schema2) - return "morph"; - if ("branches" in schema2 || isArray(schema2)) - return "union"; - if ("unit" in schema2) - return "unit"; - if ("reference" in schema2) - return "alias"; - const schemaKeys = Object.keys(schema2); - if (schemaKeys.length === 0 || schemaKeys.some((k) => k in constraintKeys)) - return "intersection"; - if ("proto" in schema2) - return "proto"; - if ("domain" in schema2) - return "domain"; - return throwParseError2(writeInvalidSchemaMessage(schema2)); -}; -var writeInvalidSchemaMessage = (schema2) => `${printable2(schema2)} is not a valid type schema`; -var nodeCountsByPrefix = {}; -var serializeListableChild = (listableNode) => isArray(listableNode) ? listableNode.map((node2) => node2.collapsibleJson) : listableNode.collapsibleJson; -var nodesByRegisteredId = {}; -$ark.nodesByRegisteredId = nodesByRegisteredId; -var registerNodeId = (prefix) => { - nodeCountsByPrefix[prefix] ??= 0; - return `${prefix}${++nodeCountsByPrefix[prefix]}`; -}; -var parseNode = (ctx) => { - const impl = nodeImplementationsByKind[ctx.kind]; - const configuredSchema = impl.applyConfig?.(ctx.def, ctx.$.resolvedConfig) ?? ctx.def; - const inner = {}; - const { meta: metaSchema, ...innerSchema } = configuredSchema; - const meta = metaSchema === void 0 ? {} : typeof metaSchema === "string" ? { description: metaSchema } : metaSchema; - const innerSchemaEntries = entriesOf(innerSchema).sort(([lKey], [rKey]) => isNodeKind(lKey) ? isNodeKind(rKey) ? precedenceOfKind(lKey) - precedenceOfKind(rKey) : 1 : isNodeKind(rKey) ? -1 : lKey < rKey ? -1 : 1).filter(([k, v]) => { - if (k.startsWith("meta.")) { - const metaKey = k.slice(5); - meta[metaKey] = v; - return false; - } - return true; - }); - for (const entry of innerSchemaEntries) { - const k = entry[0]; - const keyImpl = impl.keys[k]; - if (!keyImpl) - return throwParseError2(`Key ${k} is not valid on ${ctx.kind} schema`); - const v = keyImpl.parse ? keyImpl.parse(entry[1], ctx) : entry[1]; - if (v !== unset2 && (v !== void 0 || keyImpl.preserveUndefined)) - inner[k] = v; - } - if (impl.reduce && !ctx.prereduced) { - const reduced = impl.reduce(inner, ctx.$); - if (reduced) { - if (reduced instanceof Disjoint) - return reduced.throw(); - return withMeta(reduced, meta); - } - } - const node2 = createNode({ - id: ctx.id, - kind: ctx.kind, - inner, - meta, - $: ctx.$ - }); - return node2; -}; -var createNode = ({ id, kind, inner, meta, $: $2, ignoreCache }) => { - const impl = nodeImplementationsByKind[kind]; - const innerEntries = entriesOf(inner); - const children = []; - let innerJson = {}; - for (const [k, v] of innerEntries) { - const keyImpl = impl.keys[k]; - const serialize = keyImpl.serialize ?? (keyImpl.child ? serializeListableChild : defaultValueSerializer); - innerJson[k] = serialize(v); - if (keyImpl.child === true) { - const listableNode = v; - if (isArray(listableNode)) - children.push(...listableNode); - else - children.push(listableNode); - } else if (typeof keyImpl.child === "function") - children.push(...keyImpl.child(v)); - } - if (impl.finalizeInnerJson) - innerJson = impl.finalizeInnerJson(innerJson); - let json3 = { ...innerJson }; - let metaJson = {}; - if (!isEmptyObject2(meta)) { - metaJson = flatMorph2(meta, (k, v) => [ - k, - k === "examples" ? v : defaultValueSerializer(v) - ]); - json3.meta = possiblyCollapse(metaJson, "description", true); - } - innerJson = possiblyCollapse(innerJson, impl.collapsibleKey, false); - const innerHash = JSON.stringify({ kind, ...innerJson }); - json3 = possiblyCollapse(json3, impl.collapsibleKey, false); - const collapsibleJson = possiblyCollapse(json3, impl.collapsibleKey, true); - const hash = JSON.stringify({ kind, ...json3 }); - if ($2.nodesByHash[hash] && !ignoreCache) - return $2.nodesByHash[hash]; - const attachments = { - id, - kind, - impl, - inner, - innerEntries, - innerJson, - innerHash, - meta, - metaJson, - json: json3, - hash, - collapsibleJson, - children - }; - if (kind !== "intersection") { - for (const k in inner) - if (k !== "in" && k !== "out") - attachments[k] = inner[k]; - } - const node2 = new nodeClassesByKind[kind](attachments, $2); - return $2.nodesByHash[hash] = node2; -}; -var withId = (node2, id) => { - if (node2.id === id) - return node2; - if (isNode(nodesByRegisteredId[id])) - throwInternalError2(`Unexpected attempt to overwrite node id ${id}`); - return createNode({ - id, - kind: node2.kind, - inner: node2.inner, - meta: node2.meta, - $: node2.$, - ignoreCache: true - }); -}; -var withMeta = (node2, meta, id) => { - if (id && isNode(nodesByRegisteredId[id])) - throwInternalError2(`Unexpected attempt to overwrite node id ${id}`); - return createNode({ - id: id ?? registerNodeId(meta.alias ?? node2.kind), - kind: node2.kind, - inner: node2.inner, - meta, - $: node2.$ - }); -}; -var possiblyCollapse = (json3, toKey, allowPrimitive) => { - const collapsibleKeys = Object.keys(json3); - if (collapsibleKeys.length === 1 && collapsibleKeys[0] === toKey) { - const collapsed = json3[toKey]; - if (allowPrimitive) - return collapsed; - if ( - // if the collapsed value is still an object - hasDomain2(collapsed, "object") && // and the JSON did not include any implied keys - (Object.keys(collapsed).length === 1 || Array.isArray(collapsed)) - ) { - return collapsed; - } - } - return json3; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/prop.js -var intersectProps = (l, r, ctx) => { - if (l.key !== r.key) - return null; - const key = l.key; - let value2 = intersectOrPipeNodes(l.value, r.value, ctx); - const kind = l.required || r.required ? "required" : "optional"; - if (value2 instanceof Disjoint) { - if (kind === "optional") - value2 = $ark.intrinsic.never.internal; - else { - return value2.withPrefixKey(l.key, l.required && r.required ? "required" : "optional"); - } - } - if (kind === "required") { - return ctx.$.node("required", { - key, - value: value2 - }); - } - const defaultIntersection = l.hasDefault() ? r.hasDefault() ? l.default === r.default ? l.default : throwParseError2(writeDefaultIntersectionMessage(l.default, r.default)) : l.default : r.hasDefault() ? r.default : unset2; - return ctx.$.node("optional", { - key, - value: value2, - // unset is stripped during parsing - default: defaultIntersection - }); -}; -var BaseProp = class extends BaseConstraint { - required = this.kind === "required"; - optional = this.kind === "optional"; - impliedBasis = $ark.intrinsic.object.internal; - serializedKey = compileSerializedValue(this.key); - compiledKey = typeof this.key === "string" ? this.key : this.serializedKey; - flatRefs = append2(this.value.flatRefs.map((ref) => flatRef([this.key, ...ref.path], ref.node)), flatRef([this.key], this.value)); - _transform(mapper, ctx) { - ctx.path.push(this.key); - const result = super._transform(mapper, ctx); - ctx.path.pop(); - return result; - } - hasDefault() { - return "default" in this.inner; - } - traverseAllows = (data, ctx) => { - if (this.key in data) { - return traverseKey(this.key, () => this.value.traverseAllows(data[this.key], ctx), ctx); - } - return this.optional; - }; - traverseApply = (data, ctx) => { - if (this.key in data) { - traverseKey(this.key, () => this.value.traverseApply(data[this.key], ctx), ctx); - } else if (this.hasKind("required")) - ctx.errorFromNodeContext(this.errorContext); - }; - compile(js) { - js.if(`${this.serializedKey} in data`, () => js.traverseKey(this.serializedKey, `data${js.prop(this.key)}`, this.value)); - if (this.hasKind("required")) { - js.else(() => js.traversalKind === "Apply" ? js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) : js.return(false)); - } - if (js.traversalKind === "Allows") - js.return(true); - } -}; -var writeDefaultIntersectionMessage = (lValue, rValue) => `Invalid intersection of default values ${printable2(lValue)} & ${printable2(rValue)}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/optional.js -var implementation11 = implementNode({ - kind: "optional", - hasAssociatedError: false, - intersectionIsOpen: true, - keys: { - key: {}, - value: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - }, - default: { - preserveUndefined: true - } - }, - normalize: (schema2) => schema2, - reduce: (inner, $2) => { - if ($2.resolvedConfig.exactOptionalPropertyTypes === false) { - if (!inner.value.allows(void 0)) { - return $2.node("optional", { ...inner, value: inner.value.or(intrinsic.undefined) }, { prereduced: true }); - } - } - }, - defaults: { - description: (node2) => `${node2.compiledKey}?: ${node2.value.description}` - }, - intersections: { - optional: intersectProps - } -}); -var OptionalNode = class extends BaseProp { - constructor(...args3) { - super(...args3); - if ("default" in this.inner) - assertDefaultValueAssignability(this.value, this.inner.default, this.key); - } - get rawIn() { - const baseIn = super.rawIn; - if (!this.hasDefault()) - return baseIn; - return this.$.node("optional", omit(baseIn.inner, { default: true }), { - prereduced: true - }); - } - get outProp() { - if (!this.hasDefault()) - return this; - const { default: defaultValue, ...requiredInner } = this.inner; - return this.cacheGetter("outProp", this.$.node("required", requiredInner, { prereduced: true })); - } - expression = this.hasDefault() ? `${this.compiledKey}: ${this.value.expression} = ${printable2(this.inner.default)}` : `${this.compiledKey}?: ${this.value.expression}`; - defaultValueMorph = getDefaultableMorph(this); - defaultValueMorphRef = this.defaultValueMorph && registeredReference(this.defaultValueMorph); -}; -var Optional = { - implementation: implementation11, - Node: OptionalNode -}; -var defaultableMorphCache = {}; -var getDefaultableMorph = (node2) => { - if (!node2.hasDefault()) - return; - const cacheKey = `{${node2.compiledKey}: ${node2.value.id} = ${defaultValueSerializer(node2.default)}}`; - return defaultableMorphCache[cacheKey] ??= computeDefaultValueMorph(node2.key, node2.value, node2.default); -}; -var computeDefaultValueMorph = (key, value2, defaultInput) => { - if (typeof defaultInput === "function") { - return value2.includesTransform ? (data, ctx) => { - traverseKey(key, () => value2(data[key] = defaultInput(), ctx), ctx); - return data; - } : (data) => { - data[key] = defaultInput(); - return data; - }; - } - const precomputedMorphedDefault = value2.includesTransform ? value2.assert(defaultInput) : defaultInput; - return hasDomain2(precomputedMorphedDefault, "object") ? ( - // the type signature only allows this if the value was morphed - (data, ctx) => { - traverseKey(key, () => value2(data[key] = defaultInput, ctx), ctx); - return data; - } - ) : (data) => { - data[key] = precomputedMorphedDefault; - return data; - }; -}; -var assertDefaultValueAssignability = (node2, value2, key) => { - const wrapped = isThunk(value2); - if (hasDomain2(value2, "object") && !wrapped) - throwParseError2(writeNonPrimitiveNonFunctionDefaultValueMessage(key)); - const out = node2.in(wrapped ? value2() : value2); - if (out instanceof ArkErrors) { - if (key === null) { - throwParseError2(`Default ${out.summary}`); - } - const atPath = out.transform((e) => e.transform((input) => ({ ...input, prefixPath: [key] }))); - throwParseError2(`Default for ${atPath.summary}`); - } - return value2; -}; -var writeNonPrimitiveNonFunctionDefaultValueMessage = (key) => { - const keyDescription = key === null ? "" : typeof key === "number" ? `for value at [${key}] ` : `for ${compileSerializedValue(key)} `; - return `Non-primitive default ${keyDescription}must be specified as a function like () => ({my: 'object'})`; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/root.js -var BaseRoot = class extends BaseNode { - constructor(attachments, $2) { - super(attachments, $2); - Object.defineProperty(this, arkKind, { value: "root", enumerable: false }); - } - // doesn't seem possible to override this at a type-level (e.g. via declare) - // without TS complaining about getters - get rawIn() { - return super.rawIn; - } - get rawOut() { - return super.rawOut; - } - get internal() { - return this; - } - get "~standard"() { - return { - vendor: "arktype", - version: 1, - validate: (input) => { - const out = this(input); - if (out instanceof ArkErrors) - return out; - return { value: out }; - }, - jsonSchema: { - input: (opts) => this.rawIn.toJsonSchema({ - target: validateStandardJsonSchemaTarget(opts.target), - ...opts.libraryOptions - }), - output: (opts) => this.rawOut.toJsonSchema({ - target: validateStandardJsonSchemaTarget(opts.target), - ...opts.libraryOptions - }) - } - }; - } - as() { - return this; - } - brand(name) { - if (name === "") - return throwParseError2(emptyBrandNameMessage); - return this; - } - readonly() { - return this; - } - branches = this.hasKind("union") ? this.inner.branches : [this]; - distribute(mapBranch, reduceMapped) { - const mappedBranches = this.branches.map(mapBranch); - return reduceMapped?.(mappedBranches) ?? mappedBranches; - } - get shortDescription() { - return this.meta.description ?? this.defaultShortDescription; - } - toJsonSchema(opts = {}) { - const ctx = mergeToJsonSchemaConfigs(this.$.resolvedConfig.toJsonSchema, opts); - ctx.useRefs ||= this.isCyclic; - const schema2 = typeof ctx.dialect === "string" ? { $schema: ctx.dialect } : {}; - Object.assign(schema2, this.toJsonSchemaRecurse(ctx)); - if (ctx.useRefs) { - const defs = flatMorph2(this.references, (i, ref) => ref.isRoot() && !ref.alwaysExpandJsonSchema ? [ref.id, ref.toResolvedJsonSchema(ctx)] : []); - if (ctx.target === "draft-07") - Object.assign(schema2, { definitions: defs }); - else - schema2.$defs = defs; - } - return schema2; - } - toJsonSchemaRecurse(ctx) { - if (ctx.useRefs && !this.alwaysExpandJsonSchema) { - const defsKey = ctx.target === "draft-07" ? "definitions" : "$defs"; - return { $ref: `#/${defsKey}/${this.id}` }; - } - return this.toResolvedJsonSchema(ctx); - } - get alwaysExpandJsonSchema() { - return this.isBasis() || this.kind === "alias" || this.hasKind("union") && this.isBoolean; - } - toResolvedJsonSchema(ctx) { - const result = this.innerToJsonSchema(ctx); - return Object.assign(result, this.metaJson); - } - intersect(r) { - const rNode = this.$.parseDefinition(r); - const result = this.rawIntersect(rNode); - if (result instanceof Disjoint) - return result; - return this.$.finalize(result); - } - rawIntersect(r) { - return intersectNodesRoot(this, r, this.$); - } - toNeverIfDisjoint() { - return this; - } - and(r) { - const result = this.intersect(r); - return result instanceof Disjoint ? result.throw() : result; - } - rawAnd(r) { - const result = this.rawIntersect(r); - return result instanceof Disjoint ? result.throw() : result; - } - or(r) { - const rNode = this.$.parseDefinition(r); - return this.$.finalize(this.rawOr(rNode)); - } - rawOr(r) { - const branches = [...this.branches, ...r.branches]; - return this.$.node("union", branches); - } - map(flatMapEntry) { - return this.$.schema(this.applyStructuralOperation("map", [flatMapEntry])); - } - pick(...keys) { - return this.$.schema(this.applyStructuralOperation("pick", keys)); - } - omit(...keys) { - return this.$.schema(this.applyStructuralOperation("omit", keys)); - } - required() { - return this.$.schema(this.applyStructuralOperation("required", [])); - } - partial() { - return this.$.schema(this.applyStructuralOperation("partial", [])); - } - _keyof; - keyof() { - if (this._keyof) - return this._keyof; - const result = this.applyStructuralOperation("keyof", []).reduce((result2, branch) => result2.intersect(branch).toNeverIfDisjoint(), $ark.intrinsic.unknown.internal); - if (result.branches.length === 0) { - throwParseError2(writeUnsatisfiableExpressionError(`keyof ${this.expression}`)); - } - return this._keyof = this.$.finalize(result); - } - get props() { - if (this.branches.length !== 1) - return throwParseError2(writeLiteralUnionEntriesMessage(this.expression)); - return [...this.applyStructuralOperation("props", [])[0]]; - } - merge(r) { - const rNode = this.$.parseDefinition(r); - return this.$.schema(rNode.distribute((branch) => this.applyStructuralOperation("merge", [ - structureOf(branch) ?? throwParseError2(writeNonStructuralOperandMessage("merge", branch.expression)) - ]))); - } - applyStructuralOperation(operation, args3) { - return this.distribute((branch) => { - if (branch.equals($ark.intrinsic.object) && operation !== "merge") - return branch; - const structure = structureOf(branch); - if (!structure) { - throwParseError2(writeNonStructuralOperandMessage(operation, branch.expression)); - } - if (operation === "keyof") - return structure.keyof(); - if (operation === "get") - return structure.get(...args3); - if (operation === "props") - return structure.props; - const structuralMethodName = operation === "required" ? "require" : operation === "partial" ? "optionalize" : operation; - return this.$.node("intersection", { - domain: "object", - structure: structure[structuralMethodName](...args3) - }); - }); - } - get(...path3) { - if (path3[0] === void 0) - return this; - return this.$.schema(this.applyStructuralOperation("get", path3)); - } - extract(r) { - const rNode = this.$.parseDefinition(r); - return this.$.schema(this.branches.filter((branch) => branch.extends(rNode))); - } - exclude(r) { - const rNode = this.$.parseDefinition(r); - return this.$.schema(this.branches.filter((branch) => !branch.extends(rNode))); - } - array() { - return this.$.schema(this.isUnknown() ? { proto: Array } : { - proto: Array, - sequence: this - }, { prereduced: true }); - } - overlaps(r) { - const intersection = this.intersect(r); - return !(intersection instanceof Disjoint); - } - extends(r) { - if (this.isNever()) - return true; - const intersection = this.intersect(r); - return !(intersection instanceof Disjoint) && this.equals(intersection); - } - ifExtends(r) { - return this.extends(r) ? this : void 0; - } - subsumes(r) { - const rNode = this.$.parseDefinition(r); - return rNode.extends(this); - } - configure(meta, selector = "shallow") { - return this.configureReferences(meta, selector); - } - describe(description, selector = "shallow") { - return this.configure({ description }, selector); - } - // these should ideally be implemented in arktype since they use its syntax - // https://github.com/arktypeio/arktype/issues/1223 - optional() { - return [this, "?"]; - } - // these should ideally be implemented in arktype since they use its syntax - // https://github.com/arktypeio/arktype/issues/1223 - default(thunkableValue) { - assertDefaultValueAssignability(this, thunkableValue, null); - return [this, "=", thunkableValue]; - } - from(input) { - return this.assert(input); - } - _pipe(...morphs) { - const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(morph), this); - return this.$.finalize(result); - } - tryPipe(...morphs) { - const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(hasArkKind(morph, "root") ? morph : ((In, ctx) => { - try { - return morph(In, ctx); - } catch (e) { - return ctx.error({ - code: "predicate", - predicate: morph, - actual: `aborted due to error: - ${e} -` - }); - } - })), this); - return this.$.finalize(result); - } - pipe = Object.assign(this._pipe.bind(this), { - try: this.tryPipe.bind(this) - }); - to(def) { - return this.$.finalize(this.toNode(this.$.parseDefinition(def))); - } - toNode(root2) { - const result = pipeNodesRoot(this, root2, this.$); - if (result instanceof Disjoint) - return result.throw(); - return result; - } - rawPipeOnce(morph) { - if (hasArkKind(morph, "root")) - return this.toNode(morph); - return this.distribute((branch) => branch.hasKind("morph") ? this.$.node("morph", { - in: branch.inner.in, - morphs: [...branch.morphs, morph] - }) : this.$.node("morph", { - in: branch, - morphs: [morph] - }), this.$.parseSchema); - } - narrow(predicate) { - return this.constrainOut("predicate", predicate); - } - constrain(kind, schema2) { - return this._constrain("root", kind, schema2); - } - constrainIn(kind, schema2) { - return this._constrain("in", kind, schema2); - } - constrainOut(kind, schema2) { - return this._constrain("out", kind, schema2); - } - _constrain(io, kind, schema2) { - const constraint = this.$.node(kind, schema2); - if (constraint.isRoot()) { - return constraint.isUnknown() ? this : throwInternalError2(`Unexpected constraint node ${constraint}`); - } - const operand = io === "root" ? this : io === "in" ? this.rawIn : this.rawOut; - if (operand.hasKind("morph") || constraint.impliedBasis && !operand.extends(constraint.impliedBasis)) { - return throwInvalidOperandError(kind, constraint.impliedBasis, this); - } - const partialIntersection = this.$.node("intersection", { - // important this is constraint.kind instead of kind in case - // the node was reduced during parsing - [constraint.kind]: constraint - }); - const result = io === "out" ? pipeNodesRoot(this, partialIntersection, this.$) : intersectNodesRoot(this, partialIntersection, this.$); - if (result instanceof Disjoint) - result.throw(); - return this.$.finalize(result); - } - onUndeclaredKey(cfg) { - const rule = typeof cfg === "string" ? cfg : cfg.rule; - const deep = typeof cfg === "string" ? false : cfg.deep; - return this.$.finalize(this.transform((kind, inner) => kind === "structure" ? rule === "ignore" ? omit(inner, { undeclared: 1 }) : { ...inner, undeclared: rule } : inner, deep ? void 0 : { shouldTransform: (node2) => !includes(structuralKinds, node2.kind) })); - } - hasEqualMorphs(r) { - if (!this.includesTransform && !r.includesTransform) - return true; - if (!arrayEquals(this.shallowMorphs, r.shallowMorphs)) - return false; - if (!arrayEquals(this.flatMorphs, r.flatMorphs, { - isEqual: (l, r2) => l.propString === r2.propString && (l.node.hasKind("morph") && r2.node.hasKind("morph") ? l.node.hasEqualMorphs(r2.node) : l.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) - })) - return false; - return true; - } - onDeepUndeclaredKey(behavior) { - return this.onUndeclaredKey({ rule: behavior, deep: true }); - } - filter(predicate) { - return this.constrainIn("predicate", predicate); - } - divisibleBy(schema2) { - return this.constrain("divisor", schema2); - } - matching(schema2) { - return this.constrain("pattern", schema2); - } - atLeast(schema2) { - return this.constrain("min", schema2); - } - atMost(schema2) { - return this.constrain("max", schema2); - } - moreThan(schema2) { - return this.constrain("min", exclusivizeRangeSchema(schema2)); - } - lessThan(schema2) { - return this.constrain("max", exclusivizeRangeSchema(schema2)); - } - atLeastLength(schema2) { - return this.constrain("minLength", schema2); - } - atMostLength(schema2) { - return this.constrain("maxLength", schema2); - } - moreThanLength(schema2) { - return this.constrain("minLength", exclusivizeRangeSchema(schema2)); - } - lessThanLength(schema2) { - return this.constrain("maxLength", exclusivizeRangeSchema(schema2)); - } - exactlyLength(schema2) { - return this.constrain("exactLength", schema2); - } - atOrAfter(schema2) { - return this.constrain("after", schema2); - } - atOrBefore(schema2) { - return this.constrain("before", schema2); - } - laterThan(schema2) { - return this.constrain("after", exclusivizeRangeSchema(schema2)); - } - earlierThan(schema2) { - return this.constrain("before", exclusivizeRangeSchema(schema2)); - } -}; -var emptyBrandNameMessage = `Expected a non-empty brand name after #`; -var supportedJsonSchemaTargets = [ - "draft-2020-12", - "draft-07" -]; -var writeInvalidJsonSchemaTargetMessage = (target) => `JSONSchema target '${target}' is not supported (must be ${supportedJsonSchemaTargets.map((t) => `"${t}"`).join(" or ")})`; -var validateStandardJsonSchemaTarget = (target) => { - if (!includes(supportedJsonSchemaTargets, target)) - throwParseError2(writeInvalidJsonSchemaTargetMessage(target)); - return target; -}; -var exclusivizeRangeSchema = (schema2) => typeof schema2 === "object" && !(schema2 instanceof Date) ? { ...schema2, exclusive: true } : { - rule: schema2, - exclusive: true -}; -var typeOrTermExtends = (t, base) => hasArkKind(base, "root") ? hasArkKind(t, "root") ? t.extends(base) : base.allows(t) : hasArkKind(t, "root") ? t.hasUnit(base) : base === t; -var structureOf = (branch) => { - if (branch.hasKind("morph")) - return null; - if (branch.hasKind("intersection")) { - return branch.inner.structure ?? (branch.basis?.domain === "object" ? branch.$.bindReference($ark.intrinsic.emptyStructure) : null); - } - if (branch.isBasis() && branch.domain === "object") - return branch.$.bindReference($ark.intrinsic.emptyStructure); - return null; -}; -var writeLiteralUnionEntriesMessage = (expression) => `Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received: -${expression}`; -var writeNonStructuralOperandMessage = (operation, operand) => `${operation} operand must be an object (was ${operand})`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/utils.js -var defineRightwardIntersections = (kind, implementation23) => flatMorph2(schemaKindsRightOf(kind), (i, kind2) => [ - kind2, - implementation23 -]); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/alias.js -var normalizeAliasSchema = (schema2) => typeof schema2 === "string" ? { reference: schema2 } : schema2; -var neverIfDisjoint = (result) => result instanceof Disjoint ? $ark.intrinsic.never.internal : result; -var implementation12 = implementNode({ - kind: "alias", - hasAssociatedError: false, - collapsibleKey: "reference", - keys: { - reference: { - serialize: (s) => s.startsWith("$") ? s : `$ark.${s}` - }, - resolve: {} - }, - normalize: normalizeAliasSchema, - defaults: { - description: (node2) => node2.reference - }, - intersections: { - alias: (l, r, ctx) => ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r.resolution, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.reference}`), - ...defineRightwardIntersections("alias", (l, r, ctx) => { - if (r.isUnknown()) - return l; - if (r.isNever()) - return r; - if (r.isBasis() && !r.overlaps($ark.intrinsic.object)) { - return Disjoint.init("assignability", $ark.intrinsic.object, r); - } - return ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.id}`); - }) - } -}); -var AliasNode = class extends BaseRoot { - expression = this.reference; - structure = void 0; - get resolution() { - const result = this._resolve(); - return nodesByRegisteredId[this.id] = result; - } - _resolve() { - if (this.resolve) - return this.resolve(); - if (this.reference[0] === "$") - return this.$.resolveRoot(this.reference.slice(1)); - const id = this.reference; - let resolution = nodesByRegisteredId[id]; - const seen = []; - while (hasArkKind(resolution, "context")) { - if (seen.includes(resolution.id)) { - return throwParseError2(writeShallowCycleErrorMessage(resolution.id, seen)); - } - seen.push(resolution.id); - resolution = nodesByRegisteredId[resolution.id]; - } - if (!hasArkKind(resolution, "root")) { - return throwInternalError2(`Unexpected resolution for reference ${this.reference} -Seen: [${seen.join("->")}] -Resolution: ${printable2(resolution)}`); - } - return resolution; - } - get resolutionId() { - if (this.reference.includes("&") || this.reference.includes("=>")) - return this.resolution.id; - if (this.reference[0] !== "$") - return this.reference; - const alias = this.reference.slice(1); - const resolution = this.$.resolutions[alias]; - if (typeof resolution === "string") - return resolution; - if (hasArkKind(resolution, "root")) - return resolution.id; - return throwInternalError2(`Unexpected resolution for reference ${this.reference}: ${printable2(resolution)}`); - } - get defaultShortDescription() { - return domainDescriptions2.object; - } - innerToJsonSchema(ctx) { - return this.resolution.toJsonSchemaRecurse(ctx); - } - traverseAllows = (data, ctx) => { - const seen = ctx.seen[this.reference]; - if (seen?.includes(data)) - return true; - ctx.seen[this.reference] = append2(seen, data); - return this.resolution.traverseAllows(data, ctx); - }; - traverseApply = (data, ctx) => { - const seen = ctx.seen[this.reference]; - if (seen?.includes(data)) - return; - ctx.seen[this.reference] = append2(seen, data); - this.resolution.traverseApply(data, ctx); - }; - compile(js) { - const id = this.resolutionId; - js.if(`ctx.seen.${id} && ctx.seen.${id}.includes(data)`, () => js.return(true)); - js.if(`!ctx.seen.${id}`, () => js.line(`ctx.seen.${id} = []`)); - js.line(`ctx.seen.${id}.push(data)`); - js.return(js.invoke(id)); - } -}; -var writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join("->")}`; -var Alias = { - implementation: implementation12, - Node: AliasNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/basis.js -var InternalBasis = class extends BaseRoot { - traverseApply = (data, ctx) => { - if (!this.traverseAllows(data, ctx)) - ctx.errorFromNodeContext(this.errorContext); - }; - get errorContext() { - return { - code: this.kind, - description: this.description, - meta: this.meta, - ...this.inner - }; - } - get compiledErrorContext() { - return compileObjectLiteral(this.errorContext); - } - compile(js) { - if (js.traversalKind === "Allows") - js.return(this.compiledCondition); - else { - js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); - } - } -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/domain.js -var implementation13 = implementNode({ - kind: "domain", - hasAssociatedError: true, - collapsibleKey: "domain", - keys: { - domain: {}, - numberAllowsNaN: {} - }, - normalize: (schema2) => typeof schema2 === "string" ? { domain: schema2 } : hasKey(schema2, "numberAllowsNaN") && schema2.domain !== "number" ? throwParseError2(Domain.writeBadAllowNanMessage(schema2.domain)) : schema2, - applyConfig: (schema2, config2) => schema2.numberAllowsNaN === void 0 && schema2.domain === "number" && config2.numberAllowsNaN ? { ...schema2, numberAllowsNaN: true } : schema2, - defaults: { - description: (node2) => domainDescriptions2[node2.domain], - actual: (data) => Number.isNaN(data) ? "NaN" : domainDescriptions2[domainOf2(data)] - }, - intersections: { - domain: (l, r) => ( - // since l === r is handled by default, remaining cases are disjoint - // outside those including options like numberAllowsNaN - l.domain === "number" && r.domain === "number" ? l.numberAllowsNaN ? r : l : Disjoint.init("domain", l, r) - ) - } -}); -var DomainNode = class extends InternalBasis { - requiresNaNCheck = this.domain === "number" && !this.numberAllowsNaN; - traverseAllows = this.requiresNaNCheck ? (data) => typeof data === "number" && !Number.isNaN(data) : (data) => domainOf2(data) === this.domain; - compiledCondition = this.domain === "object" ? `((typeof data === "object" && data !== null) || typeof data === "function")` : `typeof data === "${this.domain}"${this.requiresNaNCheck ? " && !Number.isNaN(data)" : ""}`; - compiledNegation = this.domain === "object" ? `((typeof data !== "object" || data === null) && typeof data !== "function")` : `typeof data !== "${this.domain}"${this.requiresNaNCheck ? " || Number.isNaN(data)" : ""}`; - expression = this.numberAllowsNaN ? "number | NaN" : this.domain; - get nestableExpression() { - return this.numberAllowsNaN ? `(${this.expression})` : this.expression; - } - get defaultShortDescription() { - return domainDescriptions2[this.domain]; - } - innerToJsonSchema(ctx) { - if (this.domain === "bigint" || this.domain === "symbol") { - return ctx.fallback.domain({ - code: "domain", - base: {}, - domain: this.domain - }); - } - return { - type: this.domain - }; - } -}; -var Domain = { - implementation: implementation13, - Node: DomainNode, - writeBadAllowNanMessage: (actual) => `numberAllowsNaN may only be specified with domain "number" (was ${actual})` -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/intersection.js -var implementation14 = implementNode({ - kind: "intersection", - hasAssociatedError: true, - normalize: (rawSchema) => { - if (isNode(rawSchema)) - return rawSchema; - const { structure, ...schema2 } = rawSchema; - const hasRootStructureKey = !!structure; - const normalizedStructure = structure ?? {}; - const normalized = flatMorph2(schema2, (k, v) => { - if (isKeyOf2(k, structureKeys)) { - if (hasRootStructureKey) { - throwParseError2(`Flattened structure key ${k} cannot be specified alongside a root 'structure' key.`); - } - normalizedStructure[k] = v; - return []; - } - return [k, v]; - }); - if (hasArkKind(normalizedStructure, "constraint") || !isEmptyObject2(normalizedStructure)) - normalized.structure = normalizedStructure; - return normalized; - }, - finalizeInnerJson: ({ structure, ...rest }) => hasDomain2(structure, "object") ? { ...structure, ...rest } : rest, - keys: { - domain: { - child: true, - parse: (schema2, ctx) => ctx.$.node("domain", schema2) - }, - proto: { - child: true, - parse: (schema2, ctx) => ctx.$.node("proto", schema2) - }, - structure: { - child: true, - parse: (schema2, ctx) => ctx.$.node("structure", schema2), - serialize: (node2) => { - if (!node2.sequence?.minLength) - return node2.collapsibleJson; - const { sequence, ...structureJson } = node2.collapsibleJson; - const { minVariadicLength, ...sequenceJson } = sequence; - const collapsibleSequenceJson = sequenceJson.variadic && Object.keys(sequenceJson).length === 1 ? sequenceJson.variadic : sequenceJson; - return { ...structureJson, sequence: collapsibleSequenceJson }; - } - }, - divisor: { - child: true, - parse: constraintKeyParser("divisor") - }, - max: { - child: true, - parse: constraintKeyParser("max") - }, - min: { - child: true, - parse: constraintKeyParser("min") - }, - maxLength: { - child: true, - parse: constraintKeyParser("maxLength") - }, - minLength: { - child: true, - parse: constraintKeyParser("minLength") - }, - exactLength: { - child: true, - parse: constraintKeyParser("exactLength") - }, - before: { - child: true, - parse: constraintKeyParser("before") - }, - after: { - child: true, - parse: constraintKeyParser("after") - }, - pattern: { - child: true, - parse: constraintKeyParser("pattern") - }, - predicate: { - child: true, - parse: constraintKeyParser("predicate") - } - }, - // leverage reduction logic from intersection and identity to ensure initial - // parse result is reduced - reduce: (inner, $2) => ( - // we cast union out of the result here since that only occurs when intersecting two sequences - // that cannot occur when reducing a single intersection schema using unknown - intersectIntersections({}, inner, { - $: $2, - invert: false, - pipe: false - }) - ), - defaults: { - description: (node2) => { - if (node2.children.length === 0) - return "unknown"; - if (node2.structure) - return node2.structure.description; - const childDescriptions = []; - if (node2.basis && !node2.prestructurals.some((r) => r.impl.obviatesBasisDescription)) - childDescriptions.push(node2.basis.description); - if (node2.prestructurals.length) { - const sortedRefinementDescriptions = node2.prestructurals.slice().sort((l, r) => l.kind === "min" && r.kind === "max" ? -1 : 0).map((r) => r.description); - childDescriptions.push(...sortedRefinementDescriptions); - } - if (node2.inner.predicate) { - childDescriptions.push(...node2.inner.predicate.map((p) => p.description)); - } - return childDescriptions.join(" and "); - }, - expected: (source) => ` \u25E6 ${source.errors.map((e) => e.expected).join("\n \u25E6 ")}`, - problem: (ctx) => `(${ctx.actual}) must be... -${ctx.expected}` - }, - intersections: { - intersection: (l, r, ctx) => intersectIntersections(l.inner, r.inner, ctx), - ...defineRightwardIntersections("intersection", (l, r, ctx) => { - if (l.children.length === 0) - return r; - const { domain: domain2, proto, ...lInnerConstraints } = l.inner; - const lBasis = proto ?? domain2; - const basis = lBasis ? intersectOrPipeNodes(lBasis, r, ctx) : r; - return basis instanceof Disjoint ? basis : l?.basis?.equals(basis) ? ( - // if the basis doesn't change, return the original intesection - l - ) : l.$.node("intersection", { ...lInnerConstraints, [basis.kind]: basis }, { prereduced: true }); - }) - } -}); -var IntersectionNode = class extends BaseRoot { - basis = this.inner.domain ?? this.inner.proto ?? null; - prestructurals = []; - refinements = this.children.filter((node2) => { - if (!node2.isRefinement()) - return false; - if (includes(prestructuralKinds, node2.kind)) - this.prestructurals.push(node2); - return true; - }); - structure = this.inner.structure; - expression = writeIntersectionExpression(this); - get shallowMorphs() { - return this.inner.structure?.structuralMorph ? [this.inner.structure.structuralMorph] : []; - } - get defaultShortDescription() { - return this.basis?.defaultShortDescription ?? "present"; - } - innerToJsonSchema(ctx) { - return this.children.reduce( - // cast is required since TS doesn't know children have compatible schema prerequisites - (schema2, child) => child.isBasis() ? child.toJsonSchemaRecurse(ctx) : child.reduceJsonSchema(schema2, ctx), - {} - ); - } - traverseAllows = (data, ctx) => this.children.every((child) => child.traverseAllows(data, ctx)); - traverseApply = (data, ctx) => { - const errorCount = ctx.currentErrorCount; - if (this.basis) { - this.basis.traverseApply(data, ctx); - if (ctx.currentErrorCount > errorCount) - return; - } - if (this.prestructurals.length) { - for (let i = 0; i < this.prestructurals.length - 1; i++) { - this.prestructurals[i].traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return; - } - this.prestructurals[this.prestructurals.length - 1].traverseApply(data, ctx); - if (ctx.currentErrorCount > errorCount) - return; - } - if (this.structure) { - this.structure.traverseApply(data, ctx); - if (ctx.currentErrorCount > errorCount) - return; - } - if (this.inner.predicate) { - for (let i = 0; i < this.inner.predicate.length - 1; i++) { - this.inner.predicate[i].traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return; - } - this.inner.predicate[this.inner.predicate.length - 1].traverseApply(data, ctx); - } - }; - compile(js) { - if (js.traversalKind === "Allows") { - for (const child of this.children) - js.check(child); - js.return(true); - return; - } - js.initializeErrorCount(); - if (this.basis) { - js.check(this.basis); - if (this.children.length > 1) - js.returnIfFail(); - } - if (this.prestructurals.length) { - for (let i = 0; i < this.prestructurals.length - 1; i++) { - js.check(this.prestructurals[i]); - js.returnIfFailFast(); - } - js.check(this.prestructurals[this.prestructurals.length - 1]); - if (this.structure || this.inner.predicate) - js.returnIfFail(); - } - if (this.structure) { - js.check(this.structure); - if (this.inner.predicate) - js.returnIfFail(); - } - if (this.inner.predicate) { - for (let i = 0; i < this.inner.predicate.length - 1; i++) { - js.check(this.inner.predicate[i]); - js.returnIfFail(); - } - js.check(this.inner.predicate[this.inner.predicate.length - 1]); - } - } -}; -var Intersection = { - implementation: implementation14, - Node: IntersectionNode -}; -var writeIntersectionExpression = (node2) => { - if (node2.structure?.expression) - return node2.structure.expression; - const basisExpression = node2.basis && !node2.prestructurals.some((n) => n.impl.obviatesBasisExpression) ? node2.basis.nestableExpression : ""; - const refinementsExpression = node2.prestructurals.map((n) => n.expression).join(" & "); - const fullExpression = `${basisExpression}${basisExpression ? " " : ""}${refinementsExpression}`; - if (fullExpression === "Array == 0") - return "[]"; - return fullExpression || "unknown"; -}; -var intersectIntersections = (l, r, ctx) => { - const baseInner = {}; - const lBasis = l.proto ?? l.domain; - const rBasis = r.proto ?? r.domain; - const basisResult = lBasis ? rBasis ? intersectOrPipeNodes(lBasis, rBasis, ctx) : lBasis : rBasis; - if (basisResult instanceof Disjoint) - return basisResult; - if (basisResult) - baseInner[basisResult.kind] = basisResult; - return intersectConstraints({ - kind: "intersection", - baseInner, - l: flattenConstraints(l), - r: flattenConstraints(r), - roots: [], - ctx - }); -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/morph.js -var implementation15 = implementNode({ - kind: "morph", - hasAssociatedError: false, - keys: { - in: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - }, - morphs: { - parse: liftArray, - serialize: (morphs) => morphs.map((m) => hasArkKind(m, "root") ? m.json : registeredReference(m)) - }, - declaredIn: { - child: false, - serialize: (node2) => node2.json - }, - declaredOut: { - child: false, - serialize: (node2) => node2.json - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => `a morph from ${node2.rawIn.description} to ${node2.rawOut?.description ?? "unknown"}` - }, - intersections: { - morph: (l, r, ctx) => { - if (!l.hasEqualMorphs(r)) { - return throwParseError2(writeMorphIntersectionMessage(l.expression, r.expression)); - } - const inTersection = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); - if (inTersection instanceof Disjoint) - return inTersection; - const baseInner = { - morphs: l.morphs - }; - if (l.declaredIn || r.declaredIn) { - const declaredIn = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); - if (declaredIn instanceof Disjoint) - return declaredIn.throw(); - else - baseInner.declaredIn = declaredIn; - } - if (l.declaredOut || r.declaredOut) { - const declaredOut = intersectOrPipeNodes(l.rawOut, r.rawOut, ctx); - if (declaredOut instanceof Disjoint) - return declaredOut.throw(); - else - baseInner.declaredOut = declaredOut; - } - return inTersection.distribute((inBranch) => ctx.$.node("morph", { - ...baseInner, - in: inBranch - }), ctx.$.parseSchema); - }, - ...defineRightwardIntersections("morph", (l, r, ctx) => { - const inTersection = l.inner.in ? intersectOrPipeNodes(l.inner.in, r, ctx) : r; - return inTersection instanceof Disjoint ? inTersection : inTersection.equals(l.inner.in) ? l : ctx.$.node("morph", { - ...l.inner, - in: inTersection - }); - }) - } -}); -var MorphNode = class extends BaseRoot { - serializedMorphs = this.morphs.map(registeredReference); - compiledMorphs = `[${this.serializedMorphs}]`; - lastMorph = this.inner.morphs[this.inner.morphs.length - 1]; - lastMorphIfNode = hasArkKind(this.lastMorph, "root") ? this.lastMorph : void 0; - introspectableIn = this.inner.in; - introspectableOut = this.lastMorphIfNode ? Object.assign(this.referencesById, this.lastMorphIfNode.referencesById) && this.lastMorphIfNode.rawOut : void 0; - get shallowMorphs() { - return Array.isArray(this.inner.in?.shallowMorphs) ? [...this.inner.in.shallowMorphs, ...this.morphs] : this.morphs; - } - get rawIn() { - return this.declaredIn ?? this.inner.in?.rawIn ?? $ark.intrinsic.unknown.internal; - } - get rawOut() { - return this.declaredOut ?? this.introspectableOut ?? $ark.intrinsic.unknown.internal; - } - declareIn(declaredIn) { - return this.$.node("morph", { - ...this.inner, - declaredIn - }); - } - declareOut(declaredOut) { - return this.$.node("morph", { - ...this.inner, - declaredOut - }); - } - expression = `(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode ? "To" : "Out"}<${this.rawOut.expression}>`; - get defaultShortDescription() { - return this.rawIn.meta.description ?? this.rawIn.defaultShortDescription; - } - innerToJsonSchema(ctx) { - return ctx.fallback.morph({ - code: "morph", - base: this.rawIn.toJsonSchemaRecurse(ctx), - out: this.introspectableOut?.toJsonSchemaRecurse(ctx) ?? null - }); - } - compile(js) { - if (js.traversalKind === "Allows") { - if (!this.introspectableIn) - return; - js.return(js.invoke(this.introspectableIn)); - return; - } - if (this.introspectableIn) - js.line(js.invoke(this.introspectableIn)); - js.line(`ctx.queueMorphs(${this.compiledMorphs})`); - } - traverseAllows = (data, ctx) => !this.introspectableIn || this.introspectableIn.traverseAllows(data, ctx); - traverseApply = (data, ctx) => { - if (this.introspectableIn) - this.introspectableIn.traverseApply(data, ctx); - ctx.queueMorphs(this.morphs); - }; - /** Check if the morphs of r are equal to those of this node */ - hasEqualMorphs(r) { - return arrayEquals(this.morphs, r.morphs, { - isEqual: (lMorph, rMorph) => lMorph === rMorph || hasArkKind(lMorph, "root") && hasArkKind(rMorph, "root") && lMorph.equals(rMorph) - }); - } -}; -var Morph = { - implementation: implementation15, - Node: MorphNode -}; -var writeMorphIntersectionMessage = (lDescription, rDescription) => `The intersection of distinct morphs at a single path is indeterminate: -Left: ${lDescription} -Right: ${rDescription}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/proto.js -var implementation16 = implementNode({ - kind: "proto", - hasAssociatedError: true, - collapsibleKey: "proto", - keys: { - proto: { - serialize: (ctor) => getBuiltinNameOfConstructor2(ctor) ?? defaultValueSerializer(ctor) - }, - dateAllowsInvalid: {} - }, - normalize: (schema2) => { - const normalized = typeof schema2 === "string" ? { proto: builtinConstructors2[schema2] } : typeof schema2 === "function" ? isNode(schema2) ? schema2 : { proto: schema2 } : typeof schema2.proto === "string" ? { ...schema2, proto: builtinConstructors2[schema2.proto] } : schema2; - if (typeof normalized.proto !== "function") - throwParseError2(Proto.writeInvalidSchemaMessage(normalized.proto)); - if (hasKey(normalized, "dateAllowsInvalid") && normalized.proto !== Date) - throwParseError2(Proto.writeBadInvalidDateMessage(normalized.proto)); - return normalized; - }, - applyConfig: (schema2, config2) => { - if (schema2.dateAllowsInvalid === void 0 && schema2.proto === Date && config2.dateAllowsInvalid) - return { ...schema2, dateAllowsInvalid: true }; - return schema2; - }, - defaults: { - description: (node2) => node2.builtinName ? objectKindDescriptions2[node2.builtinName] : `an instance of ${node2.proto.name}`, - actual: (data) => data instanceof Date && data.toString() === "Invalid Date" ? "an invalid Date" : objectKindOrDomainOf(data) - }, - intersections: { - proto: (l, r) => l.proto === Date && r.proto === Date ? ( - // since l === r is handled by default, - // exactly one of l or r must have allow invalid dates - l.dateAllowsInvalid ? r : l - ) : constructorExtends(l.proto, r.proto) ? l : constructorExtends(r.proto, l.proto) ? r : Disjoint.init("proto", l, r), - domain: (proto, domain2) => domain2.domain === "object" ? proto : Disjoint.init("domain", $ark.intrinsic.object.internal, domain2) - } -}); -var ProtoNode = class extends InternalBasis { - builtinName = getBuiltinNameOfConstructor2(this.proto); - serializedConstructor = this.json.proto; - requiresInvalidDateCheck = this.proto === Date && !this.dateAllowsInvalid; - traverseAllows = this.requiresInvalidDateCheck ? (data) => data instanceof Date && data.toString() !== "Invalid Date" : (data) => data instanceof this.proto; - compiledCondition = `data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck ? ` && data.toString() !== "Invalid Date"` : ""}`; - compiledNegation = `!(${this.compiledCondition})`; - innerToJsonSchema(ctx) { - switch (this.builtinName) { - case "Array": - return { - type: "array" - }; - case "Date": - return ctx.fallback.date?.({ code: "date", base: {} }) ?? ctx.fallback.proto({ code: "proto", base: {}, proto: this.proto }); - default: - return ctx.fallback.proto({ - code: "proto", - base: {}, - proto: this.proto - }); - } - } - expression = this.dateAllowsInvalid ? "Date | InvalidDate" : this.proto.name; - get nestableExpression() { - return this.dateAllowsInvalid ? `(${this.expression})` : this.expression; - } - domain = "object"; - get defaultShortDescription() { - return this.description; - } -}; -var Proto = { - implementation: implementation16, - Node: ProtoNode, - writeBadInvalidDateMessage: (actual) => `dateAllowsInvalid may only be specified with constructor Date (was ${actual.name})`, - writeInvalidSchemaMessage: (actual) => `instanceOf operand must be a function (was ${domainOf2(actual)})` -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/union.js -var implementation17 = implementNode({ - kind: "union", - hasAssociatedError: true, - collapsibleKey: "branches", - keys: { - ordered: {}, - branches: { - child: true, - parse: (schema2, ctx) => { - const branches = []; - for (const branchSchema of schema2) { - const branchNodes = hasArkKind(branchSchema, "root") ? branchSchema.branches : ctx.$.parseSchema(branchSchema).branches; - for (const node2 of branchNodes) { - if (node2.hasKind("morph")) { - const matchingMorphIndex = branches.findIndex((matching) => matching.hasKind("morph") && matching.hasEqualMorphs(node2)); - if (matchingMorphIndex === -1) - branches.push(node2); - else { - const matchingMorph = branches[matchingMorphIndex]; - branches[matchingMorphIndex] = ctx.$.node("morph", { - ...matchingMorph.inner, - in: matchingMorph.rawIn.rawOr(node2.rawIn) - }); - } - } else - branches.push(node2); - } - } - if (!ctx.def.ordered) - branches.sort((l, r) => l.hash < r.hash ? -1 : 1); - return branches; - } - } - }, - normalize: (schema2) => isArray(schema2) ? { branches: schema2 } : schema2, - reduce: (inner, $2) => { - const reducedBranches = reduceBranches(inner); - if (reducedBranches.length === 1) - return reducedBranches[0]; - if (reducedBranches.length === inner.branches.length) - return; - return $2.node("union", { - ...inner, - branches: reducedBranches - }, { prereduced: true }); - }, - defaults: { - description: (node2) => node2.distribute((branch) => branch.description, describeBranches), - expected: (ctx) => { - const byPath = groupBy(ctx.errors, "propString"); - const pathDescriptions = Object.entries(byPath).map(([path3, errors]) => { - const branchesAtPath = []; - for (const errorAtPath of errors) - appendUnique(branchesAtPath, errorAtPath.expected); - const expected = describeBranches(branchesAtPath); - const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable2(errors[0].data); - return `${path3 && `${path3} `}must be ${expected}${actual && ` (was ${actual})`}`; - }); - return describeBranches(pathDescriptions); - }, - problem: (ctx) => ctx.expected, - message: (ctx) => { - if (ctx.problem[0] === "[") { - return `value at ${ctx.problem}`; - } - return ctx.problem; - } - }, - intersections: { - union: (l, r, ctx) => { - if (l.isNever !== r.isNever) { - return Disjoint.init("presence", l, r); - } - let resultBranches; - if (l.ordered) { - if (r.ordered) { - throwParseError2(writeOrderedIntersectionMessage(l.expression, r.expression)); - } - resultBranches = intersectBranches(r.branches, l.branches, ctx); - if (resultBranches instanceof Disjoint) - resultBranches.invert(); - } else - resultBranches = intersectBranches(l.branches, r.branches, ctx); - if (resultBranches instanceof Disjoint) - return resultBranches; - return ctx.$.parseSchema(l.ordered || r.ordered ? { - branches: resultBranches, - ordered: true - } : { branches: resultBranches }); - }, - ...defineRightwardIntersections("union", (l, r, ctx) => { - const branches = intersectBranches(l.branches, [r], ctx); - if (branches instanceof Disjoint) - return branches; - if (branches.length === 1) - return branches[0]; - return ctx.$.parseSchema(l.ordered ? { branches, ordered: true } : { branches }); - }) - } -}); -var UnionNode = class extends BaseRoot { - isBoolean = this.branches.length === 2 && this.branches[0].hasUnit(false) && this.branches[1].hasUnit(true); - get branchGroups() { - const branchGroups = []; - let firstBooleanIndex = -1; - for (const branch of this.branches) { - if (branch.hasKind("unit") && branch.domain === "boolean") { - if (firstBooleanIndex === -1) { - firstBooleanIndex = branchGroups.length; - branchGroups.push(branch); - } else - branchGroups[firstBooleanIndex] = $ark.intrinsic.boolean; - continue; - } - branchGroups.push(branch); - } - return branchGroups; - } - unitBranches = this.branches.filter((n) => n.rawIn.hasKind("unit")); - discriminant = this.discriminate(); - discriminantJson = this.discriminant ? discriminantToJson(this.discriminant) : null; - expression = this.distribute((n) => n.nestableExpression, expressBranches); - createBranchedOptimisticRootApply() { - return (data, onFail) => { - const optimisticResult = this.traverseOptimistic(data); - if (optimisticResult !== unset2) - return optimisticResult; - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - } - get shallowMorphs() { - return this.branches.reduce((morphs, branch) => appendUnique(morphs, branch.shallowMorphs), []); - } - get defaultShortDescription() { - return this.distribute((branch) => branch.defaultShortDescription, describeBranches); - } - innerToJsonSchema(ctx) { - if (this.branchGroups.length === 1 && this.branchGroups[0].equals($ark.intrinsic.boolean)) - return { type: "boolean" }; - const jsonSchemaBranches = this.branchGroups.map((group) => group.toJsonSchemaRecurse(ctx)); - if (jsonSchemaBranches.every((branch) => ( - // iff all branches are pure unit values with no metadata, - // we can simplify the representation to an enum - Object.keys(branch).length === 1 && hasKey(branch, "const") - ))) { - return { - enum: jsonSchemaBranches.map((branch) => branch.const) - }; - } - return { - anyOf: jsonSchemaBranches - }; - } - traverseAllows = (data, ctx) => this.branches.some((b) => b.traverseAllows(data, ctx)); - traverseApply = (data, ctx) => { - const errors = []; - for (let i = 0; i < this.branches.length; i++) { - ctx.pushBranch(); - this.branches[i].traverseApply(data, ctx); - if (!ctx.hasError()) { - if (this.branches[i].includesTransform) - return ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs); - return ctx.popBranch(); - } - errors.push(ctx.popBranch().error); - } - ctx.errorFromNodeContext({ code: "union", errors, meta: this.meta }); - }; - traverseOptimistic = (data) => { - for (let i = 0; i < this.branches.length; i++) { - const branch = this.branches[i]; - if (branch.traverseAllows(data)) { - if (branch.contextFreeMorph) - return branch.contextFreeMorph(data); - return data; - } - } - return unset2; - }; - compile(js) { - if (!this.discriminant || // if we have a union of two units like `boolean`, the - // undiscriminated compilation will be just as fast - this.unitBranches.length === this.branches.length && this.branches.length === 2) - return this.compileIndiscriminable(js); - let condition = this.discriminant.optionallyChainedPropString; - if (this.discriminant.kind === "domain") - condition = `typeof ${condition} === "object" ? ${condition} === null ? "null" : "object" : typeof ${condition} === "function" ? "object" : typeof ${condition}`; - const cases = this.discriminant.cases; - const caseKeys = Object.keys(cases); - const { optimistic } = js; - js.optimistic = false; - js.block(`switch(${condition})`, () => { - for (const k in cases) { - const v = cases[k]; - const caseCondition = k === "default" ? k : `case ${k}`; - let caseResult; - if (v === true) - caseResult = optimistic ? "data" : "true"; - else if (optimistic) { - if (v.rootApplyStrategy === "branchedOptimistic") - caseResult = js.invoke(v, { kind: "Optimistic" }); - else if (v.contextFreeMorph) - caseResult = `${js.invoke(v)} ? ${registeredReference(v.contextFreeMorph)}(data) : "${unset2}"`; - else - caseResult = `${js.invoke(v)} ? data : "${unset2}"`; - } else - caseResult = js.invoke(v); - js.line(`${caseCondition}: return ${caseResult}`); - } - return js; - }); - if (js.traversalKind === "Allows") { - js.return(optimistic ? `"${unset2}"` : false); - return; - } - const expected = describeBranches(this.discriminant.kind === "domain" ? caseKeys.map((k) => { - const jsTypeOf = k.slice(1, -1); - return jsTypeOf === "function" ? domainDescriptions2.object : domainDescriptions2[jsTypeOf]; - }) : caseKeys); - const serializedPathSegments = this.discriminant.path.map((k) => typeof k === "symbol" ? registeredReference(k) : JSON.stringify(k)); - const serializedExpected = JSON.stringify(expected); - const serializedActual = this.discriminant.kind === "domain" ? `${serializedTypeOfDescriptions}[${condition}]` : `${serializedPrintable}(${condition})`; - js.line(`ctx.errorFromNodeContext({ - code: "predicate", - expected: ${serializedExpected}, - actual: ${serializedActual}, - relativePath: [${serializedPathSegments}], - meta: ${this.compiledMeta} -})`); - } - compileIndiscriminable(js) { - if (js.traversalKind === "Apply") { - js.const("errors", "[]"); - for (const branch of this.branches) { - js.line("ctx.pushBranch()").line(js.invoke(branch)).if("!ctx.hasError()", () => js.return(branch.includesTransform ? "ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)" : "ctx.popBranch()")).line("errors.push(ctx.popBranch().error)"); - } - js.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`); - } else { - const { optimistic } = js; - js.optimistic = false; - for (const branch of this.branches) { - js.if(`${js.invoke(branch)}`, () => js.return(optimistic ? branch.contextFreeMorph ? `${registeredReference(branch.contextFreeMorph)}(data)` : "data" : true)); - } - js.return(optimistic ? `"${unset2}"` : false); - } - } - get nestableExpression() { - return this.isBoolean ? "boolean" : `(${this.expression})`; - } - discriminate() { - if (this.branches.length < 2 || this.isCyclic) - return null; - if (this.unitBranches.length === this.branches.length) { - const cases2 = flatMorph2(this.unitBranches, (i, n) => [ - `${n.rawIn.serializedValue}`, - n.hasKind("morph") ? n : true - ]); - return { - kind: "unit", - path: [], - optionallyChainedPropString: "data", - cases: cases2 - }; - } - const candidates = []; - for (let lIndex = 0; lIndex < this.branches.length - 1; lIndex++) { - const l = this.branches[lIndex]; - for (let rIndex = lIndex + 1; rIndex < this.branches.length; rIndex++) { - const r = this.branches[rIndex]; - const result = intersectNodesRoot(l.rawIn, r.rawIn, l.$); - if (!(result instanceof Disjoint)) - continue; - for (const entry of result) { - if (!entry.kind || entry.optional) - continue; - let lSerialized; - let rSerialized; - if (entry.kind === "domain") { - const lValue = entry.l; - const rValue = entry.r; - lSerialized = `"${typeof lValue === "string" ? lValue : lValue.domain}"`; - rSerialized = `"${typeof rValue === "string" ? rValue : rValue.domain}"`; - } else if (entry.kind === "unit") { - lSerialized = entry.l.serializedValue; - rSerialized = entry.r.serializedValue; - } else - continue; - const matching = candidates.find((d) => arrayEquals(d.path, entry.path) && d.kind === entry.kind); - if (!matching) { - candidates.push({ - kind: entry.kind, - cases: { - [lSerialized]: { - branchIndices: [lIndex], - condition: entry.l - }, - [rSerialized]: { - branchIndices: [rIndex], - condition: entry.r - } - }, - path: entry.path - }); - } else { - if (matching.cases[lSerialized]) { - matching.cases[lSerialized].branchIndices = appendUnique(matching.cases[lSerialized].branchIndices, lIndex); - } else { - matching.cases[lSerialized] ??= { - branchIndices: [lIndex], - condition: entry.l - }; - } - if (matching.cases[rSerialized]) { - matching.cases[rSerialized].branchIndices = appendUnique(matching.cases[rSerialized].branchIndices, rIndex); - } else { - matching.cases[rSerialized] ??= { - branchIndices: [rIndex], - condition: entry.r - }; - } - } - } - } - } - const viableCandidates = this.ordered ? viableOrderedCandidates(candidates, this.branches) : candidates; - if (!viableCandidates.length) - return null; - const ctx = createCaseResolutionContext(viableCandidates, this); - const cases = {}; - for (const k in ctx.best.cases) { - const resolution = resolveCase(ctx, k); - if (resolution === null) { - cases[k] = true; - continue; - } - if (resolution.length === this.branches.length) - return null; - if (this.ordered) { - resolution.sort((l, r) => l.originalIndex - r.originalIndex); - } - const branches = resolution.map((entry) => entry.branch); - const caseNode = branches.length === 1 ? branches[0] : this.$.node("union", this.ordered ? { branches, ordered: true } : branches); - Object.assign(this.referencesById, caseNode.referencesById); - cases[k] = caseNode; - } - if (ctx.defaultEntries.length) { - const branches = ctx.defaultEntries.map((entry) => entry.branch); - cases.default = this.$.node("union", this.ordered ? { branches, ordered: true } : branches, { - prereduced: true - }); - Object.assign(this.referencesById, cases.default.referencesById); - } - return Object.assign(ctx.location, { - cases - }); - } -}; -var createCaseResolutionContext = (viableCandidates, node2) => { - const ordered = viableCandidates.sort((l, r) => l.path.length === r.path.length ? Object.keys(r.cases).length - Object.keys(l.cases).length : l.path.length - r.path.length); - const best = ordered[0]; - const location = { - kind: best.kind, - path: best.path, - optionallyChainedPropString: optionallyChainPropString(best.path) - }; - const defaultEntries = node2.branches.map((branch, originalIndex) => ({ - originalIndex, - branch - })); - return { - best, - location, - defaultEntries, - node: node2 - }; -}; -var resolveCase = (ctx, key) => { - const caseCtx = ctx.best.cases[key]; - const discriminantNode = discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$); - let resolvedEntries = []; - const nextDefaults = []; - for (let i = 0; i < ctx.defaultEntries.length; i++) { - const entry = ctx.defaultEntries[i]; - if (caseCtx.branchIndices.includes(entry.originalIndex)) { - const pruned = pruneDiscriminant(ctx.node.branches[entry.originalIndex], ctx.location); - if (pruned === null) { - resolvedEntries = null; - } else { - resolvedEntries?.push({ - originalIndex: entry.originalIndex, - branch: pruned - }); - } - } else if ( - // we shouldn't need a special case for alias to avoid the below - // once alias resolution issues are improved: - // https://github.com/arktypeio/arktype/issues/1026 - entry.branch.hasKind("alias") && discriminantNode.hasKind("domain") && discriminantNode.domain === "object" - ) - resolvedEntries?.push(entry); - else { - if (entry.branch.rawIn.overlaps(discriminantNode)) { - const overlapping = pruneDiscriminant(entry.branch, ctx.location); - resolvedEntries?.push({ - originalIndex: entry.originalIndex, - branch: overlapping - }); - } - nextDefaults.push(entry); - } - } - ctx.defaultEntries = nextDefaults; - return resolvedEntries; -}; -var viableOrderedCandidates = (candidates, originalBranches) => { - const viableCandidates = candidates.filter((candidate) => { - const caseGroups = Object.values(candidate.cases).map((caseCtx) => caseCtx.branchIndices); - for (let i = 0; i < caseGroups.length - 1; i++) { - const currentGroup = caseGroups[i]; - for (let j = i + 1; j < caseGroups.length; j++) { - const nextGroup = caseGroups[j]; - for (const currentIndex of currentGroup) { - for (const nextIndex of nextGroup) { - if (currentIndex > nextIndex) { - if (originalBranches[currentIndex].overlaps(originalBranches[nextIndex])) { - return false; - } - } - } - } - } - } - return true; - }); - return viableCandidates; -}; -var discriminantCaseToNode = (caseDiscriminant, path3, $2) => { - let node2 = caseDiscriminant === "undefined" ? $2.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $2.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $2.units([true, false]) : caseDiscriminant; - for (let i = path3.length - 1; i >= 0; i--) { - const key = path3[i]; - node2 = $2.node("intersection", typeof key === "number" ? { - proto: "Array", - // create unknown for preceding elements (could be optimized with safe imports) - sequence: [...range(key).map((_) => ({})), node2] - } : { - domain: "object", - required: [{ key, value: node2 }] - }); - } - return node2; -}; -var optionallyChainPropString = (path3) => path3.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data"); -var serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions2); -var serializedPrintable = registeredReference(printable2); -var Union = { - implementation: implementation17, - Node: UnionNode -}; -var discriminantToJson = (discriminant) => ({ - kind: discriminant.kind, - path: discriminant.path.map((k) => typeof k === "string" ? k : compileSerializedValue(k)), - cases: flatMorph2(discriminant.cases, (k, node2) => [ - k, - node2 === true ? node2 : node2.hasKind("union") && node2.discriminantJson ? node2.discriminantJson : node2.json - ]) -}); -var describeExpressionOptions = { - delimiter: " | ", - finalDelimiter: " | " -}; -var expressBranches = (expressions) => describeBranches(expressions, describeExpressionOptions); -var describeBranches = (descriptions, opts) => { - const delimiter = opts?.delimiter ?? ", "; - const finalDelimiter = opts?.finalDelimiter ?? " or "; - if (descriptions.length === 0) - return "never"; - if (descriptions.length === 1) - return descriptions[0]; - if (descriptions.length === 2 && descriptions[0] === "false" && descriptions[1] === "true" || descriptions[0] === "true" && descriptions[1] === "false") - return "boolean"; - const seen = {}; - const unique = descriptions.filter((s) => seen[s] ? false : seen[s] = true); - const last = unique.pop(); - return `${unique.join(delimiter)}${unique.length ? finalDelimiter : ""}${last}`; -}; -var intersectBranches = (l, r, ctx) => { - const batchesByR = r.map(() => []); - for (let lIndex = 0; lIndex < l.length; lIndex++) { - let candidatesByR = {}; - for (let rIndex = 0; rIndex < r.length; rIndex++) { - if (batchesByR[rIndex] === null) { - continue; - } - if (l[lIndex].equals(r[rIndex])) { - batchesByR[rIndex] = null; - candidatesByR = {}; - break; - } - const branchIntersection = intersectOrPipeNodes(l[lIndex], r[rIndex], ctx); - if (branchIntersection instanceof Disjoint) { - continue; - } - if (branchIntersection.equals(l[lIndex])) { - batchesByR[rIndex].push(l[lIndex]); - candidatesByR = {}; - break; - } - if (branchIntersection.equals(r[rIndex])) { - batchesByR[rIndex] = null; - } else { - candidatesByR[rIndex] = branchIntersection; - } - } - for (const rIndex in candidatesByR) { - batchesByR[rIndex][lIndex] = candidatesByR[rIndex]; - } - } - const resultBranches = batchesByR.flatMap( - // ensure unions returned from branchable intersections like sequence are flattened - (batch, i) => batch?.flatMap((branch) => branch.branches) ?? r[i] - ); - return resultBranches.length === 0 ? Disjoint.init("union", l, r) : resultBranches; -}; -var reduceBranches = ({ branches, ordered }) => { - if (branches.length < 2) - return branches; - const uniquenessByIndex = branches.map(() => true); - for (let i = 0; i < branches.length; i++) { - for (let j = i + 1; j < branches.length && uniquenessByIndex[i] && uniquenessByIndex[j]; j++) { - if (branches[i].equals(branches[j])) { - uniquenessByIndex[j] = false; - continue; - } - const intersection = intersectNodesRoot(branches[i].rawIn, branches[j].rawIn, branches[0].$); - if (intersection instanceof Disjoint) - continue; - if (!ordered) - assertDeterminateOverlap(branches[i], branches[j]); - if (intersection.equals(branches[i].rawIn)) { - uniquenessByIndex[i] = !!ordered; - } else if (intersection.equals(branches[j].rawIn)) - uniquenessByIndex[j] = false; - } - } - return branches.filter((_, i) => uniquenessByIndex[i]); -}; -var assertDeterminateOverlap = (l, r) => { - if (!l.includesTransform && !r.includesTransform) - return; - if (!arrayEquals(l.shallowMorphs, r.shallowMorphs)) { - throwParseError2(writeIndiscriminableMorphMessage(l.expression, r.expression)); - } - if (!arrayEquals(l.flatMorphs, r.flatMorphs, { - isEqual: (l2, r2) => l2.propString === r2.propString && (l2.node.hasKind("morph") && r2.node.hasKind("morph") ? l2.node.hasEqualMorphs(r2.node) : l2.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l2.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) - })) { - throwParseError2(writeIndiscriminableMorphMessage(l.expression, r.expression)); - } -}; -var pruneDiscriminant = (discriminantBranch, discriminantCtx) => discriminantBranch.transform((nodeKind, inner) => { - if (nodeKind === "domain" || nodeKind === "unit") - return null; - return inner; -}, { - shouldTransform: (node2, ctx) => { - const propString = optionallyChainPropString(ctx.path); - if (!discriminantCtx.optionallyChainedPropString.startsWith(propString)) - return false; - if (node2.hasKind("domain") && node2.domain === "object") - return true; - if ((node2.hasKind("domain") || discriminantCtx.kind === "unit") && propString === discriminantCtx.optionallyChainedPropString) - return true; - return node2.children.length !== 0 && node2.kind !== "index"; - } -}); -var writeIndiscriminableMorphMessage = (lDescription, rDescription) => `An unordered union of a type including a morph and a type with overlapping input is indeterminate: -Left: ${lDescription} -Right: ${rDescription}`; -var writeOrderedIntersectionMessage = (lDescription, rDescription) => `The intersection of two ordered unions is indeterminate: -Left: ${lDescription} -Right: ${rDescription}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/unit.js -var implementation18 = implementNode({ - kind: "unit", - hasAssociatedError: true, - keys: { - unit: { - preserveUndefined: true, - serialize: (schema2) => schema2 instanceof Date ? schema2.toISOString() : defaultValueSerializer(schema2) - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => printable2(node2.unit), - problem: ({ expected, actual }) => `${expected === actual ? `must be reference equal to ${expected} (serialized to the same value)` : `must be ${expected} (was ${actual})`}` - }, - intersections: { - unit: (l, r) => Disjoint.init("unit", l, r), - ...defineRightwardIntersections("unit", (l, r) => { - if (r.allows(l.unit)) - return l; - const rBasis = r.hasKind("intersection") ? r.basis : r; - if (rBasis) { - const rDomain = rBasis.hasKind("domain") ? rBasis : $ark.intrinsic.object; - if (l.domain !== rDomain.domain) { - const lDomainDisjointValue = l.domain === "undefined" || l.domain === "null" || l.domain === "boolean" ? l.domain : $ark.intrinsic[l.domain]; - return Disjoint.init("domain", lDomainDisjointValue, rDomain); - } - } - return Disjoint.init("assignability", l, r.hasKind("intersection") ? r.children.find((rConstraint) => !rConstraint.allows(l.unit)) : r); - }) - } -}); -var UnitNode = class extends InternalBasis { - compiledValue = this.json.unit; - serializedValue = typeof this.unit === "string" || this.unit instanceof Date ? JSON.stringify(this.compiledValue) : `${this.compiledValue}`; - compiledCondition = compileEqualityCheck(this.unit, this.serializedValue); - compiledNegation = compileEqualityCheck(this.unit, this.serializedValue, "negated"); - expression = printable2(this.unit); - domain = domainOf2(this.unit); - get defaultShortDescription() { - return this.domain === "object" ? domainDescriptions2.object : this.description; - } - innerToJsonSchema(ctx) { - return ( - // this is the more standard JSON schema representation, especially for Open API - this.unit === null ? { type: "null" } : $ark.intrinsic.jsonPrimitive.allows(this.unit) ? { const: this.unit } : ctx.fallback.unit({ code: "unit", base: {}, unit: this.unit }) - ); - } - traverseAllows = this.unit instanceof Date ? (data) => data instanceof Date && data.toISOString() === this.compiledValue : Number.isNaN(this.unit) ? (data) => Number.isNaN(data) : (data) => data === this.unit; -}; -var Unit = { - implementation: implementation18, - Node: UnitNode -}; -var compileEqualityCheck = (unit, serializedValue, negated) => { - if (unit instanceof Date) { - const condition = `data instanceof Date && data.toISOString() === ${serializedValue}`; - return negated ? `!(${condition})` : condition; - } - if (Number.isNaN(unit)) - return `${negated ? "!" : ""}Number.isNaN(data)`; - return `data ${negated ? "!" : "="}== ${serializedValue}`; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/index.js -var implementation19 = implementNode({ - kind: "index", - hasAssociatedError: false, - intersectionIsOpen: true, - keys: { - signature: { - child: true, - parse: (schema2, ctx) => { - const key = ctx.$.parseSchema(schema2); - if (!key.extends($ark.intrinsic.key)) { - return throwParseError2(writeInvalidPropertyKeyMessage(key.expression)); - } - const enumerableBranches = key.branches.filter((b) => b.hasKind("unit")); - if (enumerableBranches.length) { - return throwParseError2(writeEnumerableIndexBranches(enumerableBranches.map((b) => printable2(b.unit)))); - } - return key; - } - }, - value: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => `[${node2.signature.expression}]: ${node2.value.description}` - }, - intersections: { - index: (l, r, ctx) => { - if (l.signature.equals(r.signature)) { - const valueIntersection = intersectOrPipeNodes(l.value, r.value, ctx); - const value2 = valueIntersection instanceof Disjoint ? $ark.intrinsic.never.internal : valueIntersection; - return ctx.$.node("index", { signature: l.signature, value: value2 }); - } - if (l.signature.extends(r.signature) && l.value.subsumes(r.value)) - return r; - if (r.signature.extends(l.signature) && r.value.subsumes(l.value)) - return l; - return null; - } - } -}); -var IndexNode = class extends BaseConstraint { - impliedBasis = $ark.intrinsic.object.internal; - expression = `[${this.signature.expression}]: ${this.value.expression}`; - flatRefs = append2(this.value.flatRefs.map((ref) => flatRef([this.signature, ...ref.path], ref.node)), flatRef([this.signature], this.value)); - traverseAllows = (data, ctx) => stringAndSymbolicEntriesOf2(data).every((entry) => { - if (this.signature.traverseAllows(entry[0], ctx)) { - return traverseKey(entry[0], () => this.value.traverseAllows(entry[1], ctx), ctx); - } - return true; - }); - traverseApply = (data, ctx) => { - for (const entry of stringAndSymbolicEntriesOf2(data)) { - if (this.signature.traverseAllows(entry[0], ctx)) { - traverseKey(entry[0], () => this.value.traverseApply(entry[1], ctx), ctx); - } - } - }; - _transform(mapper, ctx) { - ctx.path.push(this.signature); - const result = super._transform(mapper, ctx); - ctx.path.pop(); - return result; - } - compile() { - } -}; -var Index = { - implementation: implementation19, - Node: IndexNode -}; -var writeEnumerableIndexBranches = (keys) => `Index keys ${keys.join(", ")} should be specified as named props.`; -var writeInvalidPropertyKeyMessage = (indexSchema) => `Indexed key definition '${indexSchema}' must be a string or symbol`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/required.js -var implementation20 = implementNode({ - kind: "required", - hasAssociatedError: true, - intersectionIsOpen: true, - keys: { - key: {}, - value: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => `${node2.compiledKey}: ${node2.value.description}`, - expected: (ctx) => ctx.missingValueDescription, - actual: () => "missing" - }, - intersections: { - required: intersectProps, - optional: intersectProps - } -}); -var RequiredNode = class extends BaseProp { - expression = `${this.compiledKey}: ${this.value.expression}`; - errorContext = Object.freeze({ - code: "required", - missingValueDescription: this.value.defaultShortDescription, - relativePath: [this.key], - meta: this.meta - }); - compiledErrorContext = compileObjectLiteral(this.errorContext); -}; -var Required = { - implementation: implementation20, - Node: RequiredNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/sequence.js -var implementation21 = implementNode({ - kind: "sequence", - hasAssociatedError: false, - collapsibleKey: "variadic", - keys: { - prefix: { - child: true, - parse: (schema2, ctx) => { - if (schema2.length === 0) - return void 0; - return schema2.map((element) => ctx.$.parseSchema(element)); - } - }, - optionals: { - child: true, - parse: (schema2, ctx) => { - if (schema2.length === 0) - return void 0; - return schema2.map((element) => ctx.$.parseSchema(element)); - } - }, - defaultables: { - child: (defaultables) => defaultables.map((element) => element[0]), - parse: (defaultables, ctx) => { - if (defaultables.length === 0) - return void 0; - return defaultables.map((element) => { - const node2 = ctx.$.parseSchema(element[0]); - assertDefaultValueAssignability(node2, element[1], null); - return [node2, element[1]]; - }); - }, - serialize: (defaults) => defaults.map((element) => [ - element[0].collapsibleJson, - defaultValueSerializer(element[1]) - ]), - reduceIo: (ioKind, inner, defaultables) => { - if (ioKind === "in") { - inner.optionals = defaultables.map((d) => d[0].rawIn); - return; - } - inner.prefix = defaultables.map((d) => d[0].rawOut); - return; - } - }, - variadic: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2, ctx) - }, - minVariadicLength: { - // minVariadicLength is reflected in the id of this node, - // but not its IntersectionNode parent since it is superceded by the minLength - // node it implies - parse: (min) => min === 0 ? void 0 : min - }, - postfix: { - child: true, - parse: (schema2, ctx) => { - if (schema2.length === 0) - return void 0; - return schema2.map((element) => ctx.$.parseSchema(element)); - } - } - }, - normalize: (schema2) => { - if (typeof schema2 === "string") - return { variadic: schema2 }; - if ("variadic" in schema2 || "prefix" in schema2 || "defaultables" in schema2 || "optionals" in schema2 || "postfix" in schema2 || "minVariadicLength" in schema2) { - if (schema2.postfix?.length) { - if (!schema2.variadic) - return throwParseError2(postfixWithoutVariadicMessage); - if (schema2.optionals?.length || schema2.defaultables?.length) - return throwParseError2(postfixAfterOptionalOrDefaultableMessage); - } - if (schema2.minVariadicLength && !schema2.variadic) { - return throwParseError2("minVariadicLength may not be specified without a variadic element"); - } - return schema2; - } - return { variadic: schema2 }; - }, - reduce: (raw, $2) => { - let minVariadicLength = raw.minVariadicLength ?? 0; - const prefix = raw.prefix?.slice() ?? []; - const defaultables = raw.defaultables?.slice() ?? []; - const optionals = raw.optionals?.slice() ?? []; - const postfix = raw.postfix?.slice() ?? []; - if (raw.variadic) { - while (optionals[optionals.length - 1]?.equals(raw.variadic)) - optionals.pop(); - if (optionals.length === 0 && defaultables.length === 0) { - while (prefix[prefix.length - 1]?.equals(raw.variadic)) { - prefix.pop(); - minVariadicLength++; - } - } - while (postfix[0]?.equals(raw.variadic)) { - postfix.shift(); - minVariadicLength++; - } - } else if (optionals.length === 0 && defaultables.length === 0) { - prefix.push(...postfix.splice(0)); - } - if ( - // if any variadic adjacent elements were moved to minVariadicLength - minVariadicLength !== raw.minVariadicLength || // or any postfix elements were moved to prefix - raw.prefix && raw.prefix.length !== prefix.length - ) { - return $2.node("sequence", { - ...raw, - // empty lists will be omitted during parsing - prefix, - defaultables, - optionals, - postfix, - minVariadicLength - }, { prereduced: true }); - } - }, - defaults: { - description: (node2) => { - if (node2.isVariadicOnly) - return `${node2.variadic.nestableExpression}[]`; - const innerDescription = node2.tuple.map((element) => element.kind === "defaultables" ? `${element.node.nestableExpression} = ${printable2(element.default)}` : element.kind === "optionals" ? `${element.node.nestableExpression}?` : element.kind === "variadic" ? `...${element.node.nestableExpression}[]` : element.node.expression).join(", "); - return `[${innerDescription}]`; - } - }, - intersections: { - sequence: (l, r, ctx) => { - const rootState = _intersectSequences({ - l: l.tuple, - r: r.tuple, - disjoint: new Disjoint(), - result: [], - fixedVariants: [], - ctx - }); - const viableBranches = rootState.disjoint.length === 0 ? [rootState, ...rootState.fixedVariants] : rootState.fixedVariants; - return viableBranches.length === 0 ? rootState.disjoint : viableBranches.length === 1 ? ctx.$.node("sequence", sequenceTupleToInner(viableBranches[0].result)) : ctx.$.node("union", viableBranches.map((state) => ({ - proto: Array, - sequence: sequenceTupleToInner(state.result) - }))); - } - // exactLength, minLength, and maxLength don't need to be defined - // here since impliedSiblings guarantees they will be added - // directly to the IntersectionNode parent of the SequenceNode - // they exist on - } -}); -var SequenceNode = class extends BaseConstraint { - impliedBasis = $ark.intrinsic.Array.internal; - tuple = sequenceInnerToTuple(this.inner); - prefixLength = this.prefix?.length ?? 0; - defaultablesLength = this.defaultables?.length ?? 0; - optionalsLength = this.optionals?.length ?? 0; - postfixLength = this.postfix?.length ?? 0; - defaultablesAndOptionals = []; - prevariadic = this.tuple.filter((el) => { - if (el.kind === "defaultables" || el.kind === "optionals") { - this.defaultablesAndOptionals.push(el.node); - return true; - } - return el.kind === "prefix"; - }); - variadicOrPostfix = conflatenate(this.variadic && [this.variadic], this.postfix); - // have to wait until prevariadic and variadicOrPostfix are set to calculate - flatRefs = this.addFlatRefs(); - addFlatRefs() { - appendUniqueFlatRefs(this.flatRefs, this.prevariadic.flatMap((element, i) => append2(element.node.flatRefs.map((ref) => flatRef([`${i}`, ...ref.path], ref.node)), flatRef([`${i}`], element.node)))); - appendUniqueFlatRefs(this.flatRefs, this.variadicOrPostfix.flatMap((element) => ( - // a postfix index can't be directly represented as a type - // key, so we just use the same matcher for variadic - append2(element.flatRefs.map((ref) => flatRef([$ark.intrinsic.nonNegativeIntegerString.internal, ...ref.path], ref.node)), flatRef([$ark.intrinsic.nonNegativeIntegerString.internal], element)) - ))); - return this.flatRefs; - } - isVariadicOnly = this.prevariadic.length + this.postfixLength === 0; - minVariadicLength = this.inner.minVariadicLength ?? 0; - minLength = this.prefixLength + this.minVariadicLength + this.postfixLength; - minLengthNode = this.minLength === 0 ? null : this.$.node("minLength", this.minLength); - maxLength = this.variadic ? null : this.tuple.length; - maxLengthNode = this.maxLength === null ? null : this.$.node("maxLength", this.maxLength); - impliedSiblings = this.minLengthNode ? this.maxLengthNode ? [this.minLengthNode, this.maxLengthNode] : [this.minLengthNode] : this.maxLengthNode ? [this.maxLengthNode] : []; - defaultValueMorphs = getDefaultableMorphs(this); - defaultValueMorphsReference = this.defaultValueMorphs.length ? registeredReference(this.defaultValueMorphs) : void 0; - elementAtIndex(data, index) { - if (index < this.prevariadic.length) - return this.tuple[index]; - const firstPostfixIndex = data.length - this.postfixLength; - if (index >= firstPostfixIndex) - return { kind: "postfix", node: this.postfix[index - firstPostfixIndex] }; - return { - kind: "variadic", - node: this.variadic ?? throwInternalError2(`Unexpected attempt to access index ${index} on ${this}`) - }; - } - // minLength/maxLength should be checked by Intersection before either traversal - traverseAllows = (data, ctx) => { - for (let i = 0; i < data.length; i++) { - if (!this.elementAtIndex(data, i).node.traverseAllows(data[i], ctx)) - return false; - } - return true; - }; - traverseApply = (data, ctx) => { - let i = 0; - for (; i < data.length; i++) { - traverseKey(i, () => this.elementAtIndex(data, i).node.traverseApply(data[i], ctx), ctx); - } - }; - get element() { - return this.cacheGetter("element", this.$.node("union", this.children)); - } - // minLength/maxLength compilation should be handled by Intersection - compile(js) { - if (this.prefix) { - for (const [i, node2] of this.prefix.entries()) - js.traverseKey(`${i}`, `data[${i}]`, node2); - } - for (const [i, node2] of this.defaultablesAndOptionals.entries()) { - const dataIndex = `${i + this.prefixLength}`; - js.if(`${dataIndex} >= data.length`, () => js.traversalKind === "Allows" ? js.return(true) : js.return()); - js.traverseKey(dataIndex, `data[${dataIndex}]`, node2); - } - if (this.variadic) { - if (this.postfix) { - js.const("firstPostfixIndex", `data.length${this.postfix ? `- ${this.postfix.length}` : ""}`); - } - js.for(`i < ${this.postfix ? "firstPostfixIndex" : "data.length"}`, () => js.traverseKey("i", "data[i]", this.variadic), this.prevariadic.length); - if (this.postfix) { - for (const [i, node2] of this.postfix.entries()) { - const keyExpression = `firstPostfixIndex + ${i}`; - js.traverseKey(keyExpression, `data[${keyExpression}]`, node2); - } - } - } - if (js.traversalKind === "Allows") - js.return(true); - } - _transform(mapper, ctx) { - ctx.path.push($ark.intrinsic.nonNegativeIntegerString.internal); - const result = super._transform(mapper, ctx); - ctx.path.pop(); - return result; - } - // this depends on tuple so needs to come after it - expression = this.description; - reduceJsonSchema(schema2, ctx) { - const isDraft07 = ctx.target === "draft-07"; - if (this.prevariadic.length) { - const prefixSchemas = this.prevariadic.map((el) => { - const valueSchema = el.node.toJsonSchemaRecurse(ctx); - if (el.kind === "defaultables") { - const value2 = typeof el.default === "function" ? el.default() : el.default; - valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ - code: "defaultValue", - base: valueSchema, - value: value2 - }); - } - return valueSchema; - }); - if (isDraft07) - schema2.items = prefixSchemas; - else - schema2.prefixItems = prefixSchemas; - } - if (this.minLength) - schema2.minItems = this.minLength; - if (this.variadic) { - const variadicItemSchema = this.variadic.toJsonSchemaRecurse(ctx); - if (isDraft07 && this.prevariadic.length) - schema2.additionalItems = variadicItemSchema; - else - schema2.items = variadicItemSchema; - if (this.maxLength) - schema2.maxItems = this.maxLength; - if (this.postfix) { - const elements = this.postfix.map((el) => el.toJsonSchemaRecurse(ctx)); - schema2 = ctx.fallback.arrayPostfix({ - code: "arrayPostfix", - base: schema2, - elements - }); - } - } else { - if (isDraft07) - schema2.additionalItems = false; - else - schema2.items = false; - delete schema2.maxItems; - } - return schema2; - } -}; -var defaultableMorphsCache = {}; -var getDefaultableMorphs = (node2) => { - if (!node2.defaultables) - return []; - const morphs = []; - let cacheKey = "["; - const lastDefaultableIndex = node2.prefixLength + node2.defaultablesLength - 1; - for (let i = node2.prefixLength; i <= lastDefaultableIndex; i++) { - const [elementNode, defaultValue] = node2.defaultables[i - node2.prefixLength]; - morphs.push(computeDefaultValueMorph(i, elementNode, defaultValue)); - cacheKey += `${i}: ${elementNode.id} = ${defaultValueSerializer(defaultValue)}, `; - } - cacheKey += "]"; - return defaultableMorphsCache[cacheKey] ??= morphs; -}; -var Sequence = { - implementation: implementation21, - Node: SequenceNode -}; -var sequenceInnerToTuple = (inner) => { - const tuple = []; - if (inner.prefix) - for (const node2 of inner.prefix) - tuple.push({ kind: "prefix", node: node2 }); - if (inner.defaultables) { - for (const [node2, defaultValue] of inner.defaultables) - tuple.push({ kind: "defaultables", node: node2, default: defaultValue }); - } - if (inner.optionals) - for (const node2 of inner.optionals) - tuple.push({ kind: "optionals", node: node2 }); - if (inner.variadic) - tuple.push({ kind: "variadic", node: inner.variadic }); - if (inner.postfix) - for (const node2 of inner.postfix) - tuple.push({ kind: "postfix", node: node2 }); - return tuple; -}; -var sequenceTupleToInner = (tuple) => tuple.reduce((result, element) => { - if (element.kind === "variadic") - result.variadic = element.node; - else if (element.kind === "defaultables") { - result.defaultables = append2(result.defaultables, [ - [element.node, element.default] - ]); - } else - result[element.kind] = append2(result[element.kind], element.node); - return result; -}, {}); -var postfixAfterOptionalOrDefaultableMessage = "A postfix required element cannot follow an optional or defaultable element"; -var postfixWithoutVariadicMessage = "A postfix element requires a variadic element"; -var _intersectSequences = (s) => { - const [lHead, ...lTail] = s.l; - const [rHead, ...rTail] = s.r; - if (!lHead || !rHead) - return s; - const lHasPostfix = lTail[lTail.length - 1]?.kind === "postfix"; - const rHasPostfix = rTail[rTail.length - 1]?.kind === "postfix"; - const kind = lHead.kind === "prefix" || rHead.kind === "prefix" ? "prefix" : lHead.kind === "postfix" || rHead.kind === "postfix" ? "postfix" : lHead.kind === "variadic" && rHead.kind === "variadic" ? "variadic" : lHasPostfix || rHasPostfix ? "prefix" : lHead.kind === "defaultables" || rHead.kind === "defaultables" ? "defaultables" : "optionals"; - if (lHead.kind === "prefix" && rHead.kind === "variadic" && rHasPostfix) { - const postfixBranchResult = _intersectSequences({ - ...s, - fixedVariants: [], - r: rTail.map((element) => ({ ...element, kind: "prefix" })) - }); - if (postfixBranchResult.disjoint.length === 0) - s.fixedVariants.push(postfixBranchResult); - } else if (rHead.kind === "prefix" && lHead.kind === "variadic" && lHasPostfix) { - const postfixBranchResult = _intersectSequences({ - ...s, - fixedVariants: [], - l: lTail.map((element) => ({ ...element, kind: "prefix" })) - }); - if (postfixBranchResult.disjoint.length === 0) - s.fixedVariants.push(postfixBranchResult); - } - const result = intersectOrPipeNodes(lHead.node, rHead.node, s.ctx); - if (result instanceof Disjoint) { - if (kind === "prefix" || kind === "postfix") { - s.disjoint.push(...result.withPrefixKey( - // ideally we could handle disjoint paths more precisely here, - // but not trivial to serialize postfix elements as keys - kind === "prefix" ? s.result.length : `-${lTail.length + 1}`, - // both operands must be required for the disjoint to be considered required - elementIsRequired(lHead) && elementIsRequired(rHead) ? "required" : "optional" - )); - s.result = [...s.result, { kind, node: $ark.intrinsic.never.internal }]; - } else if (kind === "optionals" || kind === "defaultables") { - return s; - } else { - return _intersectSequences({ - ...s, - fixedVariants: [], - // if there were any optional elements, there will be no postfix elements - // so this mapping will never occur (which would be illegal otherwise) - l: lTail.map((element) => ({ ...element, kind: "prefix" })), - r: lTail.map((element) => ({ ...element, kind: "prefix" })) - }); - } - } else if (kind === "defaultables") { - if (lHead.kind === "defaultables" && rHead.kind === "defaultables" && lHead.default !== rHead.default) { - throwParseError2(writeDefaultIntersectionMessage(lHead.default, rHead.default)); - } - s.result = [ - ...s.result, - { - kind, - node: result, - default: lHead.kind === "defaultables" ? lHead.default : rHead.kind === "defaultables" ? rHead.default : throwInternalError2(`Unexpected defaultable intersection from ${lHead.kind} and ${rHead.kind} elements.`) - } - ]; - } else - s.result = [...s.result, { kind, node: result }]; - const lRemaining = s.l.length; - const rRemaining = s.r.length; - if (lHead.kind !== "variadic" || lRemaining >= rRemaining && (rHead.kind === "variadic" || rRemaining === 1)) - s.l = lTail; - if (rHead.kind !== "variadic" || rRemaining >= lRemaining && (lHead.kind === "variadic" || lRemaining === 1)) - s.r = rTail; - return _intersectSequences(s); -}; -var elementIsRequired = (el) => el.kind === "prefix" || el.kind === "postfix"; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/structure.js -var createStructuralWriter = (childStringProp) => (node2) => { - if (node2.props.length || node2.index) { - const parts = node2.index?.map((index) => index[childStringProp]) ?? []; - for (const prop of node2.props) - parts.push(prop[childStringProp]); - if (node2.undeclared) - parts.push(`+ (undeclared): ${node2.undeclared}`); - const objectLiteralDescription = `{ ${parts.join(", ")} }`; - return node2.sequence ? `${objectLiteralDescription} & ${node2.sequence.description}` : objectLiteralDescription; - } - return node2.sequence?.description ?? "{}"; -}; -var structuralDescription = createStructuralWriter("description"); -var structuralExpression = createStructuralWriter("expression"); -var intersectPropsAndIndex = (l, r, $2) => { - const kind = l.required ? "required" : "optional"; - if (!r.signature.allows(l.key)) - return null; - const value2 = intersectNodesRoot(l.value, r.value, $2); - if (value2 instanceof Disjoint) { - return kind === "optional" ? $2.node("optional", { - key: l.key, - value: $ark.intrinsic.never.internal - }) : value2.withPrefixKey(l.key, l.kind); - } - return null; -}; -var implementation22 = implementNode({ - kind: "structure", - hasAssociatedError: false, - normalize: (schema2) => schema2, - applyConfig: (schema2, config2) => { - if (!schema2.undeclared && config2.onUndeclaredKey !== "ignore") { - return { - ...schema2, - undeclared: config2.onUndeclaredKey - }; - } - return schema2; - }, - keys: { - required: { - child: true, - parse: constraintKeyParser("required"), - reduceIo: (ioKind, inner, nodes) => { - inner.required = append2(inner.required, nodes.map((node2) => ioKind === "in" ? node2.rawIn : node2.rawOut)); - return; - } - }, - optional: { - child: true, - parse: constraintKeyParser("optional"), - reduceIo: (ioKind, inner, nodes) => { - if (ioKind === "in") { - inner.optional = nodes.map((node2) => node2.rawIn); - return; - } - for (const node2 of nodes) { - inner[node2.outProp.kind] = append2(inner[node2.outProp.kind], node2.outProp.rawOut); - } - } - }, - index: { - child: true, - parse: constraintKeyParser("index") - }, - sequence: { - child: true, - parse: constraintKeyParser("sequence") - }, - undeclared: { - parse: (behavior) => behavior === "ignore" ? void 0 : behavior, - reduceIo: (ioKind, inner, value2) => { - if (value2 === "reject") { - inner.undeclared = "reject"; - return; - } - if (ioKind === "in") - delete inner.undeclared; - else - inner.undeclared = "reject"; - } - } - }, - defaults: { - description: structuralDescription - }, - intersections: { - structure: (l, r, ctx) => { - const lInner = { ...l.inner }; - const rInner = { ...r.inner }; - const disjointResult = new Disjoint(); - if (l.undeclared) { - const lKey = l.keyof(); - for (const k of r.requiredKeys) { - if (!lKey.allows(k)) { - disjointResult.add("presence", $ark.intrinsic.never.internal, r.propsByKey[k].value, { - path: [k] - }); - } - } - if (rInner.optional) - rInner.optional = rInner.optional.filter((n) => lKey.allows(n.key)); - if (rInner.index) { - rInner.index = rInner.index.flatMap((n) => { - if (n.signature.extends(lKey)) - return n; - const indexOverlap = intersectNodesRoot(lKey, n.signature, ctx.$); - if (indexOverlap instanceof Disjoint) - return []; - const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); - if (normalized.required) { - rInner.required = conflatenate(rInner.required, normalized.required); - } - if (normalized.optional) { - rInner.optional = conflatenate(rInner.optional, normalized.optional); - } - return normalized.index ?? []; - }); - } - } - if (r.undeclared) { - const rKey = r.keyof(); - for (const k of l.requiredKeys) { - if (!rKey.allows(k)) { - disjointResult.add("presence", l.propsByKey[k].value, $ark.intrinsic.never.internal, { - path: [k] - }); - } - } - if (lInner.optional) - lInner.optional = lInner.optional.filter((n) => rKey.allows(n.key)); - if (lInner.index) { - lInner.index = lInner.index.flatMap((n) => { - if (n.signature.extends(rKey)) - return n; - const indexOverlap = intersectNodesRoot(rKey, n.signature, ctx.$); - if (indexOverlap instanceof Disjoint) - return []; - const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); - if (normalized.required) { - lInner.required = conflatenate(lInner.required, normalized.required); - } - if (normalized.optional) { - lInner.optional = conflatenate(lInner.optional, normalized.optional); - } - return normalized.index ?? []; - }); - } - } - const baseInner = {}; - if (l.undeclared || r.undeclared) { - baseInner.undeclared = l.undeclared === "reject" || r.undeclared === "reject" ? "reject" : "delete"; - } - const childIntersectionResult = intersectConstraints({ - kind: "structure", - baseInner, - l: flattenConstraints(lInner), - r: flattenConstraints(rInner), - roots: [], - ctx - }); - if (childIntersectionResult instanceof Disjoint) - disjointResult.push(...childIntersectionResult); - if (disjointResult.length) - return disjointResult; - return childIntersectionResult; - } - }, - reduce: (inner, $2) => { - if (!inner.required && !inner.optional) - return; - const seen = {}; - let updated = false; - const newOptionalProps = inner.optional ? [...inner.optional] : []; - if (inner.required) { - for (let i = 0; i < inner.required.length; i++) { - const requiredProp = inner.required[i]; - if (requiredProp.key in seen) - throwParseError2(writeDuplicateKeyMessage(requiredProp.key)); - seen[requiredProp.key] = true; - if (inner.index) { - for (const index of inner.index) { - const intersection = intersectPropsAndIndex(requiredProp, index, $2); - if (intersection instanceof Disjoint) - return intersection; - } - } - } - } - if (inner.optional) { - for (let i = 0; i < inner.optional.length; i++) { - const optionalProp = inner.optional[i]; - if (optionalProp.key in seen) - throwParseError2(writeDuplicateKeyMessage(optionalProp.key)); - seen[optionalProp.key] = true; - if (inner.index) { - for (const index of inner.index) { - const intersection = intersectPropsAndIndex(optionalProp, index, $2); - if (intersection instanceof Disjoint) - return intersection; - if (intersection !== null) { - newOptionalProps[i] = intersection; - updated = true; - } - } - } - } - } - if (updated) { - return $2.node("structure", { ...inner, optional: newOptionalProps }, { prereduced: true }); - } - } -}); -var StructureNode = class extends BaseConstraint { - impliedBasis = $ark.intrinsic.object.internal; - impliedSiblings = this.children.flatMap((n) => n.impliedSiblings ?? []); - props = conflatenate(this.required, this.optional); - propsByKey = flatMorph2(this.props, (i, node2) => [node2.key, node2]); - propsByKeyReference = registeredReference(this.propsByKey); - expression = structuralExpression(this); - requiredKeys = this.required?.map((node2) => node2.key) ?? []; - optionalKeys = this.optional?.map((node2) => node2.key) ?? []; - literalKeys = [...this.requiredKeys, ...this.optionalKeys]; - _keyof; - keyof() { - if (this._keyof) - return this._keyof; - let branches = this.$.units(this.literalKeys).branches; - if (this.index) { - for (const { signature } of this.index) - branches = branches.concat(signature.branches); - } - return this._keyof = this.$.node("union", branches); - } - map(flatMapProp) { - return this.$.node("structure", this.props.flatMap(flatMapProp).reduce((structureInner, mapped) => { - const originalProp = this.propsByKey[mapped.key]; - if (isNode(mapped)) { - if (mapped.kind !== "required" && mapped.kind !== "optional") { - return throwParseError2(`Map result must have kind "required" or "optional" (was ${mapped.kind})`); - } - structureInner[mapped.kind] = append2(structureInner[mapped.kind], mapped); - return structureInner; - } - const mappedKind = mapped.kind ?? originalProp?.kind ?? "required"; - const mappedPropInner = flatMorph2(mapped, (k, v) => k in Optional.implementation.keys ? [k, v] : []); - structureInner[mappedKind] = append2(structureInner[mappedKind], this.$.node(mappedKind, mappedPropInner)); - return structureInner; - }, {})); - } - assertHasKeys(keys) { - const invalidKeys = keys.filter((k) => !typeOrTermExtends(k, this.keyof())); - if (invalidKeys.length) { - return throwParseError2(writeInvalidKeysMessage(this.expression, invalidKeys)); - } - } - get(indexer, ...path3) { - let value2; - let required2 = false; - const key = indexerToKey(indexer); - if ((typeof key === "string" || typeof key === "symbol") && this.propsByKey[key]) { - value2 = this.propsByKey[key].value; - required2 = this.propsByKey[key].required; - } - if (this.index) { - for (const n of this.index) { - if (typeOrTermExtends(key, n.signature)) - value2 = value2?.and(n.value) ?? n.value; - } - } - if (this.sequence && typeOrTermExtends(key, $ark.intrinsic.nonNegativeIntegerString)) { - if (hasArkKind(key, "root")) { - if (this.sequence.variadic) - value2 = value2?.and(this.sequence.element) ?? this.sequence.element; - } else { - const index = Number.parseInt(key); - if (index < this.sequence.prevariadic.length) { - const fixedElement = this.sequence.prevariadic[index].node; - value2 = value2?.and(fixedElement) ?? fixedElement; - required2 ||= index < this.sequence.prefixLength; - } else if (this.sequence.variadic) { - const nonFixedElement = this.$.node("union", this.sequence.variadicOrPostfix); - value2 = value2?.and(nonFixedElement) ?? nonFixedElement; - } - } - } - if (!value2) { - if (this.sequence?.variadic && hasArkKind(key, "root") && key.extends($ark.intrinsic.number)) { - return throwParseError2(writeNumberIndexMessage(key.expression, this.sequence.expression)); - } - return throwParseError2(writeInvalidKeysMessage(this.expression, [key])); - } - const result = value2.get(...path3); - return required2 ? result : result.or($ark.intrinsic.undefined); - } - pick(...keys) { - this.assertHasKeys(keys); - return this.$.node("structure", this.filterKeys("pick", keys)); - } - omit(...keys) { - this.assertHasKeys(keys); - return this.$.node("structure", this.filterKeys("omit", keys)); - } - optionalize() { - const { required: required2, ...inner } = this.inner; - return this.$.node("structure", { - ...inner, - optional: this.props.map((prop) => prop.hasKind("required") ? this.$.node("optional", prop.inner) : prop) - }); - } - require() { - const { optional, ...inner } = this.inner; - return this.$.node("structure", { - ...inner, - required: this.props.map((prop) => prop.hasKind("optional") ? { - key: prop.key, - value: prop.value - } : prop) - }); - } - merge(r) { - const inner = this.filterKeys("omit", [r.keyof()]); - if (r.required) - inner.required = append2(inner.required, r.required); - if (r.optional) - inner.optional = append2(inner.optional, r.optional); - if (r.index) - inner.index = append2(inner.index, r.index); - if (r.sequence) - inner.sequence = r.sequence; - if (r.undeclared) - inner.undeclared = r.undeclared; - else - delete inner.undeclared; - return this.$.node("structure", inner); - } - filterKeys(operation, keys) { - const result = makeRootAndArrayPropertiesMutable(this.inner); - const shouldKeep = (key) => { - const matchesKey = keys.some((k) => typeOrTermExtends(key, k)); - return operation === "pick" ? matchesKey : !matchesKey; - }; - if (result.required) - result.required = result.required.filter((prop) => shouldKeep(prop.key)); - if (result.optional) - result.optional = result.optional.filter((prop) => shouldKeep(prop.key)); - if (result.index) - result.index = result.index.filter((index) => shouldKeep(index.signature)); - return result; - } - traverseAllows = (data, ctx) => this._traverse("Allows", data, ctx); - traverseApply = (data, ctx) => this._traverse("Apply", data, ctx); - _traverse = (traversalKind, data, ctx) => { - const errorCount = ctx?.currentErrorCount ?? 0; - for (let i = 0; i < this.props.length; i++) { - if (traversalKind === "Allows") { - if (!this.props[i].traverseAllows(data, ctx)) - return false; - } else { - this.props[i].traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return false; - } - } - if (this.sequence) { - if (traversalKind === "Allows") { - if (!this.sequence.traverseAllows(data, ctx)) - return false; - } else { - this.sequence.traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return false; - } - } - if (this.index || this.undeclared === "reject") { - const keys = Object.keys(data); - keys.push(...Object.getOwnPropertySymbols(data)); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (this.index) { - for (const node2 of this.index) { - if (node2.signature.traverseAllows(k, ctx)) { - if (traversalKind === "Allows") { - const result = traverseKey(k, () => node2.value.traverseAllows(data[k], ctx), ctx); - if (!result) - return false; - } else { - traverseKey(k, () => node2.value.traverseApply(data[k], ctx), ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return false; - } - } - } - } - if (this.undeclared === "reject" && !this.declaresKey(k)) { - if (traversalKind === "Allows") - return false; - ctx.errorFromNodeContext({ - code: "predicate", - expected: "removed", - actual: "", - relativePath: [k], - meta: this.meta - }); - if (ctx.failFast) - return false; - } - } - } - if (this.structuralMorph && ctx && !ctx.hasError()) - ctx.queueMorphs([this.structuralMorph]); - return true; - }; - get defaultable() { - return this.cacheGetter("defaultable", this.optional?.filter((o) => o.hasDefault()) ?? []); - } - declaresKey = (k) => k in this.propsByKey || this.index?.some((n) => n.signature.allows(k)) || this.sequence !== void 0 && $ark.intrinsic.nonNegativeIntegerString.allows(k); - _compileDeclaresKey(js) { - const parts = []; - if (this.props.length) - parts.push(`k in ${this.propsByKeyReference}`); - if (this.index) { - for (const index of this.index) - parts.push(js.invoke(index.signature, { kind: "Allows", arg: "k" })); - } - if (this.sequence) - parts.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"); - return parts.join(" || ") || "false"; - } - get structuralMorph() { - return this.cacheGetter("structuralMorph", getPossibleMorph(this)); - } - structuralMorphRef = this.structuralMorph && registeredReference(this.structuralMorph); - compile(js) { - if (js.traversalKind === "Apply") - js.initializeErrorCount(); - for (const prop of this.props) { - js.check(prop); - if (js.traversalKind === "Apply") - js.returnIfFailFast(); - } - if (this.sequence) { - js.check(this.sequence); - if (js.traversalKind === "Apply") - js.returnIfFailFast(); - } - if (this.index || this.undeclared === "reject") { - js.const("keys", "Object.keys(data)"); - js.line("keys.push(...Object.getOwnPropertySymbols(data))"); - js.for("i < keys.length", () => this.compileExhaustiveEntry(js)); - } - if (js.traversalKind === "Allows") - return js.return(true); - if (this.structuralMorphRef) { - js.if("ctx && !ctx.hasError()", () => { - js.line(`ctx.queueMorphs([`); - precompileMorphs(js, this); - return js.line("])"); - }); - } - } - compileExhaustiveEntry(js) { - js.const("k", "keys[i]"); - if (this.index) { - for (const node2 of this.index) { - js.if(`${js.invoke(node2.signature, { arg: "k", kind: "Allows" })}`, () => js.traverseKey("k", "data[k]", node2.value)); - } - } - if (this.undeclared === "reject") { - js.if(`!(${this._compileDeclaresKey(js)})`, () => { - if (js.traversalKind === "Allows") - return js.return(false); - return js.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast", () => js.return()); - }); - } - return js; - } - reduceJsonSchema(schema2, ctx) { - switch (schema2.type) { - case "object": - return this.reduceObjectJsonSchema(schema2, ctx); - case "array": - const arraySchema = this.sequence?.reduceJsonSchema(schema2, ctx) ?? schema2; - if (this.props.length || this.index) { - return ctx.fallback.arrayObject({ - code: "arrayObject", - base: arraySchema, - object: this.reduceObjectJsonSchema({ type: "object" }, ctx) - }); - } - return arraySchema; - default: - return ToJsonSchema.throwInternalOperandError("structure", schema2); - } - } - reduceObjectJsonSchema(schema2, ctx) { - if (this.props.length) { - schema2.properties = {}; - for (const prop of this.props) { - const valueSchema = prop.value.toJsonSchemaRecurse(ctx); - if (typeof prop.key === "symbol") { - ctx.fallback.symbolKey({ - code: "symbolKey", - base: schema2, - key: prop.key, - value: valueSchema, - optional: prop.optional - }); - continue; - } - if (prop.hasDefault()) { - const value2 = typeof prop.default === "function" ? prop.default() : prop.default; - valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ - code: "defaultValue", - base: valueSchema, - value: value2 - }); - } - schema2.properties[prop.key] = valueSchema; - } - if (this.requiredKeys.length && schema2.properties) { - schema2.required = this.requiredKeys.filter((k) => typeof k === "string" && k in schema2.properties); - } - } - if (this.index) { - for (const index of this.index) { - const valueJsonSchema = index.value.toJsonSchemaRecurse(ctx); - if (index.signature.equals($ark.intrinsic.string)) { - schema2.additionalProperties = valueJsonSchema; - continue; - } - for (const keyBranch of index.signature.branches) { - if (!keyBranch.extends($ark.intrinsic.string)) { - schema2 = ctx.fallback.symbolKey({ - code: "symbolKey", - base: schema2, - key: null, - value: valueJsonSchema, - optional: false - }); - continue; - } - let keySchema = { type: "string" }; - if (keyBranch.hasKind("morph")) { - keySchema = ctx.fallback.morph({ - code: "morph", - base: keyBranch.rawIn.toJsonSchemaRecurse(ctx), - out: keyBranch.rawOut.toJsonSchemaRecurse(ctx) - }); - } - if (!keyBranch.hasKind("intersection")) { - return throwInternalError2(`Unexpected index branch kind ${keyBranch.kind}.`); - } - const { pattern } = keyBranch.inner; - if (pattern) { - const keySchemaWithPattern = Object.assign(keySchema, { - pattern: pattern[0].rule - }); - for (let i = 1; i < pattern.length; i++) { - keySchema = ctx.fallback.patternIntersection({ - code: "patternIntersection", - base: keySchemaWithPattern, - pattern: pattern[i].rule - }); - } - schema2.patternProperties ??= {}; - schema2.patternProperties[keySchemaWithPattern.pattern] = valueJsonSchema; - } - } - } - } - if (this.undeclared && !schema2.additionalProperties) - schema2.additionalProperties = false; - return schema2; - } -}; -var defaultableMorphsCache2 = {}; -var constructStructuralMorphCacheKey = (node2) => { - let cacheKey = ""; - for (let i = 0; i < node2.defaultable.length; i++) - cacheKey += node2.defaultable[i].defaultValueMorphRef; - if (node2.sequence?.defaultValueMorphsReference) - cacheKey += node2.sequence?.defaultValueMorphsReference; - if (node2.undeclared === "delete") { - cacheKey += "delete !("; - if (node2.required) - for (const n of node2.required) - cacheKey += n.compiledKey + " | "; - if (node2.optional) - for (const n of node2.optional) - cacheKey += n.compiledKey + " | "; - if (node2.index) - for (const index of node2.index) - cacheKey += index.signature.id + " | "; - if (node2.sequence) { - if (node2.sequence.maxLength === null) - cacheKey += intrinsic.nonNegativeIntegerString.id; - else { - for (let i = 0; i < node2.sequence.tuple.length; i++) - cacheKey += i + " | "; - } - } - cacheKey += ")"; - } - return cacheKey; -}; -var getPossibleMorph = (node2) => { - const cacheKey = constructStructuralMorphCacheKey(node2); - if (!cacheKey) - return void 0; - if (defaultableMorphsCache2[cacheKey]) - return defaultableMorphsCache2[cacheKey]; - const $arkStructuralMorph = (data, ctx) => { - for (let i = 0; i < node2.defaultable.length; i++) { - if (!(node2.defaultable[i].key in data)) - node2.defaultable[i].defaultValueMorph(data, ctx); - } - if (node2.sequence?.defaultables) { - for (let i = data.length - node2.sequence.prefixLength; i < node2.sequence.defaultables.length; i++) - node2.sequence.defaultValueMorphs[i](data, ctx); - } - if (node2.undeclared === "delete") { - for (const k in data) - if (!node2.declaresKey(k)) - delete data[k]; - } - return data; - }; - return defaultableMorphsCache2[cacheKey] = $arkStructuralMorph; -}; -var precompileMorphs = (js, node2) => { - const requiresContext = node2.defaultable.some((node3) => node3.defaultValueMorph.length === 2) || node2.sequence?.defaultValueMorphs.some((morph) => morph.length === 2); - const args3 = `(data${requiresContext ? ", ctx" : ""})`; - return js.block(`${args3} => `, (js2) => { - for (let i = 0; i < node2.defaultable.length; i++) { - const { serializedKey, defaultValueMorphRef } = node2.defaultable[i]; - js2.if(`!(${serializedKey} in data)`, (js3) => js3.line(`${defaultValueMorphRef}${args3}`)); - } - if (node2.sequence?.defaultables) { - js2.for(`i < ${node2.sequence.defaultables.length}`, (js3) => js3.set(`data[i]`, 5), `data.length - ${node2.sequence.prefixLength}`); - } - if (node2.undeclared === "delete") { - js2.forIn("data", (js3) => js3.if(`!(${node2._compileDeclaresKey(js3)})`, (js4) => js4.line(`delete data[k]`))); - } - return js2.return("data"); - }); -}; -var Structure = { - implementation: implementation22, - Node: StructureNode -}; -var indexerToKey = (indexable) => { - if (hasArkKind(indexable, "root") && indexable.hasKind("unit")) - indexable = indexable.unit; - if (typeof indexable === "number") - indexable = `${indexable}`; - return indexable; -}; -var writeNumberIndexMessage = (indexExpression, sequenceExpression) => `${indexExpression} is not allowed as an array index on ${sequenceExpression}. Use the 'nonNegativeIntegerString' keyword instead.`; -var normalizeIndex = (signature, value2, $2) => { - const [enumerableBranches, nonEnumerableBranches] = spliterate(signature.branches, (k) => k.hasKind("unit")); - if (!enumerableBranches.length) - return { index: $2.node("index", { signature, value: value2 }) }; - const normalized = {}; - for (const n of enumerableBranches) { - const prop = $2.node("required", { key: n.unit, value: value2 }); - normalized[prop.kind] = append2(normalized[prop.kind], prop); - } - if (nonEnumerableBranches.length) { - normalized.index = $2.node("index", { - signature: nonEnumerableBranches, - value: value2 - }); - } - return normalized; -}; -var typeKeyToString = (k) => hasArkKind(k, "root") ? k.expression : printable2(k); -var writeInvalidKeysMessage = (o, keys) => `Key${keys.length === 1 ? "" : "s"} ${keys.map(typeKeyToString).join(", ")} ${keys.length === 1 ? "does" : "do"} not exist on ${o}`; -var writeDuplicateKeyMessage = (key) => `Duplicate key ${compileSerializedValue(key)}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/kinds.js -var nodeImplementationsByKind = { - ...boundImplementationsByKind, - alias: Alias.implementation, - domain: Domain.implementation, - unit: Unit.implementation, - proto: Proto.implementation, - union: Union.implementation, - morph: Morph.implementation, - intersection: Intersection.implementation, - divisor: Divisor.implementation, - pattern: Pattern.implementation, - predicate: Predicate.implementation, - required: Required.implementation, - optional: Optional.implementation, - index: Index.implementation, - sequence: Sequence.implementation, - structure: Structure.implementation -}; -$ark.defaultConfig = withAlphabetizedKeys(Object.assign(flatMorph2(nodeImplementationsByKind, (kind, implementation23) => [ - kind, - implementation23.defaults -]), { - jitless: envHasCsp2(), - clone: deepClone, - onUndeclaredKey: "ignore", - exactOptionalPropertyTypes: true, - numberAllowsNaN: false, - dateAllowsInvalid: false, - onFail: null, - keywords: {}, - toJsonSchema: ToJsonSchema.defaultConfig -})); -$ark.resolvedConfig = mergeConfigs($ark.defaultConfig, $ark.config); -var nodeClassesByKind = { - ...boundClassesByKind, - alias: Alias.Node, - domain: Domain.Node, - unit: Unit.Node, - proto: Proto.Node, - union: Union.Node, - morph: Morph.Node, - intersection: Intersection.Node, - divisor: Divisor.Node, - pattern: Pattern.Node, - predicate: Predicate.Node, - required: Required.Node, - optional: Optional.Node, - index: Index.Node, - sequence: Sequence.Node, - structure: Structure.Node -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/module.js -var RootModule = class extends DynamicBase { - // ensure `[arkKind]` is non-enumerable so it doesn't get spread on import/export - get [arkKind]() { - return "module"; - } -}; -var bindModule = (module, $2) => new RootModule(flatMorph2(module, (alias, value2) => [ - alias, - hasArkKind(value2, "module") ? bindModule(value2, $2) : $2.bindReference(value2) -])); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/scope.js -var schemaBranchesOf = (schema2) => isArray(schema2) ? schema2 : "branches" in schema2 && isArray(schema2.branches) ? schema2.branches : void 0; -var throwMismatchedNodeRootError = (expected, actual) => throwParseError2(`Node of kind ${actual} is not valid as a ${expected} definition`); -var writeDuplicateAliasError = (alias) => `#${alias} duplicates public alias ${alias}`; -var scopesByName = {}; -$ark.ambient ??= {}; -var rawUnknownUnion; -var rootScopeFnName = "function $"; -var precompile = (references) => bindPrecompilation(references, precompileReferences(references)); -var bindPrecompilation = (references, precompiler) => { - const precompilation = precompiler.write(rootScopeFnName, 4); - const compiledTraversals = precompiler.compile()(); - for (const node2 of references) { - if (node2.precompilation) { - continue; - } - node2.traverseAllows = compiledTraversals[`${node2.id}Allows`].bind(compiledTraversals); - if (node2.isRoot() && !node2.allowsRequiresContext) { - node2.allows = node2.traverseAllows; - } - node2.traverseApply = compiledTraversals[`${node2.id}Apply`].bind(compiledTraversals); - if (compiledTraversals[`${node2.id}Optimistic`]) { - ; - node2.traverseOptimistic = compiledTraversals[`${node2.id}Optimistic`].bind(compiledTraversals); - } - node2.precompilation = precompilation; - } -}; -var precompileReferences = (references) => new CompiledFunction().return(references.reduce((js, node2) => { - const allowsCompiler = new NodeCompiler({ kind: "Allows" }).indent(); - node2.compile(allowsCompiler); - const allowsJs = allowsCompiler.write(`${node2.id}Allows`); - const applyCompiler = new NodeCompiler({ kind: "Apply" }).indent(); - node2.compile(applyCompiler); - const applyJs = applyCompiler.write(`${node2.id}Apply`); - const result = `${js}${allowsJs}, -${applyJs}, -`; - if (!node2.hasKind("union")) - return result; - const optimisticCompiler = new NodeCompiler({ - kind: "Allows", - optimistic: true - }).indent(); - node2.compile(optimisticCompiler); - const optimisticJs = optimisticCompiler.write(`${node2.id}Optimistic`); - return `${result}${optimisticJs}, -`; -}, "{\n") + "}"); -var BaseScope = class { - config; - resolvedConfig; - name; - get [arkKind]() { - return "scope"; - } - referencesById = {}; - references = []; - resolutions = {}; - exportedNames = []; - aliases = {}; - resolved = false; - nodesByHash = {}; - intrinsic; - constructor(def, config2) { - this.config = mergeConfigs($ark.config, config2); - this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config2); - this.name = this.resolvedConfig.name ?? `anonymousScope${Object.keys(scopesByName).length}`; - if (this.name in scopesByName) - throwParseError2(`A Scope already named ${this.name} already exists`); - scopesByName[this.name] = this; - const aliasEntries = Object.entries(def).map((entry) => this.preparseOwnAliasEntry(...entry)); - for (const [k, v] of aliasEntries) { - let name = k; - if (k[0] === "#") { - name = k.slice(1); - if (name in this.aliases) - throwParseError2(writeDuplicateAliasError(name)); - this.aliases[name] = v; - } else { - if (name in this.aliases) - throwParseError2(writeDuplicateAliasError(k)); - this.aliases[name] = v; - this.exportedNames.push(name); - } - if (!hasArkKind(v, "module") && !hasArkKind(v, "generic") && !isThunk(v)) { - const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name }); - this.resolutions[name] = hasArkKind(preparsed, "root") ? this.bindReference(preparsed) : this.createParseContext(preparsed).id; - } - } - rawUnknownUnion ??= this.node("union", { - branches: [ - "string", - "number", - "object", - "bigint", - "symbol", - { unit: true }, - { unit: false }, - { unit: void 0 }, - { unit: null } - ] - }, { prereduced: true }); - this.nodesByHash[rawUnknownUnion.hash] = this.node("intersection", {}, { prereduced: true }); - this.intrinsic = $ark.intrinsic ? flatMorph2($ark.intrinsic, (k, v) => ( - // don't include cyclic aliases from JSON scope - k.startsWith("json") ? [] : [k, this.bindReference(v)] - )) : {}; - } - cacheGetter(name, value2) { - Object.defineProperty(this, name, { value: value2 }); - return value2; - } - get internal() { - return this; - } - // json is populated when the scope is exported, so ensure it is populated - // before allowing external access - _json; - get json() { - if (!this._json) - this.export(); - return this._json; - } - defineSchema(def) { - return def; - } - generic = (...params) => { - const $2 = this; - return (def, possibleHkt) => new GenericRoot(params, possibleHkt ? new LazyGenericBody(def) : def, $2, $2, possibleHkt ?? null); - }; - units = (values, opts) => { - const uniqueValues = []; - for (const value2 of values) - if (!uniqueValues.includes(value2)) - uniqueValues.push(value2); - const branches = uniqueValues.map((unit) => this.node("unit", { unit }, opts)); - return this.node("union", branches, { - ...opts, - prereduced: true - }); - }; - lazyResolutions = []; - lazilyResolve(resolve, syntheticAlias) { - const node2 = this.node("alias", { - reference: syntheticAlias ?? "synthetic", - resolve - }, { prereduced: true }); - if (!this.resolved) - this.lazyResolutions.push(node2); - return node2; - } - schema = (schema2, opts) => this.finalize(this.parseSchema(schema2, opts)); - parseSchema = (schema2, opts) => this.node(schemaKindOf(schema2), schema2, opts); - preparseNode(kinds, schema2, opts) { - let kind = typeof kinds === "string" ? kinds : schemaKindOf(schema2, kinds); - if (isNode(schema2) && schema2.kind === kind) - return schema2; - if (kind === "alias" && !opts?.prereduced) { - const { reference: reference2 } = Alias.implementation.normalize(schema2, this); - if (reference2.startsWith("$")) { - const resolution = this.resolveRoot(reference2.slice(1)); - schema2 = resolution; - kind = resolution.kind; - } - } else if (kind === "union" && hasDomain2(schema2, "object")) { - const branches = schemaBranchesOf(schema2); - if (branches?.length === 1) { - schema2 = branches[0]; - kind = schemaKindOf(schema2); - } - } - if (isNode(schema2) && schema2.kind === kind) - return schema2; - const impl = nodeImplementationsByKind[kind]; - const normalizedSchema = impl.normalize?.(schema2, this) ?? schema2; - if (isNode(normalizedSchema)) { - return normalizedSchema.kind === kind ? normalizedSchema : throwMismatchedNodeRootError(kind, normalizedSchema.kind); - } - return { - ...opts, - $: this, - kind, - def: normalizedSchema, - prefix: opts.alias ?? kind - }; - } - bindReference(reference2) { - let bound; - if (isNode(reference2)) { - bound = reference2.$ === this ? reference2 : new reference2.constructor(reference2.attachments, this); - } else { - bound = reference2.$ === this ? reference2 : new GenericRoot(reference2.params, reference2.bodyDef, reference2.$, this, reference2.hkt); - } - if (!this.resolved) { - Object.assign(this.referencesById, bound.referencesById); - } - return bound; - } - resolveRoot(name) { - return this.maybeResolveRoot(name) ?? throwParseError2(writeUnresolvableMessage(name)); - } - maybeResolveRoot(name) { - const result = this.maybeResolve(name); - if (hasArkKind(result, "generic")) - return; - return result; - } - /** If name is a valid reference to a submodule alias, return its resolution */ - maybeResolveSubalias(name) { - return maybeResolveSubalias(this.aliases, name) ?? maybeResolveSubalias(this.ambient, name); - } - get ambient() { - return $ark.ambient; - } - maybeResolve(name) { - const cached4 = this.resolutions[name]; - if (cached4) { - if (typeof cached4 !== "string") - return this.bindReference(cached4); - const v = nodesByRegisteredId[cached4]; - if (hasArkKind(v, "root")) - return this.resolutions[name] = v; - if (hasArkKind(v, "context")) { - if (v.phase === "resolving") { - return this.node("alias", { reference: `$${name}` }, { prereduced: true }); - } - if (v.phase === "resolved") { - return throwInternalError2(`Unexpected resolved context for was uncached by its scope: ${printable2(v)}`); - } - v.phase = "resolving"; - const node2 = this.bindReference(this.parseOwnDefinitionFormat(v.def, v)); - v.phase = "resolved"; - nodesByRegisteredId[node2.id] = node2; - nodesByRegisteredId[v.id] = node2; - return this.resolutions[name] = node2; - } - return throwInternalError2(`Unexpected nodesById entry for ${cached4}: ${printable2(v)}`); - } - let def = this.aliases[name] ?? this.ambient?.[name]; - if (!def) - return this.maybeResolveSubalias(name); - def = this.normalizeRootScopeValue(def); - if (hasArkKind(def, "generic")) - return this.resolutions[name] = this.bindReference(def); - if (hasArkKind(def, "module")) { - if (!def.root) - throwParseError2(writeMissingSubmoduleAccessMessage(name)); - return this.resolutions[name] = this.bindReference(def.root); - } - return this.resolutions[name] = this.parse(def, { - alias: name - }); - } - createParseContext(input) { - const id = input.id ?? registerNodeId(input.prefix); - return nodesByRegisteredId[id] = Object.assign(input, { - [arkKind]: "context", - $: this, - id, - phase: "unresolved" - }); - } - traversal(root2) { - return new Traversal(root2, this.resolvedConfig); - } - import(...names) { - return new RootModule(flatMorph2(this.export(...names), (alias, value2) => [ - `#${alias}`, - value2 - ])); - } - precompilation; - _exportedResolutions; - _exports; - export(...names) { - if (!this._exports) { - this._exports = {}; - for (const name of this.exportedNames) { - const def = this.aliases[name]; - this._exports[name] = hasArkKind(def, "module") ? bindModule(def, this) : bootstrapAliasReferences(this.maybeResolve(name)); - } - for (const node2 of this.lazyResolutions) - node2.resolution; - this._exportedResolutions = resolutionsOfModule(this, this._exports); - this._json = resolutionsToJson(this._exportedResolutions); - Object.assign(this.resolutions, this._exportedResolutions); - this.references = Object.values(this.referencesById); - if (!this.resolvedConfig.jitless) { - const precompiler = precompileReferences(this.references); - this.precompilation = precompiler.write(rootScopeFnName, 4); - bindPrecompilation(this.references, precompiler); - } - this.resolved = true; - } - const namesToExport = names.length ? names : this.exportedNames; - return new RootModule(flatMorph2(namesToExport, (_, name) => [ - name, - this._exports[name] - ])); - } - resolve(name) { - return this.export()[name]; - } - node = (kinds, nodeSchema, opts = {}) => { - const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts); - if (isNode(ctxOrNode)) - return this.bindReference(ctxOrNode); - const ctx = this.createParseContext(ctxOrNode); - const node2 = parseNode(ctx); - const bound = this.bindReference(node2); - return nodesByRegisteredId[ctx.id] = bound; - }; - parse = (def, opts = {}) => this.finalize(this.parseDefinition(def, opts)); - parseDefinition(def, opts = {}) { - if (hasArkKind(def, "root")) - return this.bindReference(def); - const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts); - if (hasArkKind(ctxInputOrNode, "root")) - return this.bindReference(ctxInputOrNode); - const ctx = this.createParseContext(ctxInputOrNode); - nodesByRegisteredId[ctx.id] = ctx; - let node2 = this.bindReference(this.parseOwnDefinitionFormat(def, ctx)); - if (node2.isCyclic) - node2 = withId(node2, ctx.id); - nodesByRegisteredId[ctx.id] = node2; - return node2; - } - finalize(node2) { - bootstrapAliasReferences(node2); - if (!node2.precompilation && !this.resolvedConfig.jitless) - precompile(node2.references); - return node2; - } -}; -var SchemaScope = class extends BaseScope { - parseOwnDefinitionFormat(def, ctx) { - return parseNode(ctx); - } - preparseOwnDefinitionFormat(schema2, opts) { - return this.preparseNode(schemaKindOf(schema2), schema2, opts); - } - preparseOwnAliasEntry(k, v) { - return [k, v]; - } - normalizeRootScopeValue(v) { - return v; - } -}; -var bootstrapAliasReferences = (resolution) => { - const aliases = resolution.references.filter((node2) => node2.hasKind("alias")); - for (const aliasNode of aliases) { - Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById); - for (const ref of resolution.references) { - if (aliasNode.id in ref.referencesById) - Object.assign(ref.referencesById, aliasNode.referencesById); - } - } - return resolution; -}; -var resolutionsToJson = (resolutions) => flatMorph2(resolutions, (k, v) => [ - k, - hasArkKind(v, "root") || hasArkKind(v, "generic") ? v.json : hasArkKind(v, "module") ? resolutionsToJson(v) : throwInternalError2(`Unexpected resolution ${printable2(v)}`) -]); -var maybeResolveSubalias = (base, name) => { - const dotIndex = name.indexOf("."); - if (dotIndex === -1) - return; - const dotPrefix = name.slice(0, dotIndex); - const prefixSchema = base[dotPrefix]; - if (prefixSchema === void 0) - return; - if (!hasArkKind(prefixSchema, "module")) - return throwParseError2(writeNonSubmoduleDotMessage(dotPrefix)); - const subalias = name.slice(dotIndex + 1); - const resolution = prefixSchema[subalias]; - if (resolution === void 0) - return maybeResolveSubalias(prefixSchema, subalias); - if (hasArkKind(resolution, "root") || hasArkKind(resolution, "generic")) - return resolution; - if (hasArkKind(resolution, "module")) { - return resolution.root ?? throwParseError2(writeMissingSubmoduleAccessMessage(name)); - } - throwInternalError2(`Unexpected resolution for alias '${name}': ${printable2(resolution)}`); -}; -var schemaScope = (aliases, config2) => new SchemaScope(aliases, config2); -var rootSchemaScope = new SchemaScope({}); -var resolutionsOfModule = ($2, typeSet) => { - const result = {}; - for (const k in typeSet) { - const v = typeSet[k]; - if (hasArkKind(v, "module")) { - const innerResolutions = resolutionsOfModule($2, v); - const prefixedResolutions = flatMorph2(innerResolutions, (innerK, innerV) => [`${k}.${innerK}`, innerV]); - Object.assign(result, prefixedResolutions); - } else if (hasArkKind(v, "root") || hasArkKind(v, "generic")) - result[k] = v; - else - throwInternalError2(`Unexpected scope resolution ${printable2(v)}`); - } - return result; -}; -var writeUnresolvableMessage = (token) => `'${token}' is unresolvable`; -var writeNonSubmoduleDotMessage = (name) => `'${name}' must reference a module to be accessed using dot syntax`; -var writeMissingSubmoduleAccessMessage = (name) => `Reference to submodule '${name}' must specify an alias`; -rootSchemaScope.export(); -var rootSchema = rootSchemaScope.schema; -var node = rootSchemaScope.node; -var defineSchema = rootSchemaScope.defineSchema; -var genericNode = rootSchemaScope.generic; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/shared.js -var arrayIndexSource = `^(?:0|[1-9]\\d*)$`; -var arrayIndexMatcher = new RegExp(arrayIndexSource); -var arrayIndexMatcherReference = registeredReference(arrayIndexMatcher); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/intrinsic.js -var intrinsicBases = schemaScope({ - bigint: "bigint", - // since we know this won't be reduced, it can be safely cast to a union - boolean: [{ unit: false }, { unit: true }], - false: { unit: false }, - never: [], - null: { unit: null }, - number: "number", - object: "object", - string: "string", - symbol: "symbol", - true: { unit: true }, - unknown: {}, - undefined: { unit: void 0 }, - Array, - Date -}, { prereducedAliases: true }).export(); -$ark.intrinsic = { ...intrinsicBases }; -var intrinsicRoots = schemaScope({ - integer: { - domain: "number", - divisor: 1 - }, - lengthBoundable: ["string", Array], - key: ["string", "symbol"], - nonNegativeIntegerString: { domain: "string", pattern: arrayIndexSource } -}, { prereducedAliases: true }).export(); -Object.assign($ark.intrinsic, intrinsicRoots); -var intrinsicJson = schemaScope({ - jsonPrimitive: [ - "string", - "number", - { unit: true }, - { unit: false }, - { unit: null } - ], - jsonObject: { - domain: "object", - index: { - signature: "string", - value: "$jsonData" - } - }, - jsonData: ["$jsonPrimitive", "$jsonObject"] -}, { prereducedAliases: true }).export(); -var intrinsic = { - ...intrinsicBases, - ...intrinsicRoots, - ...intrinsicJson, - emptyStructure: node("structure", {}, { prereduced: true }) -}; -$ark.intrinsic = { ...intrinsic }; - -// node_modules/.pnpm/arkregex@0.0.4/node_modules/arkregex/out/regex.js -var regex = ((src, flags) => new RegExp(src, flags)); -Object.assign(regex, { as: regex }); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/config.js -var configure = configureSchema; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/date.js -var isDateLiteral = (value2) => typeof value2 === "string" && value2[0] === "d" && (value2[1] === "'" || value2[1] === '"') && value2[value2.length - 1] === value2[1]; -var isValidDate = (d) => d.toString() !== "Invalid Date"; -var extractDateLiteralSource = (literal) => literal.slice(2, -1); -var writeInvalidDateMessage = (source) => `'${source}' could not be parsed by the Date constructor`; -var tryParseDate = (source, errorOnFail) => maybeParseDate(source, errorOnFail); -var maybeParseDate = (source, errorOnFail) => { - const stringParsedDate = new Date(source); - if (isValidDate(stringParsedDate)) - return stringParsedDate; - const epochMillis = tryParseNumber(source); - if (epochMillis !== void 0) { - const numberParsedDate = new Date(epochMillis); - if (isValidDate(numberParsedDate)) - return numberParsedDate; - } - return errorOnFail ? throwParseError2(errorOnFail === true ? writeInvalidDateMessage(source) : errorOnFail) : void 0; -}; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/enclosed.js -var regexExecArray = rootSchema({ - proto: "Array", - sequence: "string", - required: { - key: "groups", - value: ["object", { unit: void 0 }] - } -}); -var parseEnclosed = (s, enclosing) => { - const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]); - if (s.scanner.lookahead === "") - return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing)); - s.scanner.shift(); - if (enclosing in enclosingRegexTokens) { - let regex3; - try { - regex3 = new RegExp(enclosed); - } catch (e) { - throwParseError2(String(e)); - } - s.root = s.ctx.$.node("intersection", { - domain: "string", - pattern: enclosed - }, { prereduced: true }); - if (enclosing === "x/") { - s.root = s.ctx.$.node("morph", { - in: s.root, - morphs: (s2) => regex3.exec(s2), - declaredOut: regexExecArray - }); - } - } else if (isKeyOf2(enclosing, enclosingQuote)) - s.root = s.ctx.$.node("unit", { unit: enclosed }); - else { - const date2 = tryParseDate(enclosed, writeInvalidDateMessage(enclosed)); - s.root = s.ctx.$.node("unit", { meta: enclosed, unit: date2 }); - } -}; -var enclosingQuote = { - "'": 1, - '"': 1 -}; -var enclosingChar = { - "/": 1, - "'": 1, - '"': 1 -}; -var enclosingLiteralTokens = { - "d'": "'", - 'd"': '"', - "'": "'", - '"': '"' -}; -var enclosingRegexTokens = { - "/": "/", - "x/": "/" -}; -var enclosingTokens = { - ...enclosingLiteralTokens, - ...enclosingRegexTokens -}; -var untilLookaheadIsClosing = { - "'": (scanner) => scanner.lookahead === `'`, - '"': (scanner) => scanner.lookahead === `"`, - "/": (scanner) => scanner.lookahead === `/` -}; -var enclosingCharDescriptions = { - '"': "double-quote", - "'": "single-quote", - "/": "forward slash" -}; -var writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/ast/validate.js -var writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`; -var shallowOptionalMessage = "Optional definitions like 'string?' are only valid as properties in an object or tuple"; -var shallowDefaultableMessage = "Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple"; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/tokens.js -var terminatingChars = { - "<": 1, - ">": 1, - "=": 1, - "|": 1, - "&": 1, - ")": 1, - "[": 1, - "%": 1, - ",": 1, - ":": 1, - "?": 1, - "#": 1, - ...whitespaceChars2 -}; -var lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ? unscanned[0] === "=" ? ( - // >== would only occur in an expression like Array==5 - // otherwise, >= would only occur as part of a bound like number>=5 - unscanned[1] === "=" -) : unscanned.trimStart() === "" || isKeyOf2(unscanned.trimStart()[0], terminatingChars) : lookahead === "=" ? unscanned[0] !== "=" : lookahead === "," || lookahead === "?"; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/genericArgs.js -var parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []); -var _parseGenericArgs = (name, g, s, argNodes) => { - const argState = s.parseUntilFinalizer(); - argNodes.push(argState.root); - if (argState.finalizer === ">") { - if (argNodes.length !== g.params.length) { - return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map((arg) => arg.expression))); - } - return argNodes; - } - if (argState.finalizer === ",") - return _parseGenericArgs(name, g, s, argNodes); - return argState.error(writeUnclosedGroupMessage(">")); -}; -var writeInvalidGenericArgCountMessage = (name, params, argDefs) => `${name}<${params.join(", ")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? "" : `: ${argDefs.join(", ")}`})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/unenclosed.js -var parseUnenclosed = (s) => { - const token = s.scanner.shiftUntilLookahead(terminatingChars); - if (token === "keyof") - s.addPrefix("keyof"); - else - s.root = unenclosedToNode(s, token); -}; -var parseGenericInstantiation = (name, g, s) => { - s.scanner.shiftUntilNonWhitespace(); - const lookahead = s.scanner.shift(); - if (lookahead !== "<") - return s.error(writeInvalidGenericArgCountMessage(name, g.names, [])); - const parsedArgs = parseGenericArgs(name, g, s); - return g(...parsedArgs); -}; -var unenclosedToNode = (s, token) => maybeParseReference(s, token) ?? maybeParseUnenclosedLiteral(s, token) ?? s.error(token === "" ? s.scanner.lookahead === "#" ? writePrefixedPrivateReferenceMessage(s.shiftedBy(1).scanner.shiftUntilLookahead(terminatingChars)) : writeMissingOperandMessage(s) : writeUnresolvableMessage(token)); -var maybeParseReference = (s, token) => { - if (s.ctx.args?.[token]) { - const arg = s.ctx.args[token]; - if (typeof arg !== "string") - return arg; - return s.ctx.$.node("alias", { reference: arg }, { prereduced: true }); - } - const resolution = s.ctx.$.maybeResolve(token); - if (hasArkKind(resolution, "root")) - return resolution; - if (resolution === void 0) - return; - if (hasArkKind(resolution, "generic")) - return parseGenericInstantiation(token, resolution, s); - return throwParseError2(`Unexpected resolution ${printable2(resolution)}`); -}; -var maybeParseUnenclosedLiteral = (s, token) => { - const maybeNumber = tryParseWellFormedNumber(token); - if (maybeNumber !== void 0) - return s.ctx.$.node("unit", { unit: maybeNumber }); - const maybeBigint = tryParseWellFormedBigint(token); - if (maybeBigint !== void 0) - return s.ctx.$.node("unit", { unit: maybeBigint }); -}; -var writeMissingOperandMessage = (s) => { - const operator = s.previousOperator(); - return operator ? writeMissingRightOperandMessage(operator, s.scanner.unscanned) : writeExpressionExpectedMessage(s.scanner.unscanned); -}; -var writeMissingRightOperandMessage = (token, unscanned = "") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : ""}`; -var writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : ""}`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operand/operand.js -var parseOperand = (s) => s.scanner.lookahead === "" ? s.error(writeMissingOperandMessage(s)) : s.scanner.lookahead === "(" ? s.shiftedBy(1).reduceGroupOpen() : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift()) : s.scanner.lookaheadIsIn(whitespaceChars2) ? parseOperand(s.shiftedBy(1)) : s.scanner.lookahead === "d" ? s.scanner.nextLookahead in enclosingQuote ? parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`) : parseUnenclosed(s) : s.scanner.lookahead === "x" ? s.scanner.nextLookahead === "/" ? s.shiftedBy(2) && parseEnclosed(s, "x/") : parseUnenclosed(s) : parseUnenclosed(s); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/reduce/shared.js -var minComparators = { - ">": true, - ">=": true -}; -var maxComparators = { - "<": true, - "<=": true -}; -var invertedComparators = { - "<": ">", - ">": "<", - "<=": ">=", - ">=": "<=", - "==": "==" -}; -var writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`; -var writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`; -var writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/bounds.js -var parseBound = (s, start) => { - const comparator = shiftComparator(s, start); - if (s.root.hasKind("unit")) { - if (typeof s.root.unit === "number") { - s.reduceLeftBound(s.root.unit, comparator); - s.unsetRoot(); - return; - } - if (s.root.unit instanceof Date) { - const literal = `d'${s.root.description ?? s.root.unit.toISOString()}'`; - s.unsetRoot(); - s.reduceLeftBound(literal, comparator); - return; - } - } - return parseRightBound(s, comparator); -}; -var comparatorStartChars = { - "<": 1, - ">": 1, - "=": 1 -}; -var shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}` : start; -var getBoundKinds = (comparator, limit, root2, boundKind) => { - if (root2.extends($ark.intrinsic.number)) { - if (typeof limit !== "number") { - return throwParseError2(writeInvalidLimitMessage(comparator, limit, boundKind)); - } - return comparator === "==" ? ["min", "max"] : comparator[0] === ">" ? ["min"] : ["max"]; - } - if (root2.extends($ark.intrinsic.lengthBoundable)) { - if (typeof limit !== "number") { - return throwParseError2(writeInvalidLimitMessage(comparator, limit, boundKind)); - } - return comparator === "==" ? ["exactLength"] : comparator[0] === ">" ? ["minLength"] : ["maxLength"]; - } - if (root2.extends($ark.intrinsic.Date)) { - return comparator === "==" ? ["after", "before"] : comparator[0] === ">" ? ["after"] : ["before"]; - } - return throwParseError2(writeUnboundableMessage(root2.expression)); -}; -var openLeftBoundToRoot = (leftBound) => ({ - rule: isDateLiteral(leftBound.limit) ? extractDateLiteralSource(leftBound.limit) : leftBound.limit, - exclusive: leftBound.comparator.length === 1 -}); -var parseRightBound = (s, comparator) => { - const previousRoot = s.unsetRoot(); - const previousScannerIndex = s.scanner.location; - s.parseOperand(); - const limitNode = s.unsetRoot(); - const limitToken = s.scanner.sliceChars(previousScannerIndex, s.scanner.location); - s.root = previousRoot; - if (!limitNode.hasKind("unit") || typeof limitNode.unit !== "number" && !(limitNode.unit instanceof Date)) - return s.error(writeInvalidLimitMessage(comparator, limitToken, "right")); - const limit = limitNode.unit; - const exclusive = comparator.length === 1; - const boundKinds = getBoundKinds(comparator, typeof limit === "number" ? limit : limitToken, previousRoot, "right"); - for (const kind of boundKinds) { - s.constrainRoot(kind, comparator === "==" ? { rule: limit } : { rule: limit, exclusive }); - } - if (!s.branches.leftBound) - return; - if (!isKeyOf2(comparator, maxComparators)) - return s.error(writeUnpairableComparatorMessage(comparator)); - const lowerBoundKind = getBoundKinds(s.branches.leftBound.comparator, s.branches.leftBound.limit, previousRoot, "left"); - s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.leftBound)); - s.branches.leftBound = null; -}; -var writeInvalidLimitMessage = (comparator, limit, boundKind) => `Comparator ${boundKind === "left" ? invertedComparators[comparator] : comparator} must be ${boundKind === "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/brand.js -var parseBrand = (s) => { - s.scanner.shiftUntilNonWhitespace(); - const brandName = s.scanner.shiftUntilLookahead(terminatingChars); - s.root = s.root.brand(brandName); -}; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/divisor.js -var parseDivisor = (s) => { - s.scanner.shiftUntilNonWhitespace(); - const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars); - const divisor = tryParseInteger(divisorToken, { - errorOnFail: writeInvalidDivisorMessage(divisorToken) - }); - if (divisor === 0) - s.error(writeInvalidDivisorMessage(0)); - s.root = s.root.constrain("divisor", divisor); -}; -var writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/operator.js -var parseOperator = (s) => { - const lookahead = s.scanner.shift(); - return lookahead === "" ? s.finalize("") : lookahead === "[" ? s.scanner.shift() === "]" ? s.setRoot(s.root.array()) : s.error(incompleteArrayTokenMessage) : lookahead === "|" ? s.scanner.lookahead === ">" ? s.shiftedBy(1).pushRootToBranch("|>") : s.pushRootToBranch(lookahead) : lookahead === "&" ? s.pushRootToBranch(lookahead) : lookahead === ")" ? s.finalizeGroup() : lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ? s.finalize(lookahead) : isKeyOf2(lookahead, comparatorStartChars) ? parseBound(s, lookahead) : lookahead === "%" ? parseDivisor(s) : lookahead === "#" ? parseBrand(s) : lookahead in whitespaceChars2 ? parseOperator(s) : s.error(writeUnexpectedCharacterMessage(lookahead)); -}; -var writeUnexpectedCharacterMessage = (char, shouldBe = "") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`; -var incompleteArrayTokenMessage = `Missing expected ']'`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/shift/operator/default.js -var parseDefault = (s) => { - const baseNode = s.unsetRoot(); - s.parseOperand(); - const defaultNode = s.unsetRoot(); - if (!defaultNode.hasKind("unit")) - return s.error(writeNonLiteralDefaultMessage(defaultNode.expression)); - const defaultValue = defaultNode.unit instanceof Date ? () => new Date(defaultNode.unit) : defaultNode.unit; - return [baseNode, "=", defaultValue]; -}; -var writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/string.js -var parseString = (def, ctx) => { - const aliasResolution = ctx.$.maybeResolveRoot(def); - if (aliasResolution) - return aliasResolution; - if (def.endsWith("[]")) { - const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2)); - if (possibleElementResolution) - return possibleElementResolution.array(); - } - const s = new RuntimeState(new Scanner(def), ctx); - const node2 = fullStringParse(s); - if (s.finalizer === ">") - throwParseError2(writeUnexpectedCharacterMessage(">")); - return node2; -}; -var fullStringParse = (s) => { - s.parseOperand(); - let result = parseUntilFinalizer(s).root; - if (!result) { - return throwInternalError2(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`); - } - if (s.finalizer === "=") - result = parseDefault(s); - else if (s.finalizer === "?") - result = [result, "?"]; - s.scanner.shiftUntilNonWhitespace(); - if (s.scanner.lookahead) { - throwParseError2(writeUnexpectedCharacterMessage(s.scanner.lookahead)); - } - return result; -}; -var parseUntilFinalizer = (s) => { - while (s.finalizer === void 0) - next(s); - return s; -}; -var next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand(); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/reduce/dynamic.js -var RuntimeState = class _RuntimeState { - root; - branches = { - prefixes: [], - leftBound: null, - intersection: null, - union: null, - pipe: null - }; - finalizer; - groups = []; - scanner; - ctx; - constructor(scanner, ctx) { - this.scanner = scanner; - this.ctx = ctx; - } - error(message) { - return throwParseError2(message); - } - hasRoot() { - return this.root !== void 0; - } - setRoot(root2) { - this.root = root2; - } - unsetRoot() { - const value2 = this.root; - this.root = void 0; - return value2; - } - constrainRoot(...args3) { - this.root = this.root.constrain(args3[0], args3[1]); - } - finalize(finalizer) { - if (this.groups.length) - return this.error(writeUnclosedGroupMessage(")")); - this.finalizeBranches(); - this.finalizer = finalizer; - } - reduceLeftBound(limit, comparator) { - const invertedComparator = invertedComparators[comparator]; - if (!isKeyOf2(invertedComparator, minComparators)) - return this.error(writeUnpairableComparatorMessage(comparator)); - if (this.branches.leftBound) { - return this.error(writeMultipleLeftBoundsMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator, limit, invertedComparator)); - } - this.branches.leftBound = { - comparator: invertedComparator, - limit - }; - } - finalizeBranches() { - this.assertRangeUnset(); - if (this.branches.pipe) { - this.pushRootToBranch("|>"); - this.root = this.branches.pipe; - return; - } - if (this.branches.union) { - this.pushRootToBranch("|"); - this.root = this.branches.union; - return; - } - if (this.branches.intersection) { - this.pushRootToBranch("&"); - this.root = this.branches.intersection; - return; - } - this.applyPrefixes(); - } - finalizeGroup() { - this.finalizeBranches(); - const topBranchState = this.groups.pop(); - if (!topBranchState) { - return this.error(writeUnmatchedGroupCloseMessage(")", this.scanner.unscanned)); - } - this.branches = topBranchState; - } - addPrefix(prefix) { - this.branches.prefixes.push(prefix); - } - applyPrefixes() { - while (this.branches.prefixes.length) { - const lastPrefix = this.branches.prefixes.pop(); - this.root = lastPrefix === "keyof" ? this.root.keyof() : throwInternalError2(`Unexpected prefix '${lastPrefix}'`); - } - } - pushRootToBranch(token) { - this.assertRangeUnset(); - this.applyPrefixes(); - const root2 = this.root; - this.root = void 0; - this.branches.intersection = this.branches.intersection?.rawAnd(root2) ?? root2; - if (token === "&") - return; - this.branches.union = this.branches.union?.rawOr(this.branches.intersection) ?? this.branches.intersection; - this.branches.intersection = null; - if (token === "|") - return; - this.branches.pipe = this.branches.pipe?.rawPipeOnce(this.branches.union) ?? this.branches.union; - this.branches.union = null; - } - parseUntilFinalizer() { - return parseUntilFinalizer(new _RuntimeState(this.scanner, this.ctx)); - } - parseOperator() { - return parseOperator(this); - } - parseOperand() { - return parseOperand(this); - } - assertRangeUnset() { - if (this.branches.leftBound) { - return this.error(writeOpenRangeMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator)); - } - } - reduceGroupOpen() { - this.groups.push(this.branches); - this.branches = { - prefixes: [], - leftBound: null, - union: null, - intersection: null, - pipe: null - }; - } - previousOperator() { - return this.branches.leftBound?.comparator ?? this.branches.prefixes[this.branches.prefixes.length - 1] ?? (this.branches.intersection ? "&" : this.branches.union ? "|" : this.branches.pipe ? "|>" : void 0); - } - shiftedBy(count) { - this.scanner.jumpForward(count); - return this; - } -}; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/generic.js -var emptyGenericParameterMessage = "An empty string is not a valid generic parameter name"; -var parseGenericParamName = (scanner, result, ctx) => { - scanner.shiftUntilNonWhitespace(); - const name = scanner.shiftUntilLookahead(terminatingChars); - if (name === "") { - if (scanner.lookahead === "" && result.length) - return result; - return throwParseError2(emptyGenericParameterMessage); - } - scanner.shiftUntilNonWhitespace(); - return _parseOptionalConstraint(scanner, name, result, ctx); -}; -var extendsToken = "extends "; -var _parseOptionalConstraint = (scanner, name, result, ctx) => { - scanner.shiftUntilNonWhitespace(); - if (scanner.unscanned.startsWith(extendsToken)) - scanner.jumpForward(extendsToken.length); - else { - if (scanner.lookahead === ",") - scanner.shift(); - result.push(name); - return parseGenericParamName(scanner, result, ctx); - } - const s = parseUntilFinalizer(new RuntimeState(scanner, ctx)); - result.push([name, s.root]); - return parseGenericParamName(scanner, result, ctx); -}; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/fn.js -var InternalFnParser = class extends Callable { - constructor($2) { - const attach = { - $: $2, - raw: $2.fn - }; - super((...signature) => { - const returnOperatorIndex = signature.indexOf(":"); - const lastParamIndex = returnOperatorIndex === -1 ? signature.length - 1 : returnOperatorIndex - 1; - const paramDefs = signature.slice(0, lastParamIndex + 1); - const paramTuple = $2.parse(paramDefs).assertHasKind("intersection"); - let returnType = $2.intrinsic.unknown; - if (returnOperatorIndex !== -1) { - if (returnOperatorIndex !== signature.length - 2) - return throwParseError2(badFnReturnTypeMessage); - returnType = $2.parse(signature[returnOperatorIndex + 1]); - } - return (impl) => new InternalTypedFn(impl, paramTuple, returnType); - }, { attach }); - } -}; -var InternalTypedFn = class extends Callable { - raw; - params; - returns; - expression; - constructor(raw, params, returns) { - const typedName = `typed ${raw.name}`; - const typed = { - // assign to a key with the expected name to force it to be created that way - [typedName]: (...args3) => { - const validatedArgs = params.assert(args3); - const returned = raw(...validatedArgs); - return returns.assert(returned); - } - }[typedName]; - super(typed); - this.raw = raw; - this.params = params; - this.returns = returns; - let argsExpression = params.expression; - if (argsExpression[0] === "[" && argsExpression[argsExpression.length - 1] === "]") - argsExpression = argsExpression.slice(1, -1); - else if (argsExpression.endsWith("[]")) - argsExpression = `...${argsExpression}`; - this.expression = `(${argsExpression}) => ${returns?.expression ?? "unknown"}`; - } -}; -var badFnReturnTypeMessage = `":" must be followed by exactly one return type e.g: -fn("string", ":", "number")(s => s.length)`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/match.js -var InternalMatchParser = class extends Callable { - $; - constructor($2) { - super((...args3) => new InternalChainedMatchParser($2)(...args3), { - bind: $2 - }); - this.$ = $2; - } - in(def) { - return new InternalChainedMatchParser(this.$, def === void 0 ? void 0 : this.$.parse(def)); - } - at(key, cases) { - return new InternalChainedMatchParser(this.$).at(key, cases); - } - case(when, then) { - return new InternalChainedMatchParser(this.$).case(when, then); - } -}; -var InternalChainedMatchParser = class extends Callable { - $; - in; - key; - branches = []; - constructor($2, In) { - super((cases) => this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.parse(k), v]))); - this.$ = $2; - this.in = In; - } - at(key, cases) { - if (this.key) - throwParseError2(doubleAtMessage); - if (this.branches.length) - throwParseError2(chainedAtMessage); - this.key = key; - return cases ? this.match(cases) : this; - } - case(def, resolver) { - return this.caseEntry(this.$.parse(def), resolver); - } - caseEntry(node2, resolver) { - const wrappableNode = this.key ? this.$.parse({ [this.key]: node2 }) : node2; - const branch = wrappableNode.pipe(resolver); - this.branches.push(branch); - return this; - } - match(cases) { - return this(cases); - } - strings(cases) { - return this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.node("unit", { unit: k }), v])); - } - caseEntries(entries) { - for (let i = 0; i < entries.length; i++) { - const [k, v] = entries[i]; - if (k === "default") { - if (i !== entries.length - 1) { - throwParseError2(`default may only be specified as the last key of a switch definition`); - } - return this.default(v); - } - if (typeof v !== "function") { - return throwParseError2(`Value for case "${k}" must be a function (was ${domainOf2(v)})`); - } - this.caseEntry(k, v); - } - return this; - } - default(defaultCase) { - if (typeof defaultCase === "function") - this.case(intrinsic.unknown, defaultCase); - const schema2 = { - branches: this.branches, - ordered: true - }; - if (defaultCase === "never" || defaultCase === "assert") - schema2.meta = { onFail: throwOnDefault }; - const cases = this.$.node("union", schema2); - if (!this.in) - return this.$.finalize(cases); - let inputValidatedCases = this.in.pipe(cases); - if (defaultCase === "never" || defaultCase === "assert") { - inputValidatedCases = inputValidatedCases.configureReferences({ - onFail: throwOnDefault - }, "self"); - } - return this.$.finalize(inputValidatedCases); - } -}; -var throwOnDefault = (errors) => errors.throw(); -var chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in().at('bar')`; -var doubleAtMessage = `At most one key matcher may be specified per expression`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/property.js -var parseProperty = (def, ctx) => { - if (isArray(def)) { - if (def[1] === "=") - return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "=", def[2]]; - if (def[1] === "?") - return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "?"]; - } - return parseInnerDefinition(def, ctx); -}; -var invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`; -var invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/objectLiteral.js -var parseObjectLiteral = (def, ctx) => { - let spread; - const structure = {}; - const defEntries = stringAndSymbolicEntriesOf2(def); - for (const [k, v] of defEntries) { - const parsedKey = preparseKey(k); - if (parsedKey.kind === "spread") { - if (!isEmptyObject2(structure)) - return throwParseError2(nonLeadingSpreadError); - const operand = ctx.$.parseOwnDefinitionFormat(v, ctx); - if (operand.equals(intrinsic.object)) - continue; - if (!operand.hasKind("intersection") || // still error on attempts to spread proto nodes like ...Date - !operand.basis?.equals(intrinsic.object)) { - return throwParseError2(writeInvalidSpreadTypeMessage(operand.expression)); - } - spread = operand.structure; - continue; - } - if (parsedKey.kind === "undeclared") { - if (v !== "reject" && v !== "delete" && v !== "ignore") - throwParseError2(writeInvalidUndeclaredBehaviorMessage(v)); - structure.undeclared = v; - continue; - } - const parsedValue = parseProperty(v, ctx); - const parsedEntryKey = parsedKey; - if (parsedKey.kind === "required") { - if (!isArray(parsedValue)) { - appendNamedProp(structure, "required", { - key: parsedKey.normalized, - value: parsedValue - }, ctx); - } else { - appendNamedProp(structure, "optional", parsedValue[1] === "=" ? { - key: parsedKey.normalized, - value: parsedValue[0], - default: parsedValue[2] - } : { - key: parsedKey.normalized, - value: parsedValue[0] - }, ctx); - } - continue; - } - if (isArray(parsedValue)) { - if (parsedValue[1] === "?") - throwParseError2(invalidOptionalKeyKindMessage); - if (parsedValue[1] === "=") - throwParseError2(invalidDefaultableKeyKindMessage); - } - if (parsedKey.kind === "optional") { - appendNamedProp(structure, "optional", { - key: parsedKey.normalized, - value: parsedValue - }, ctx); - continue; - } - const signature = ctx.$.parseOwnDefinitionFormat(parsedEntryKey.normalized, ctx); - const normalized = normalizeIndex(signature, parsedValue, ctx.$); - if (normalized.index) - structure.index = append2(structure.index, normalized.index); - if (normalized.required) - structure.required = append2(structure.required, normalized.required); - } - const structureNode = ctx.$.node("structure", structure); - return ctx.$.parseSchema({ - domain: "object", - structure: spread?.merge(structureNode) ?? structureNode - }); -}; -var appendNamedProp = (structure, kind, inner, ctx) => { - structure[kind] = append2( - // doesn't seem like this cast should be necessary - structure[kind], - ctx.$.node(kind, inner) - ); -}; -var writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable2(actual)})`; -var nonLeadingSpreadError = "Spread operator may only be used as the first key in an object"; -var preparseKey = (key) => typeof key === "symbol" ? { kind: "required", normalized: key } : key[key.length - 1] === "?" ? key[key.length - 2] === Backslash2 ? { kind: "required", normalized: `${key.slice(0, -2)}?` } : { - kind: "optional", - normalized: key.slice(0, -1) -} : key[0] === "[" && key[key.length - 1] === "]" ? { kind: "index", normalized: key.slice(1, -1) } : key[0] === Backslash2 && key[1] === "[" && key[key.length - 1] === "]" ? { kind: "required", normalized: key.slice(1) } : key === "..." ? { kind: "spread" } : key === "+" ? { kind: "undeclared" } : { - kind: "required", - normalized: key === "\\..." ? "..." : key === "\\+" ? "+" : key -}; -var writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/tupleExpressions.js -var maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null; -var parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof(); -var parseBranchTuple = (def, ctx) => { - if (def[2] === void 0) - return throwParseError2(writeMissingRightOperandMessage(def[1], "")); - const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx); - const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx); - if (def[1] === "|") - return ctx.$.node("union", { branches: [l, r] }); - const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$); - if (result instanceof Disjoint) - return result.throw(); - return result; -}; -var parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array(); -var parseMorphTuple = (def, ctx) => { - if (typeof def[2] !== "function") { - return throwParseError2(writeMalformedFunctionalExpressionMessage("=>", def[2])); - } - return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]); -}; -var writeMalformedFunctionalExpressionMessage = (operator, value2) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value2})`; -var parseNarrowTuple = (def, ctx) => { - if (typeof def[2] !== "function") { - return throwParseError2(writeMalformedFunctionalExpressionMessage(":", def[2])); - } - return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]); -}; -var parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]); -var defineIndexOneParsers = (parsers) => parsers; -var postfixParsers = defineIndexOneParsers({ - "[]": parseArrayTuple, - "?": () => throwParseError2(shallowOptionalMessage) -}); -var infixParsers = defineIndexOneParsers({ - "|": parseBranchTuple, - "&": parseBranchTuple, - ":": parseNarrowTuple, - "=>": parseMorphTuple, - "|>": parseBranchTuple, - "@": parseMetaTuple, - // since object and tuple literals parse there via `parseProperty`, - // they must be shallow if parsed directly as a tuple expression - "=": () => throwParseError2(shallowDefaultableMessage) -}); -var indexOneParsers = { ...postfixParsers, ...infixParsers }; -var isIndexOneExpression = (def) => indexOneParsers[def[1]] !== void 0; -var defineIndexZeroParsers = (parsers) => parsers; -var indexZeroParsers = defineIndexZeroParsers({ - keyof: parseKeyOfTuple, - instanceof: (def, ctx) => { - if (typeof def[1] !== "function") { - return throwParseError2(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1]))); - } - const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError2(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor)))); - return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches }); - }, - "===": (def, ctx) => ctx.$.units(def.slice(1)) -}); -var isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== void 0; -var writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/tupleLiteral.js -var parseTupleLiteral = (def, ctx) => { - let sequences = [{}]; - let i = 0; - while (i < def.length) { - let spread = false; - if (def[i] === "..." && i < def.length - 1) { - spread = true; - i++; - } - const parsedProperty = parseProperty(def[i], ctx); - const [valueNode, operator, possibleDefaultValue] = !isArray(parsedProperty) ? [parsedProperty] : parsedProperty; - i++; - if (spread) { - if (!valueNode.extends($ark.intrinsic.Array)) - return throwParseError2(writeNonArraySpreadMessage(valueNode.expression)); - sequences = sequences.flatMap((base) => ( - // since appendElement mutates base, we have to shallow-ish clone it for each branch - valueNode.distribute((branch) => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)) - )); - } else { - sequences = sequences.map((base) => { - if (operator === "?") - return appendOptionalElement(base, valueNode); - if (operator === "=") - return appendDefaultableElement(base, valueNode, possibleDefaultValue); - return appendRequiredElement(base, valueNode); - }); - } - } - return ctx.$.parseSchema(sequences.map((sequence) => isEmptyObject2(sequence) ? { - proto: Array, - exactLength: 0 - } : { - proto: Array, - sequence - })); -}; -var appendRequiredElement = (base, element) => { - if (base.defaultables || base.optionals) { - return throwParseError2(base.variadic ? ( - // e.g. [boolean = true, ...string[], number] - postfixAfterOptionalOrDefaultableMessage - ) : requiredPostOptionalMessage); - } - if (base.variadic) { - base.postfix = append2(base.postfix, element); - } else { - base.prefix = append2(base.prefix, element); - } - return base; -}; -var appendOptionalElement = (base, element) => { - if (base.variadic) - return throwParseError2(optionalOrDefaultableAfterVariadicMessage); - base.optionals = append2(base.optionals, element); - return base; -}; -var appendDefaultableElement = (base, element, value2) => { - if (base.variadic) - return throwParseError2(optionalOrDefaultableAfterVariadicMessage); - if (base.optionals) - return throwParseError2(defaultablePostOptionalMessage); - base.defaultables = append2(base.defaultables, [[element, value2]]); - return base; -}; -var appendVariadicElement = (base, element) => { - if (base.postfix) - throwParseError2(multipleVariadicMesage); - if (base.variadic) { - if (!base.variadic.equals(element)) { - throwParseError2(multipleVariadicMesage); - } - } else { - base.variadic = element.internal; - } - return base; -}; -var appendSpreadBranch = (base, branch) => { - const spread = branch.select({ method: "find", kind: "sequence" }); - if (!spread) { - return appendVariadicElement(base, $ark.intrinsic.unknown); - } - if (spread.prefix) - for (const node2 of spread.prefix) - appendRequiredElement(base, node2); - if (spread.optionals) - for (const node2 of spread.optionals) - appendOptionalElement(base, node2); - if (spread.variadic) - appendVariadicElement(base, spread.variadic); - if (spread.postfix) - for (const node2 of spread.postfix) - appendRequiredElement(base, node2); - return base; -}; -var writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`; -var multipleVariadicMesage = "A tuple may have at most one variadic element"; -var requiredPostOptionalMessage = "A required element may not follow an optional element"; -var optionalOrDefaultableAfterVariadicMessage = "An optional element may not follow a variadic element"; -var defaultablePostOptionalMessage = "A defaultable element may not follow an optional element without a default"; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/parser/definition.js -var parseCache = {}; -var parseInnerDefinition = (def, ctx) => { - if (typeof def === "string") { - if (ctx.args && Object.keys(ctx.args).some((k) => def.includes(k))) { - return parseString(def, ctx); - } - const scopeCache = parseCache[ctx.$.name] ??= {}; - return scopeCache[def] ??= parseString(def, ctx); - } - return hasDomain2(def, "object") ? parseObject(def, ctx) : throwParseError2(writeBadDefinitionTypeMessage(domainOf2(def))); -}; -var parseObject = (def, ctx) => { - const objectKind = objectKindOf2(def); - switch (objectKind) { - case void 0: - if (hasArkKind(def, "root")) - return def; - if ("~standard" in def) - return parseStandardSchema(def, ctx); - return parseObjectLiteral(def, ctx); - case "Array": - return parseTuple(def, ctx); - case "RegExp": - return ctx.$.node("intersection", { - domain: "string", - pattern: def - }, { prereduced: true }); - case "Function": { - const resolvedDef = isThunk(def) ? def() : def; - if (hasArkKind(resolvedDef, "root")) - return resolvedDef; - return throwParseError2(writeBadDefinitionTypeMessage("Function")); - } - default: - return throwParseError2(writeBadDefinitionTypeMessage(objectKind ?? printable2(def))); - } -}; -var parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx2) => { - const result = def["~standard"].validate(v); - if (!result.issues) - return result.value; - for (const { message, path: path3 } of result.issues) { - if (path3) { - if (path3.length) { - ctx2.error({ - problem: uncapitalize(message), - relativePath: path3.map((k) => typeof k === "object" ? k.key : k) - }); - } else { - ctx2.error({ - message - }); - } - } else { - ctx2.error({ - message - }); - } - } -}); -var parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx); -var writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/type.js -var InternalTypeParser = class extends Callable { - constructor($2) { - const attach = Object.assign( - { - errors: ArkErrors, - hkt: Hkt, - $: $2, - raw: $2.parse, - module: $2.constructor.module, - scope: $2.constructor.scope, - declare: $2.declare, - define: $2.define, - match: $2.match, - generic: $2.generic, - schema: $2.schema, - // this won't be defined during bootstrapping, but externally always will be - keywords: $2.ambient, - unit: $2.unit, - enumerated: $2.enumerated, - instanceOf: $2.instanceOf, - valueOf: $2.valueOf, - or: $2.or, - and: $2.and, - merge: $2.merge, - pipe: $2.pipe, - fn: $2.fn - }, - // also won't be defined during bootstrapping - $2.ambientAttachments - ); - super((...args3) => { - if (args3.length === 1) { - return $2.parse(args3[0]); - } - if (args3.length === 2 && typeof args3[0] === "string" && args3[0][0] === "<" && args3[0][args3[0].length - 1] === ">") { - const paramString = args3[0].slice(1, -1); - const params = $2.parseGenericParams(paramString, {}); - return new GenericRoot(params, args3[1], $2, $2, null); - } - return $2.parse(args3); - }, { - attach - }); - } -}; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/scope.js -var $arkTypeRegistry = $ark; -var InternalScope = class _InternalScope extends BaseScope { - get ambientAttachments() { - if (!$arkTypeRegistry.typeAttachments) - return; - return this.cacheGetter("ambientAttachments", flatMorph2($arkTypeRegistry.typeAttachments, (k, v) => [ - k, - this.bindReference(v) - ])); - } - preparseOwnAliasEntry(alias, def) { - const firstParamIndex = alias.indexOf("<"); - if (firstParamIndex === -1) { - if (hasArkKind(def, "module") || hasArkKind(def, "generic")) - return [alias, def]; - const qualifiedName = this.name === "ark" ? alias : alias === "root" ? this.name : `${this.name}.${alias}`; - const config2 = this.resolvedConfig.keywords?.[qualifiedName]; - if (config2) - def = [def, "@", config2]; - return [alias, def]; - } - if (alias[alias.length - 1] !== ">") { - throwParseError2(`'>' must be the last character of a generic declaration in a scope`); - } - const name = alias.slice(0, firstParamIndex); - const paramString = alias.slice(firstParamIndex + 1, -1); - return [ - name, - // use a thunk definition for the generic so that we can parse - // constraints within the current scope - () => { - const params = this.parseGenericParams(paramString, { alias: name }); - const generic2 = parseGeneric(params, def, this); - return generic2; - } - ]; - } - parseGenericParams(def, opts) { - return parseGenericParamName(new Scanner(def), [], this.createParseContext({ - ...opts, - def, - prefix: "generic" - })); - } - normalizeRootScopeValue(resolution) { - if (isThunk(resolution) && !hasArkKind(resolution, "generic")) - return resolution(); - return resolution; - } - preparseOwnDefinitionFormat(def, opts) { - return { - ...opts, - def, - prefix: opts.alias ?? "type" - }; - } - parseOwnDefinitionFormat(def, ctx) { - const isScopeAlias = ctx.alias && ctx.alias in this.aliases; - if (!isScopeAlias && !ctx.args) - ctx.args = { this: ctx.id }; - const result = parseInnerDefinition(def, ctx); - if (isArray(result)) { - if (result[1] === "=") - return throwParseError2(shallowDefaultableMessage); - if (result[1] === "?") - return throwParseError2(shallowOptionalMessage); - } - return result; - } - unit = (value2) => this.units([value2]); - valueOf = (tsEnum) => this.units(enumValues(tsEnum)); - enumerated = (...values) => this.units(values); - instanceOf = (ctor) => this.node("proto", { proto: ctor }, { prereduced: true }); - or = (...defs) => this.schema(defs.map((def) => this.parse(def))); - and = (...defs) => defs.reduce((node2, def) => node2.and(this.parse(def)), this.intrinsic.unknown); - merge = (...defs) => defs.reduce((node2, def) => node2.merge(this.parse(def)), this.intrinsic.object); - pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs); - fn = new InternalFnParser(this); - match = new InternalMatchParser(this); - declare = () => ({ - type: this.type - }); - define(def) { - return def; - } - type = new InternalTypeParser(this); - static scope = ((def, config2 = {}) => new _InternalScope(def, config2)); - static module = ((def, config2 = {}) => this.scope(def, config2).export()); -}; -var scope = Object.assign(InternalScope.scope, { - define: (def) => def -}); -var Scope = InternalScope; - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/builtins.js -var MergeHkt = class extends Hkt { - description = 'merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'; -}; -var Merge = genericNode(["base", intrinsic.object], ["props", intrinsic.object])((args3) => args3.base.merge(args3.props), MergeHkt); -var arkBuiltins = Scope.module({ - Key: intrinsic.key, - Merge -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/Array.js -var liftFromHkt = class extends Hkt { -}; -var liftFrom = genericNode("element")((args3) => { - const nonArrayElement = args3.element.exclude(intrinsic.Array); - const lifted = nonArrayElement.array(); - return nonArrayElement.rawOr(lifted).pipe(liftArray).distribute((branch) => branch.assertHasKind("morph").declareOut(lifted), rootSchema); -}, liftFromHkt); -var arkArray = Scope.module({ - root: intrinsic.Array, - readonly: "root", - index: intrinsic.nonNegativeIntegerString, - liftFrom -}, { - name: "Array" -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/FormData.js -var value = rootSchema(["string", registry.FileConstructor]); -var parsedFormDataValue = value.rawOr(value.array()); -var parsed = rootSchema({ - meta: "an object representing parsed form data", - domain: "object", - index: { - signature: "string", - value: parsedFormDataValue - } -}); -var arkFormData = Scope.module({ - root: ["instanceof", FormData], - value, - parsed, - parse: rootSchema({ - in: FormData, - morphs: (data) => { - const result = {}; - for (const [k, v] of data) { - if (k in result) { - const existing = result[k]; - if (typeof existing === "string" || existing instanceof registry.FileConstructor) - result[k] = [existing, v]; - else - existing.push(v); - } else - result[k] = v; - } - return result; - }, - declaredOut: parsed - }) -}, { - name: "FormData" -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/TypedArray.js -var TypedArray = Scope.module({ - Int8: ["instanceof", Int8Array], - Uint8: ["instanceof", Uint8Array], - Uint8Clamped: ["instanceof", Uint8ClampedArray], - Int16: ["instanceof", Int16Array], - Uint16: ["instanceof", Uint16Array], - Int32: ["instanceof", Int32Array], - Uint32: ["instanceof", Uint32Array], - Float32: ["instanceof", Float32Array], - Float64: ["instanceof", Float64Array], - BigInt64: ["instanceof", BigInt64Array], - BigUint64: ["instanceof", BigUint64Array] -}, { - name: "TypedArray" -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/constructors.js -var omittedPrototypes = { - Boolean: 1, - Number: 1, - String: 1 -}; -var arkPrototypes = Scope.module({ - ...flatMorph2({ ...ecmascriptConstructors2, ...platformConstructors2 }, (k, v) => k in omittedPrototypes ? [] : [k, ["instanceof", v]]), - Array: arkArray, - TypedArray, - FormData: arkFormData -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/number.js -var epoch = rootSchema({ - domain: { - domain: "number", - meta: "a number representing a Unix timestamp" - }, - divisor: { - rule: 1, - meta: `an integer representing a Unix timestamp` - }, - min: { - rule: -864e13, - meta: `a Unix timestamp after -8640000000000000` - }, - max: { - rule: 864e13, - meta: "a Unix timestamp before 8640000000000000" - }, - meta: "an integer representing a safe Unix timestamp" -}); -var integer = rootSchema({ - domain: "number", - divisor: 1 -}); -var number = Scope.module({ - root: intrinsic.number, - integer, - epoch, - safe: rootSchema({ - domain: { - domain: "number", - numberAllowsNaN: false - }, - min: Number.MIN_SAFE_INTEGER, - max: Number.MAX_SAFE_INTEGER - }), - NaN: ["===", Number.NaN], - Infinity: ["===", Number.POSITIVE_INFINITY], - NegativeInfinity: ["===", Number.NEGATIVE_INFINITY] -}, { - name: "number" -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/string.js -var regexStringNode = (regex3, description, jsonSchemaFormat) => { - const schema2 = { - domain: "string", - pattern: { - rule: regex3.source, - flags: regex3.flags, - meta: description - } - }; - if (jsonSchemaFormat) - schema2.meta = { format: jsonSchemaFormat }; - return node("intersection", schema2); -}; -var stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher2, "a well-formed integer string"); -var stringInteger = Scope.module({ - root: stringIntegerRoot, - parse: rootSchema({ - in: stringIntegerRoot, - morphs: (s, ctx) => { - const parsed2 = Number.parseInt(s); - return Number.isSafeInteger(parsed2) ? parsed2 : ctx.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER"); - }, - declaredOut: intrinsic.integer - }) -}, { - name: "string.integer" -}); -var hex = regexStringNode(/^[\dA-Fa-f]+$/, "hex characters only"); -var base64 = Scope.module({ - root: regexStringNode(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/, "base64-encoded"), - url: regexStringNode(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/, "base64url-encoded") -}, { - name: "string.base64" -}); -var preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized"); -var capitalize2 = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1), - declaredOut: preformattedCapitalize - }), - preformatted: preformattedCapitalize -}, { - name: "string.capitalize" -}); -var isLuhnValid = (creditCardInput) => { - const sanitized = creditCardInput.replace(/[ -]+/g, ""); - let sum = 0; - let digit; - let tmpNum; - let shouldDouble = false; - for (let i = sanitized.length - 1; i >= 0; i--) { - digit = sanitized.substring(i, i + 1); - tmpNum = Number.parseInt(digit, 10); - if (shouldDouble) { - tmpNum *= 2; - sum += tmpNum >= 10 ? tmpNum % 10 + 1 : tmpNum; - } else - sum += tmpNum; - shouldDouble = !shouldDouble; - } - return !!(sum % 10 === 0 ? sanitized : false); -}; -var creditCardMatcher = /^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/; -var creditCard = rootSchema({ - domain: "string", - pattern: { - meta: "a credit card number", - rule: creditCardMatcher.source - }, - predicate: { - meta: "a credit card number", - predicate: isLuhnValid - } -}); -var iso8601Matcher = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; -var isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf()); -var parsableDate = rootSchema({ - domain: "string", - predicate: { - meta: "a parsable date", - predicate: isParsableDate - } -}).assertHasKind("intersection"); -var epochRoot = stringInteger.root.internal.narrow((s, ctx) => { - const n = Number.parseInt(s); - const out = number.epoch(n); - if (out instanceof ArkErrors) { - ctx.errors.merge(out); - return false; - } - return true; -}).configure({ - description: "an integer string representing a safe Unix timestamp" -}, "self").assertHasKind("intersection"); -var epoch2 = Scope.module({ - root: epochRoot, - parse: rootSchema({ - in: epochRoot, - morphs: (s) => new Date(s), - declaredOut: intrinsic.Date - }) -}, { - name: "string.date.epoch" -}); -var isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"); -var iso = Scope.module({ - root: isoRoot, - parse: rootSchema({ - in: isoRoot, - morphs: (s) => new Date(s), - declaredOut: intrinsic.Date - }) -}, { - name: "string.date.iso" -}); -var stringDate = Scope.module({ - root: parsableDate, - parse: rootSchema({ - declaredIn: parsableDate, - in: "string", - morphs: (s, ctx) => { - const date2 = new Date(s); - if (Number.isNaN(date2.valueOf())) - return ctx.error("a parsable date"); - return date2; - }, - declaredOut: intrinsic.Date - }), - iso, - epoch: epoch2 -}, { - name: "string.date" -}); -var email = regexStringNode( - // considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead - // which breaks some integrations e.g. fast-check - // regex based on: - // https://www.regular-expressions.info/email.html - /^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/, - "an email address", - "email" -); -var ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; -var ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`; -var ipv4Matcher = new RegExp(`^${ipv4Address}$`); -var ipv6Segment = "(?:[0-9a-fA-F]{1,4})"; -var ipv6Matcher = new RegExp(`^((?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`); -var ip = Scope.module({ - root: ["v4 | v6", "@", "an IP address"], - v4: regexStringNode(ipv4Matcher, "an IPv4 address", "ipv4"), - v6: regexStringNode(ipv6Matcher, "an IPv6 address", "ipv6") -}, { - name: "string.ip" -}); -var jsonStringDescription = "a JSON string"; -var writeJsonSyntaxErrorProblem = (error41) => { - if (!(error41 instanceof SyntaxError)) - throw error41; - return `must be ${jsonStringDescription} (${error41})`; -}; -var jsonRoot = rootSchema({ - meta: jsonStringDescription, - domain: "string", - predicate: { - meta: jsonStringDescription, - predicate: (s, ctx) => { - try { - JSON.parse(s); - return true; - } catch (e) { - return ctx.reject({ - code: "predicate", - expected: jsonStringDescription, - problem: writeJsonSyntaxErrorProblem(e) - }); - } - } - } -}); -var parseJson = (s, ctx) => { - if (s.length === 0) { - return ctx.error({ - code: "predicate", - expected: jsonStringDescription, - actual: "empty" - }); - } - try { - return JSON.parse(s); - } catch (e) { - return ctx.error({ - code: "predicate", - expected: jsonStringDescription, - problem: writeJsonSyntaxErrorProblem(e) - }); - } -}; -var json = Scope.module({ - root: jsonRoot, - parse: rootSchema({ - meta: "safe JSON string parser", - in: "string", - morphs: parseJson, - declaredOut: intrinsic.jsonObject - }) -}, { - name: "string.json" -}); -var preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters"); -var lower = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.toLowerCase(), - declaredOut: preformattedLower - }), - preformatted: preformattedLower -}, { - name: "string.lower" -}); -var normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"]; -var preformattedNodes = flatMorph2(normalizedForms, (i, form) => [ - form, - rootSchema({ - domain: "string", - predicate: (s) => s.normalize(form) === s, - meta: `${form}-normalized unicode` - }) -]); -var normalizeNodes = flatMorph2(normalizedForms, (i, form) => [ - form, - rootSchema({ - in: "string", - morphs: (s) => s.normalize(form), - declaredOut: preformattedNodes[form] - }) -]); -var NFC = Scope.module({ - root: normalizeNodes.NFC, - preformatted: preformattedNodes.NFC -}, { - name: "string.normalize.NFC" -}); -var NFD = Scope.module({ - root: normalizeNodes.NFD, - preformatted: preformattedNodes.NFD -}, { - name: "string.normalize.NFD" -}); -var NFKC = Scope.module({ - root: normalizeNodes.NFKC, - preformatted: preformattedNodes.NFKC -}, { - name: "string.normalize.NFKC" -}); -var NFKD = Scope.module({ - root: normalizeNodes.NFKD, - preformatted: preformattedNodes.NFKD -}, { - name: "string.normalize.NFKD" -}); -var normalize = Scope.module({ - root: "NFC", - NFC, - NFD, - NFKC, - NFKD -}, { - name: "string.normalize" -}); -var numericRoot = regexStringNode(numericStringMatcher2, "a well-formed numeric string"); -var stringNumeric = Scope.module({ - root: numericRoot, - parse: rootSchema({ - in: numericRoot, - morphs: (s) => Number.parseFloat(s), - declaredOut: intrinsic.number - }) -}, { - name: "string.numeric" -}); -var regexPatternDescription = "a regex pattern"; -var regex2 = rootSchema({ - domain: "string", - predicate: { - meta: regexPatternDescription, - predicate: (s, ctx) => { - try { - new RegExp(s); - return true; - } catch (e) { - return ctx.reject({ - code: "predicate", - expected: regexPatternDescription, - problem: String(e) - }); - } - } - }, - meta: { format: "regex" } -}); -var semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/; -var semver = regexStringNode(semverMatcher, "a semantic version (see https://semver.org/)"); -var preformattedTrim = regexStringNode( - // no leading or trailing whitespace - /^\S.*\S$|^\S?$/, - "trimmed" -); -var trim = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.trim(), - declaredOut: preformattedTrim - }), - preformatted: preformattedTrim -}, { - name: "string.trim" -}); -var preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters"); -var upper = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.toUpperCase(), - declaredOut: preformattedUpper - }), - preformatted: preformattedUpper -}, { - name: "string.upper" -}); -var isParsableUrl = (s) => URL.canParse(s); -var urlRoot = rootSchema({ - domain: "string", - predicate: { - meta: "a URL string", - predicate: isParsableUrl - }, - // URL.canParse allows a subset of the RFC-3986 URI spec - // since there is no other serializable validation, best include a format - meta: { format: "uri" } -}); -var url = Scope.module({ - root: urlRoot, - parse: rootSchema({ - declaredIn: urlRoot, - in: "string", - morphs: (s, ctx) => { - try { - return new URL(s); - } catch { - return ctx.error("a URL string"); - } - }, - declaredOut: rootSchema(URL) - }) -}, { - name: "string.url" -}); -var uuid = Scope.module({ - // the meta tuple expression ensures the error message does not delegate - // to the individual branches, which are too detailed - root: [ - "versioned | nil | max", - "@", - { description: "a UUID", format: "uuid" } - ], - "#nil": "'00000000-0000-0000-0000-000000000000'", - "#max": "'ffffffff-ffff-ffff-ffff-ffffffffffff'", - "#versioned": /[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i, - v1: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv1"), - v2: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv2"), - v3: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv3"), - v4: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv4"), - v5: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv5"), - v6: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv6"), - v7: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv7"), - v8: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv8") -}, { - name: "string.uuid" -}); -var string = Scope.module({ - root: intrinsic.string, - alpha: regexStringNode(/^[A-Za-z]*$/, "only letters"), - alphanumeric: regexStringNode(/^[\dA-Za-z]*$/, "only letters and digits 0-9"), - hex, - base64, - capitalize: capitalize2, - creditCard, - date: stringDate, - digits: regexStringNode(/^\d*$/, "only digits 0-9"), - email, - integer: stringInteger, - ip, - json, - lower, - normalize, - numeric: stringNumeric, - regex: regex2, - semver, - trim, - upper, - url, - uuid -}, { - name: "string" -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/ts.js -var arkTsKeywords = Scope.module({ - bigint: intrinsic.bigint, - boolean: intrinsic.boolean, - false: intrinsic.false, - never: intrinsic.never, - null: intrinsic.null, - number: intrinsic.number, - object: intrinsic.object, - string: intrinsic.string, - symbol: intrinsic.symbol, - true: intrinsic.true, - unknown: intrinsic.unknown, - undefined: intrinsic.undefined -}); -var unknown = Scope.module({ - root: intrinsic.unknown, - any: intrinsic.unknown -}, { - name: "unknown" -}); -var json2 = Scope.module({ - root: intrinsic.jsonObject, - stringify: node("morph", { - in: intrinsic.jsonObject, - morphs: (data) => JSON.stringify(data), - declaredOut: intrinsic.string - }) -}, { - name: "object.json" -}); -var object = Scope.module({ - root: intrinsic.object, - json: json2 -}, { - name: "object" -}); -var RecordHkt = class extends Hkt { - description = 'instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'; -}; -var Record = genericNode(["K", intrinsic.key], "V")((args3) => ({ - domain: "object", - index: { - signature: args3.K, - value: args3.V - } -}), RecordHkt); -var PickHkt = class extends Hkt { - description = 'pick a set of properties from an object like `Pick(User, "name | age")`'; -}; -var Pick = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args3) => args3.T.pick(args3.K), PickHkt); -var OmitHkt = class extends Hkt { - description = 'omit a set of properties from an object like `Omit(User, "age")`'; -}; -var Omit = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args3) => args3.T.omit(args3.K), OmitHkt); -var PartialHkt = class extends Hkt { - description = "make all named properties of an object optional like `Partial(User)`"; -}; -var Partial = genericNode(["T", intrinsic.object])((args3) => args3.T.partial(), PartialHkt); -var RequiredHkt = class extends Hkt { - description = "make all named properties of an object required like `Required(User)`"; -}; -var Required2 = genericNode(["T", intrinsic.object])((args3) => args3.T.required(), RequiredHkt); -var ExcludeHkt = class extends Hkt { - description = 'exclude branches of a union like `Exclude("boolean", "true")`'; -}; -var Exclude = genericNode("T", "U")((args3) => args3.T.exclude(args3.U), ExcludeHkt); -var ExtractHkt = class extends Hkt { - description = 'extract branches of a union like `Extract("0 | false | 1", "number")`'; -}; -var Extract = genericNode("T", "U")((args3) => args3.T.extract(args3.U), ExtractHkt); -var arkTsGenerics = Scope.module({ - Exclude, - Extract, - Omit, - Partial, - Pick, - Record, - Required: Required2 -}); - -// node_modules/.pnpm/arktype@2.1.28/node_modules/arktype/out/keywords/keywords.js -var ark = scope({ - ...arkTsKeywords, - ...arkTsGenerics, - ...arkPrototypes, - ...arkBuiltins, - string, - number, - object, - unknown -}, { prereducedAliases: true, name: "ark" }); -var keywords = ark.export(); -Object.assign($arkTypeRegistry.ambient, keywords); -$arkTypeRegistry.typeAttachments = { - string: keywords.string.root, - number: keywords.number.root, - bigint: keywords.bigint, - boolean: keywords.boolean, - symbol: keywords.symbol, - undefined: keywords.undefined, - null: keywords.null, - object: keywords.object.root, - unknown: keywords.unknown.root, - false: keywords.false, - true: keywords.true, - never: keywords.never, - arrayIndex: keywords.Array.index, - Key: keywords.Key, - Record: keywords.Record, - Array: keywords.Array.root, - Date: keywords.Date -}; -var type = Object.assign( - ark.type, - // assign attachments newly parsed in keywords - // future scopes add these directly from the - // registry when their TypeParsers are instantiated - $arkTypeRegistry.typeAttachments -); -var match = ark.match; -var fn = ark.fn; -var generic = ark.generic; -var schema = ark.schema; -var define2 = ark.define; -var declare = ark.declare; - -// external.ts -var ghPullfrogMcpName = "gh_pullfrog"; -var agentsManifest = { - claude: { - displayName: "Claude Code", - apiKeyNames: ["anthropic_api_key"], - url: "https://claude.com/claude-code" - }, - codex: { - displayName: "Codex CLI", - apiKeyNames: ["openai_api_key"], - url: "https://platform.openai.com/docs/guides/codex" - }, - cursor: { - displayName: "Cursor CLI", - apiKeyNames: ["cursor_api_key"], - url: "https://cursor.com/" - }, - gemini: { - displayName: "Gemini CLI", - apiKeyNames: ["google_api_key", "gemini_api_key"], - url: "https://ai.google.dev/gemini-api/docs" - }, - opencode: { - displayName: "OpenCode", - apiKeyNames: [], - // empty array means OpenCode accepts any API_KEY from environment - url: "https://opencode.ai" - } -}; -var AgentName = type.enumerated(...Object.keys(agentsManifest)); +// agents/instructions.ts +init_external(); // modes.ts +init_external(); var reportProgressInstruction = `Use ${ghPullfrogMcpName}/report_progress to share progress and results. Continue calling it as you make progress - it will update the same comment. Never create additional comments manually.`; function getModes({ disableProgressComment }) { return [ @@ -92863,203 +98171,15 @@ ${encodedEvent}` : ""} }; // agents/shared.ts +init_external(); +init_cli(); +init_github(); import { spawnSync } from "node:child_process"; import { chmodSync, createWriteStream as createWriteStream2, existsSync as existsSync2 } from "node:fs"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join as join4 } from "node:path"; import { pipeline } from "node:stream/promises"; - -// utils/github.ts -var core2 = __toESM(require_core(), 1); -import { createSign } from "node:crypto"; -function isGitHubActionsEnvironment() { - return Boolean(process.env.GITHUB_ACTIONS); -} -async function acquireTokenViaOIDC() { - log.info("Generating OIDC token..."); - const oidcToken = await core2.getIDToken("pullfrog-api"); - log.info("OIDC token generated successfully"); - const apiUrl = process.env.API_URL || "https://pullfrog.com"; - log.info("Exchanging OIDC token for installation token..."); - const timeoutMs = 5e3; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - try { - const tokenResponse = await fetch(`${apiUrl}/api/github/installation-token`, { - method: "POST", - headers: { - Authorization: `Bearer ${oidcToken}`, - "Content-Type": "application/json" - }, - signal: controller.signal - }); - clearTimeout(timeoutId); - if (!tokenResponse.ok) { - throw new Error(`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText}`); - } - const tokenData = await tokenResponse.json(); - log.info(`Installation token obtained for ${tokenData.repository || "all repositories"}`); - return tokenData.token; - } catch (error41) { - clearTimeout(timeoutId); - if (error41 instanceof Error && error41.name === "AbortError") { - throw new Error(`Token exchange timed out after ${timeoutMs}ms`); - } - throw error41; - } -} -var base64UrlEncode = (str) => { - return Buffer.from(str).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -}; -var generateJWT = (appId, privateKey) => { - const now = Math.floor(Date.now() / 1e3); - const payload = { - iat: now - 60, - exp: now + 5 * 60, - iss: appId - }; - const header = { - alg: "RS256", - typ: "JWT" - }; - const encodedHeader = base64UrlEncode(JSON.stringify(header)); - const encodedPayload = base64UrlEncode(JSON.stringify(payload)); - const signaturePart = `${encodedHeader}.${encodedPayload}`; - const signature = createSign("RSA-SHA256").update(signaturePart).sign(privateKey, "base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - return `${signaturePart}.${signature}`; -}; -var githubRequest = async (path3, options = {}) => { - const { method = "GET", headers = {}, body } = options; - const url2 = `https://api.github.com${path3}`; - const requestHeaders = { - Accept: "application/vnd.github.v3+json", - "User-Agent": "Pullfrog-Installation-Token-Generator/1.0", - ...headers - }; - const response = await fetch(url2, { - method, - headers: requestHeaders, - ...body && { body } - }); - if (!response.ok) { - const errorText = await response.text(); - throw new Error( - `GitHub API request failed: ${response.status} ${response.statusText} -${errorText}` - ); - } - return response.json(); -}; -var checkRepositoryAccess = async (token, repoOwner, repoName) => { - try { - const response = await githubRequest("/installation/repositories", { - headers: { Authorization: `token ${token}` } - }); - return response.repositories.some( - (repo) => repo.owner.login === repoOwner && repo.name === repoName - ); - } catch { - return false; - } -}; -var createInstallationToken = async (jwt, installationId) => { - const response = await githubRequest( - `/app/installations/${installationId}/access_tokens`, - { - method: "POST", - headers: { Authorization: `Bearer ${jwt}` } - } - ); - return response.token; -}; -var findInstallationId = async (jwt, repoOwner, repoName) => { - const installations = await githubRequest("/app/installations", { - headers: { Authorization: `Bearer ${jwt}` } - }); - for (const installation of installations) { - try { - const tempToken = await createInstallationToken(jwt, installation.id); - const hasAccess = await checkRepositoryAccess(tempToken, repoOwner, repoName); - if (hasAccess) { - return installation.id; - } - } catch { - } - } - throw new Error( - `No installation found with access to ${repoOwner}/${repoName}. Ensure the GitHub App is installed on the target repository.` - ); -}; -async function acquireTokenViaGitHubApp() { - const repoContext = parseRepoContext(); - const config2 = { - appId: process.env.GITHUB_APP_ID, - privateKey: process.env.GITHUB_PRIVATE_KEY?.replace(/\\n/g, "\n"), - repoOwner: repoContext.owner, - repoName: repoContext.name - }; - const jwt = generateJWT(config2.appId, config2.privateKey); - const installationId = await findInstallationId(jwt, config2.repoOwner, config2.repoName); - const token = await createInstallationToken(jwt, installationId); - return token; -} -async function acquireNewToken() { - if (isGitHubActionsEnvironment()) { - return await acquireTokenViaOIDC(); - } else { - return await acquireTokenViaGitHubApp(); - } -} -var githubInstallationToken; -async function setupGitHubInstallationToken() { - const acquiredToken = await acquireNewToken(); - core2.setSecret(acquiredToken); - githubInstallationToken = acquiredToken; - return acquiredToken; -} -function getGitHubInstallationToken() { - if (!githubInstallationToken) { - throw new Error("GitHub installation token not set. Call setupGitHubInstallationToken first."); - } - return githubInstallationToken; -} -async function revokeGitHubInstallationToken() { - if (!githubInstallationToken) { - return; - } - const token = githubInstallationToken; - githubInstallationToken = void 0; - const apiUrl = process.env.GITHUB_API_URL || "https://api.github.com"; - try { - await fetch(`${apiUrl}/installation/token`, { - method: "DELETE", - headers: { - Accept: "application/vnd.github+json", - Authorization: `Bearer ${token}`, - "X-GitHub-Api-Version": "2022-11-28" - } - }); - log.info("Installation token revoked"); - } catch (error41) { - log.warning( - `Failed to revoke installation token: ${error41 instanceof Error ? error41.message : String(error41)}` - ); - } -} -function parseRepoContext() { - const githubRepo = process.env.GITHUB_REPOSITORY; - if (!githubRepo) { - throw new Error("GITHUB_REPOSITORY environment variable is required"); - } - const [owner, name] = githubRepo.split("/"); - if (!owner || !name) { - throw new Error(`Invalid GITHUB_REPOSITORY format: ${githubRepo}. Expected 'owner/repo'`); - } - return { owner, name }; -} - -// agents/shared.ts function createAgentEnv(agentSpecificVars) { return { PATH: process.env.PATH, @@ -93729,6 +98849,7 @@ var Codex = class { }; // agents/codex.ts +init_cli(); var codex = agent({ name: "codex", install: async () => { @@ -93898,6 +99019,7 @@ function configureCodexMcpServers({ mcpServers, cliPath }) { } // agents/cursor.ts +init_cli(); import { spawn as spawn3 } from "node:child_process"; import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "node:fs"; import { homedir as homedir2 } from "node:os"; @@ -94106,6 +99228,7 @@ function configureCursorSandbox({ sandbox }) { } // agents/gemini.ts +init_cli(); import { spawnSync as spawnSync3 } from "node:child_process"; // utils/subprocess.ts @@ -94375,6 +99498,7 @@ function configureGeminiMcpServers({ mcpServers, cliPath }) { } // agents/opencode.ts +init_cli(); import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs"; import { join as join7 } from "node:path"; var finalOutput = ""; @@ -94720,3782 +99844,12 @@ var agents = { import { mkdtemp as mkdtemp2 } from "node:fs/promises"; import { tmpdir as tmpdir2 } from "node:os"; import { join as join8 } from "node:path"; - -// node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && process.version !== void 0) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - return ""; -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js -function register3(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - if (!options) { - options = {}; - } - if (Array.isArray(name)) { - return name.reverse().reduce((callback, name2) => { - return register3.bind(null, state, name2, callback, options); - }, method)(); - } - return Promise.resolve().then(() => { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce((method2, registered) => { - return registered.hook.bind(null, method2, options); - }, method)(); - }); -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js -function addHook(state, kind, name, hook2) { - const orig = hook2; - if (!state.registry[name]) { - state.registry[name] = []; - } - if (kind === "before") { - hook2 = (method, options) => { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; - } - if (kind === "after") { - hook2 = (method, options) => { - let result; - return Promise.resolve().then(method.bind(null, options)).then((result_) => { - result = result_; - return orig(result, options); - }).then(() => { - return result; - }); - }; - } - if (kind === "error") { - hook2 = (method, options) => { - return Promise.resolve().then(method.bind(null, options)).catch((error41) => { - return orig(error41, options); - }); - }; - } - state.registry[name].push({ - hook: hook2, - orig - }); -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - const index = state.registry[name].map((registered) => { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; - } - state.registry[name].splice(index, 1); -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js -var bind = Function.bind; -var bindable = bind.bind(bind); -function bindApi(hook2, state, name) { - const removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook2.api = { remove: removeHookRef }; - hook2.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach((kind) => { - const args3 = name ? [state, kind, name] : [state, kind]; - hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args3); - }); -} -function Singular() { - const singularHookName = Symbol("Singular"); - const singularHookState = { - registry: {} - }; - const singularHook = register3.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} -function Collection() { - const state = { - registry: {} - }; - const hook2 = register3.bind(null, state); - bindApi(hook2, state); - return hook2; -} -var before_after_hook_default = { Singular, Collection }; - -// node_modules/.pnpm/@octokit+endpoint@11.0.1/node_modules/@octokit/endpoint/dist-bundle/index.js -var VERSION = "0.0.0-development"; -var userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; -function lowercaseKeys(object2) { - if (!object2) { - return {}; - } - return Object.keys(object2).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object2[key]; - return newObj; - }, {}); -} -function isPlainObject2(value2) { - if (typeof value2 !== "object" || value2 === null) return false; - if (Object.prototype.toString.call(value2) !== "[object Object]") return false; - const proto = Object.getPrototypeOf(value2); - if (proto === null) return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value2); -} -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject2(options[key])) { - if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); - else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; -} -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; -} -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url2] = route.split(" "); - options = Object.assign(url2 ? { method, url: url2 } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); - } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} -function addQueryParameters(url2, parameters) { - const separator2 = /\?/.test(url2) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url2; - } - return url2 + separator2 + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} -var urlVariableRegex = /\{[^{}}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); -} -function omit2(object2, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object2)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object2[key]; - } - } - return result; -} -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue2(operator, value2, key) { - value2 = operator === "+" || operator === "#" ? encodeReserved(value2) : encodeUnreserved(value2); - if (key) { - return encodeUnreserved(key) + "=" + value2; - } else { - return value2; - } -} -function isDefined(value2) { - return value2 !== void 0 && value2 !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value2 = context[key], result = []; - if (isDefined(value2) && value2 !== "") { - if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") { - value2 = value2.toString(); - if (modifier && modifier !== "*") { - value2 = value2.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue2(operator, value2, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value2)) { - value2.filter(isDefined).forEach(function(value22) { - result.push( - encodeValue2(operator, value22, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value2).forEach(function(k) { - if (isDefined(value2[k])) { - result.push(encodeValue2(operator, value2[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value2)) { - value2.filter(isDefined).forEach(function(value22) { - tmp.push(encodeValue2(operator, value22)); - }); - } else { - Object.keys(value2).forEach(function(k) { - if (isDefined(value2[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue2(operator, value2[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value2)) { - result.push(encodeUnreserved(key)); - } - } else if (value2 === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value2 === "") { - result.push(""); - } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator2 = ","; - if (operator === "?") { - separator2 = "&"; - } else if (operator !== "#") { - separator2 = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator2); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} -function parse(options) { - let method = options.method.toUpperCase(); - let url2 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit2(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url2); - url2 = parseUrl(url2).expand(parameters); - if (!/^http/.test(url2)) { - url2 = options.baseUrl + url2; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit2(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format2) => format2.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); - } - if (url2.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format2 = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format2}`; - }).join(","); - } - } - } - if (["GET", "HEAD"].includes(method)) { - url2 = addQueryParameters(url2, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } - } - } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url: url2, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); -} -var endpoint = withDefaults(null, DEFAULTS); - -// node_modules/.pnpm/@octokit+request@10.0.5/node_modules/@octokit/request/dist-bundle/index.js -var import_fast_content_type_parse = __toESM(require_fast_content_type_parse(), 1); - -// node_modules/.pnpm/@octokit+request-error@7.0.1/node_modules/@octokit/request-error/dist-src/index.js -var RequestError = class extends Error { - name; - /** - * http status code - */ - status; - /** - * Request options that lead to the error. - */ - request; - /** - * Response object if a response was received - */ - response; - constructor(message, statusCode, options) { - super(message); - this.name = "HttpError"; - this.status = Number.parseInt(statusCode); - if (Number.isNaN(this.status)) { - this.status = 0; - } - if ("response" in options) { - this.response = options.response; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? [ - name, - String(value2) - ]) - ); - let fetchResponse; - try { - fetchResponse = await fetch3(requestOptions.url, { - method: requestOptions.method, - body, - redirect: requestOptions.request?.redirect, - headers: requestHeaders, - signal: requestOptions.request?.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }); - } catch (error41) { - let message = "Unknown Error"; - if (error41 instanceof Error) { - if (error41.name === "AbortError") { - error41.status = 500; - throw error41; - } - message = error41.message; - if (error41.name === "TypeError" && "cause" in error41) { - if (error41.cause instanceof Error) { - message = error41.cause.message; - } else if (typeof error41.cause === "string") { - message = error41.cause; - } - } - } - const requestError = new RequestError(message, 500, { - request: requestOptions - }); - requestError.cause = error41; - throw requestError; - } - const status = fetchResponse.status; - const url2 = fetchResponse.url; - const responseHeaders = {}; - for (const [key, value2] of fetchResponse.headers) { - responseHeaders[key] = value2; - } - const octokitResponse = { - url: url2, - status, - headers: responseHeaders, - data: "" - }; - if ("deprecation" in responseHeaders) { - const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log2.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return octokitResponse; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return octokitResponse; - } - throw new RequestError(fetchResponse.statusText, status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status === 304) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError("Not modified", status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status >= 400) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError(toErrorMessage(octokitResponse.data), status, { - response: octokitResponse, - request: requestOptions - }); - } - octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; - return octokitResponse; -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (!contentType) { - return response.text().catch(() => ""); - } - const mimetype = (0, import_fast_content_type_parse.safeParse)(contentType); - if (isJSONResponse(mimetype)) { - let text = ""; - try { - text = await response.text(); - return JSON.parse(text); - } catch (err) { - return text; - } - } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { - return response.text().catch(() => ""); - } else { - return response.arrayBuffer().catch(() => new ArrayBuffer(0)); - } -} -function isJSONResponse(mimetype) { - return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; -} -function toErrorMessage(data) { - if (typeof data === "string") { - return data; - } - if (data instanceof ArrayBuffer) { - return "Unknown error"; - } - if ("message" in data) { - const suffix2 = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; - return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix2}` : `${data.message}${suffix2}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} -function withDefaults2(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults2.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults2.bind(null, endpoint2) - }); -} -var request = withDefaults2(endpoint, defaults_default); - -// node_modules/.pnpm/@octokit+graphql@9.0.2/node_modules/@octokit/graphql/dist-bundle/index.js -var VERSION3 = "0.0.0-development"; -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); -} -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - name = "GraphqlResponseError"; - errors; - data; -}; -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType", - "operationName" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query2, options) { - if (options) { - if (typeof query2 === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); - } - } - const parsedOptions = typeof query2 === "string" ? Object.assign({ query: query2 }, options) : query2; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); -} -function withDefaults3(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query2, options) => { - return graphql(newRequest, query2, options); - }; - return Object.assign(newApi, { - defaults: withDefaults3.bind(null, newRequest), - endpoint: newRequest.endpoint - }); -} -var graphql2 = withDefaults3(request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION3} ${getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults3(customRequest, { - method: "POST", - url: "/graphql" - }); -} - -// node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js -var b64url = "(?:[a-zA-Z0-9_-]+)"; -var sep = "\\."; -var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); -var isJWT = jwtRE.test.bind(jwtRE); -async function auth(token) { - const isApp = isJWT(token); - const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); - const isUserToServer = token.startsWith("ghu_"); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} -async function hook(token, request2, route, parameters) { - const endpoint2 = request2.endpoint.merge( - route, - parameters - ); - endpoint2.headers.authorization = withAuthorizationPrefix(token); - return request2(endpoint2); -} -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/version.js -var VERSION4 = "7.0.5"; - -// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/index.js -var noop = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop; - } - if (typeof logger.info !== "function") { - logger.info = noop; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -var userAgentTrail = `octokit-core.js/${VERSION4} ${getUserAgent()}`; -var Octokit = class { - static VERSION = VERSION4; - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args3) { - const options = args3[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static plugins = []; - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - }; - return NewOctokit; - } - constructor(options = {}) { - const hook2 = new before_after_hook_default.Collection(); - const requestDefaults = { - baseUrl: request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook2.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - this.request = request.defaults(requestDefaults); - this.graphql = withCustomRequest(this.request).defaults(requestDefaults); - this.log = createLogger(options.log); - this.hook = hook2; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth2 = createTokenAuth(options.auth); - hook2.wrap("request", auth2.hook); - this.auth = auth2; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth2 = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook2.wrap("request", auth2.hook); - this.auth = auth2; - } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); - } - } - // assigned during constructor - request; - graphql; - log; - hook; - // TODO: type `octokit.auth` based on passed options.authStrategy - auth; -}; - -// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/version.js -var VERSION5 = "6.0.0"; - -// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/index.js -function requestLog(octokit) { - octokit.hook.wrap("request", (request2, options) => { - octokit.log.debug("request", options); - const start = Date.now(); - const requestOptions = octokit.request.endpoint.parse(options); - const path3 = requestOptions.url.replace(options.baseUrl, ""); - return request2(options).then((response) => { - const requestId = response.headers["x-github-request-id"]; - octokit.log.info( - `${requestOptions.method} ${path3} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` - ); - return response; - }).catch((error41) => { - const requestId = error41.response?.headers["x-github-request-id"] || "UNKNOWN"; - octokit.log.error( - `${requestOptions.method} ${path3} - ${error41.status} with id ${requestId} in ${Date.now() - start}ms` - ); - throw error41; - }); - }); -} -requestLog.VERSION = VERSION5; - -// node_modules/.pnpm/@octokit+plugin-paginate-rest@13.2.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js -var VERSION6 = "0.0.0-development"; -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); - if (!responseNeedsNormalization) return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - const totalCommits = response.data.total_commits; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - delete response.data.total_commits; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - response.data.total_commits = totalCommits; - return response; -} -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 headers = options.headers; - let url2 = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url2) return { done: true }; - try { - const response = await requestMethod({ method, url: url2, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url2 = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - if (!url2 && "total_commits" in normalizedResponse.data) { - const parsedUrl = new URL(normalizedResponse.url); - const params = parsedUrl.searchParams; - const page = parseInt(params.get("page") || "1", 10); - const per_page = parseInt(params.get("per_page") || "250", 10); - if (page * per_page < normalizedResponse.data.total_commits) { - params.set("page", String(page + 1)); - url2 = parsedUrl.toString(); - } - } - return { value: normalizedResponse }; - } catch (error41) { - if (error41.status !== 409) throw error41; - url2 = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} -var composePaginateRest = Object.assign(paginate, { - iterator -}); -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION6; - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js -var VERSION7 = "16.1.0"; - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addRepoAccessToSelfHostedRunnerGroupInOrg: [ - "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], - createOrUpdateEnvironmentSecret: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - deleteHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - getHostedRunnersGithubOwnedImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/github-owned" - ], - getHostedRunnersLimitsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/limits" - ], - getHostedRunnersMachineSpecsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/machine-sizes" - ], - getHostedRunnersPartnerImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/partner" - ], - getHostedRunnersPlatformsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/platforms" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - listGithubHostedRunnersInGroupForOrg: [ - "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" - ], - listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - updateHostedRunnerForOrg: [ - "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubBillingUsageReportOrg: [ - "GET /organizations/{org}/settings/billing/usage" - ], - getGithubBillingUsageReportUser: [ - "GET /users/{username}/settings/billing/usage" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - campaigns: { - createCampaign: ["POST /orgs/{org}/campaigns"], - deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], - getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], - listOrgCampaigns: ["GET /orgs/{org}/campaigns"], - updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - commitAutofix: [ - "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" - ], - createAutofix: [ - "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" - ], - createVariantAnalysis: [ - "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" - ], - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - deleteCodeqlDatabase: [ - "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getAutofix: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - getVariantAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" - ], - getVariantAnalysisRepoTask: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" - ], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codeSecurity: { - attachConfiguration: [ - "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" - ], - attachEnterpriseConfiguration: [ - "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" - ], - createConfiguration: ["POST /orgs/{org}/code-security/configurations"], - createConfigurationForEnterprise: [ - "POST /enterprises/{enterprise}/code-security/configurations" - ], - deleteConfiguration: [ - "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" - ], - deleteConfigurationForEnterprise: [ - "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ], - detachConfiguration: [ - "DELETE /orgs/{org}/code-security/configurations/detach" - ], - getConfiguration: [ - "GET /orgs/{org}/code-security/configurations/{configuration_id}" - ], - getConfigurationForRepository: [ - "GET /repos/{owner}/{repo}/code-security-configuration" - ], - getConfigurationsForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations" - ], - getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], - getDefaultConfigurations: [ - "GET /orgs/{org}/code-security/configurations/defaults" - ], - getDefaultConfigurationsForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations/defaults" - ], - getRepositoriesForConfiguration: [ - "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" - ], - getRepositoriesForEnterpriseConfiguration: [ - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" - ], - getSingleConfigurationForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ], - setConfigurationAsDefault: [ - "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" - ], - setConfigurationAsDefaultForEnterprise: [ - "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" - ], - updateConfiguration: [ - "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" - ], - updateEnterpriseConfiguration: [ - "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], - copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - credentials: { revoke: ["POST /credentials/revoke"] }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - repositoryAccessForOrg: [ - "GET /organizations/{org}/dependabot/repository-access" - ], - setRepositoryAccessDefaultLevel: [ - "PUT /organizations/{org}/dependabot/repository-access/default-level" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ], - updateRepositoryAccessForOrg: [ - "PATCH /organizations/{org}/dependabot/repository-access" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - hostedCompute: { - createNetworkConfigurationForOrg: [ - "POST /orgs/{org}/settings/network-configurations" - ], - deleteNetworkConfigurationFromOrg: [ - "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ], - getNetworkConfigurationForOrg: [ - "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ], - getNetworkSettingsForOrg: [ - "GET /orgs/{org}/settings/network-settings/{network_settings_id}" - ], - listNetworkConfigurationsForOrg: [ - "GET /orgs/{org}/settings/network-configurations" - ], - updateNetworkConfigurationForOrg: [ - "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addBlockedByDependency: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - addSubIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" - ], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listDependenciesBlockedBy: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" - ], - listDependenciesBlocking: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" - ], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - listSubIssues: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" - ], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeDependencyBlockedBy: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - removeSubIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" - ], - reprioritizeSubIssue: [ - "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}", - {}, - { - deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" - } - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createArtifactStorageRecord: [ - "POST /orgs/{org}/artifacts/metadata/storage-record" - ], - createInvitation: ["POST /orgs/{org}/invitations"], - createIssueType: ["POST /orgs/{org}/issue-types"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], - deleteAttestationsById: [ - "DELETE /orgs/{org}/attestations/{attestation_id}" - ], - deleteAttestationsBySubjectDigest: [ - "DELETE /orgs/{org}/attestations/digest/{subject_digest}" - ], - deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], - getOrgRulesetVersion: [ - "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" - ], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listArtifactStorageRecords: [ - "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" - ], - listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], - listAttestationsBulk: [ - "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" - ], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listIssueTypes: ["GET /orgs/{org}/issue-types"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: [ - "GET /orgs/{org}/security-managers", - {}, - { - deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" - } - ], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}", - {}, - { - deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" - } - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - privateRegistries: { - createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], - deleteOrgPrivateRegistry: [ - "DELETE /orgs/{org}/private-registries/{secret_name}" - ], - getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], - getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], - listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], - updateOrgPrivateRegistry: [ - "PATCH /orgs/{org}/private-registries/{secret_name}" - ] - }, - projects: { - addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], - addItemForUser: ["POST /users/{user_id}/projectsV2/{project_number}/items"], - deleteItemForOrg: [ - "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" - ], - deleteItemForUser: [ - "DELETE /users/{user_id}/projectsV2/{project_number}/items/{item_id}" - ], - getFieldForOrg: [ - "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" - ], - getFieldForUser: [ - "GET /users/{user_id}/projectsV2/{project_number}/fields/{field_id}" - ], - getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], - getForUser: ["GET /users/{user_id}/projectsV2/{project_number}"], - getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], - getUserItem: [ - "GET /users/{user_id}/projectsV2/{project_number}/items/{item_id}" - ], - listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], - listFieldsForUser: [ - "GET /users/{user_id}/projectsV2/{project_number}/fields" - ], - listForOrg: ["GET /orgs/{org}/projectsV2"], - listForUser: ["GET /users/{username}/projectsV2"], - listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], - listItemsForUser: [ - "GET /users/{user_id}/projectsV2/{project_number}/items" - ], - updateItemForOrg: [ - "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" - ], - updateItemForUser: [ - "PATCH /users/{user_id}/projectsV2/{project_number}/items/{item_id}" - ] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkPrivateVulnerabilityReporting: [ - "GET /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAttestation: ["POST /repos/{owner}/{repo}/attestations"], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateCustomPropertiesValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" - ], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" - ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesetHistory: [ - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" - ], - getRepoRulesetVersion: [ - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" - ], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAttestations: [ - "GET /repos/{owner}/{repo}/attestations/{subject_digest}" - ], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: [ - "GET /search/issues", - {}, - { - deprecated: "octokit.rest.search.issuesAndPullRequests() is deprecated, see https://docs.github.com/rest/search/search#search-issues-and-pull-requests" - } - ], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - createPushProtectionBypass: [ - "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - listOrgPatternConfigs: [ - "GET /orgs/{org}/secret-scanning/pattern-configurations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - updateOrgPatternConfigs: [ - "PATCH /orgs/{org}/secret-scanning/pattern-configurations" - ] - }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" - ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteAttestationsBulk: [ - "POST /users/{username}/attestations/delete-request" - ], - deleteAttestationsById: [ - "DELETE /users/{username}/attestations/{attestation_id}" - ], - deleteAttestationsBySubjectDigest: [ - "DELETE /users/{username}/attestations/digest/{subject_digest}" - ], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getById: ["GET /user/{account_id}"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], - listAttestationsBulk: [ - "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" - ], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope2, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint2] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint2; - const [method, url2] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url: url2 - }, - defaults - ); - if (!endpointMethodsMap.has(scope2)) { - endpointMethodsMap.set(scope2, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope2).set(methodName, { - scope: scope2, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope: scope2 }, methodName) { - return endpointMethodsMap.get(scope2).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope: scope2 }) { - return [...endpointMethodsMap.get(scope2).keys()]; - }, - set(target, methodName, value2) { - return target.cache[methodName] = value2; - }, - get({ octokit, scope: scope2, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope2).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope2, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope2 of endpointMethodsMap.keys()) { - newMethods[scope2] = new Proxy({ octokit, scope: scope2, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope2, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args3) { - let options = requestWithDefaults.endpoint.merge(...args3); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope2}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args3); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope2}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args3); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION7; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION7; - -// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/version.js -var VERSION8 = "22.0.0"; - -// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/index.js -var Octokit2 = Octokit.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults( - { - userAgent: `octokit-rest.js/${VERSION8}` - } -); - -// mcp/shared.ts -var mcpInitContext; -function initMcpContext(state) { - mcpInitContext = state; -} -function getMcpContext() { - if (!mcpInitContext) { - throw new Error("MCP context not initialized. Call initializeMcpContext first."); - } - return { - ...mcpInitContext, - ...parseRepoContext(), - octokit: new Octokit2({ - auth: getGitHubInstallationToken() - }) - }; -} -function isProgressCommentDisabled() { - return mcpInitContext?.payload.disableProgressComment === true; -} -var tool = (toolDef) => toolDef; -function sanitizeSchema(schema2) { - if (!schema2 || typeof schema2 !== "object") { - return schema2; - } - if (Array.isArray(schema2)) { - return schema2.map(sanitizeSchema); - } - if (schema2.anyOf && Array.isArray(schema2.anyOf) && schema2.anyOf.length > 0) { - const enumValues2 = []; - let allAreEnumObjects = true; - for (const item of schema2.anyOf) { - if (item && typeof item === "object" && Array.isArray(item.enum)) { - const stringEnums = item.enum.filter((v) => typeof v === "string"); - if (stringEnums.length > 0) { - enumValues2.push(...stringEnums); - } else { - allAreEnumObjects = false; - break; - } - } else { - allAreEnumObjects = false; - break; - } - } - if (allAreEnumObjects && enumValues2.length > 0) { - const uniqueEnums = [...new Set(enumValues2)]; - const result = { - type: "string", - enum: uniqueEnums - }; - if (schema2.description) { - result.description = schema2.description; - } - return result; - } - } - const sanitized = {}; - for (const [key, value2] of Object.entries(schema2)) { - if (key === "$schema") { - continue; - } - if (key === "anyOf" && schema2.anyOf) { - continue; - } - if (key === "$defs") { - sanitized.definitions = sanitizeSchema(value2); - continue; - } - sanitized[key] = sanitizeSchema(value2); - } - return sanitized; -} -function wrapSchema(schema2) { - const originalToJsonSchema = schema2.toJsonSchema?.bind(schema2); - if (!originalToJsonSchema) { - return schema2; - } - return new Proxy(schema2, { - get(target, prop) { - if (prop === "toJsonSchema") { - return () => { - const originalSchema = originalToJsonSchema(); - return sanitizeSchema(originalSchema); - }; - } - return target[prop]; - } - }); -} -function sanitizeTool(tool2) { - if (!tool2.parameters) { - return tool2; - } - const wrappedSchema = wrapSchema(tool2.parameters); - return { - ...tool2, - parameters: wrappedSchema - }; -} -var addTools = (server, tools) => { - const shouldSanitize = mcpInitContext?.agentName === "gemini" || mcpInitContext?.agentName === "opencode"; - for (const tool2 of tools) { - const processedTool = shouldSanitize ? sanitizeTool(tool2) : tool2; - server.addTool(processedTool); - } - return server; -}; -var contextualize = (executor) => { - return async (params) => { - try { - const ctx = getMcpContext(); - const result = await executor(params, ctx); - return handleToolSuccess(result); - } catch (error41) { - return handleToolError(error41); - } - }; -}; -var handleToolSuccess = (data) => { - return { - content: [ - { - type: "text", - text: JSON.stringify(data, null, 2) - } - ] - }; -}; -var handleToolError = (error41) => { - const errorMessage = error41 instanceof Error ? error41.message : String(error41); - return { - content: [ - { - type: "text", - text: `Error: ${errorMessage}` - } - ], - isError: true - }; -}; - -// mcp/comment.ts -var PULLFROG_DIVIDER = ""; -function buildCommentFooter(payload) { - const repoContext = parseRepoContext(); - const runId = process.env.GITHUB_RUN_ID; - const agentName = payload.agent; - const agentInfo = agentName ? agentsManifest[agentName] : null; - const agentDisplayName = agentInfo?.displayName || "Unknown agent"; - const agentUrl = agentInfo?.url || "https://pullfrog.com"; - const workflowRunPart = runId ? `[View workflow run](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})` : "View workflow run"; - return ` -${PULLFROG_DIVIDER} -Pullfrog  \uFF5C Triggered by [Pullfrog](https://pullfrog.com) \uFF5C Using [${agentDisplayName}](${agentUrl}) \uFF5C ${workflowRunPart} \uFF5C [\u{1D54F}](https://x.com/pullfrogai)`; -} -function stripExistingFooter(body) { - const dividerIndex = body.indexOf(PULLFROG_DIVIDER); - if (dividerIndex === -1) { - return body; - } - return body.substring(0, dividerIndex).trimEnd(); -} -function addFooter(body, payload) { - const bodyWithoutFooter = stripExistingFooter(body); - const footer = buildCommentFooter(payload); - return `${bodyWithoutFooter}${footer}`; -} -var Comment = type({ - issueNumber: type.number.describe("the issue number to comment on"), - body: type.string.describe("the comment body content") -}); -var CreateCommentTool = tool({ - name: "create_issue_comment", - description: "Create a comment on a GitHub issue", - parameters: Comment, - execute: contextualize(async ({ issueNumber, body }, ctx) => { - const bodyWithFooter = addFooter(body, ctx.payload); - const result = await ctx.octokit.rest.issues.createComment({ - owner: ctx.owner, - repo: ctx.name, - issue_number: issueNumber, - body: bodyWithFooter - }); - return { - success: true, - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body - }; - }) -}); -var EditComment = type({ - commentId: type.number.describe("the ID of the comment to edit"), - body: type.string.describe("the new comment body content") -}); -var EditCommentTool = tool({ - name: "edit_issue_comment", - description: "Edit a GitHub issue comment by its ID", - parameters: EditComment, - execute: contextualize(async ({ commentId, body }, ctx) => { - const bodyWithFooter = addFooter(body, ctx.payload); - const result = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.owner, - repo: ctx.name, - comment_id: commentId, - body: bodyWithFooter - }); - return { - success: true, - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body, - updatedAt: result.data.updated_at - }; - }) -}); -function getProgressCommentIdFromEnv() { - const envCommentId = process.env.PULLFROG_PROGRESS_COMMENT_ID; - if (envCommentId) { - const parsed2 = parseInt(envCommentId, 10); - if (!Number.isNaN(parsed2)) { - return parsed2; - } - } - return null; -} -var progressCommentId = null; -var progressCommentIdInitialized = false; -var progressCommentWasUpdated = false; -function getProgressCommentId() { - if (!progressCommentIdInitialized) { - progressCommentId = getProgressCommentIdFromEnv(); - progressCommentIdInitialized = true; - } - return progressCommentId; -} -function setProgressCommentId(id) { - progressCommentId = id; - progressCommentIdInitialized = true; -} -var ReportProgress = type({ - body: type.string.describe("the progress update content to share") -}); -async function reportProgress({ body }) { - const ctx = getMcpContext(); - const bodyWithFooter = addFooter(body, ctx.payload); - const existingCommentId = getProgressCommentId(); - if (existingCommentId) { - const result2 = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.owner, - repo: ctx.name, - comment_id: existingCommentId, - body: bodyWithFooter - }); - progressCommentWasUpdated = true; - return { - commentId: result2.data.id, - url: result2.data.html_url, - body: result2.data.body || "", - action: "updated" - }; - } - const issueNumber = ctx.payload.event.issue_number; - if (issueNumber === void 0) { - return void 0; - } - const result = await ctx.octokit.rest.issues.createComment({ - owner: ctx.owner, - repo: ctx.name, - issue_number: issueNumber, - body: bodyWithFooter - }); - setProgressCommentId(result.data.id); - progressCommentWasUpdated = true; - return { - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body || "", - action: "created" - }; -} -var ReportProgressTool = tool({ - name: "report_progress", - description: "Share progress on the associated GitHub issue/PR. Call this to post updates as you work. The first call creates a comment, subsequent calls update it. Use this throughout your work to keep stakeholders informed.", - parameters: ReportProgress, - execute: contextualize(async ({ body }) => { - const result = await reportProgress({ body }); - if (!result) { - return { - success: false, - message: "cannot create progress comment: no issue_number found in the payload event" - }; - } - return { - success: true, - ...result - }; - }) -}); -async function ensureProgressCommentUpdated() { - const existingCommentId = getProgressCommentId(); - if (!existingCommentId || progressCommentWasUpdated) { - return; - } - try { - const ctx = getMcpContext(); - const repoContext = parseRepoContext(); - const runId = process.env.GITHUB_RUN_ID; - const workflowRunLink = runId ? `[workflow](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})` : "workflow"; - const errorMessage = `\u274C this run croaked - -The workflow encountered an error before any progress could be reported. Please check the ${workflowRunLink} for details.`; - const bodyWithFooter = addFooter(errorMessage, ctx.payload); - await ctx.octokit.rest.issues.updateComment({ - owner: ctx.owner, - repo: ctx.name, - comment_id: existingCommentId, - body: bodyWithFooter - }); - } catch { - } -} -var ReplyToReviewComment = type({ - pull_number: type.number.describe("the pull request number"), - comment_id: type.number.describe("the ID of the review comment to reply to"), - body: type.string.describe("the reply text explaining how the feedback was addressed") -}); -var ReplyToReviewCommentTool = tool({ - name: "reply_to_review_comment", - description: "Reply to a PR review comment thread explaining how the feedback was addressed. Use this after addressing each review comment to provide specific context about the changes made.", - parameters: ReplyToReviewComment, - execute: contextualize(async ({ pull_number, comment_id, body }, ctx) => { - const bodyWithFooter = addFooter(body, ctx.payload); - const result = await ctx.octokit.rest.pulls.createReplyForReviewComment({ - owner: ctx.owner, - repo: ctx.name, - pull_number, - comment_id, - body: bodyWithFooter - }); - return { - success: true, - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body, - in_reply_to_id: result.data.in_reply_to_id - }; - }) -}); +init_out4(); +init_external(); +init_comment(); // mcp/config.ts +init_external(); function createMcpConfigs(mcpServerUrl) { return { [ghPullfrogMcpName]: { @@ -98506,6 +99860,7 @@ function createMcpConfigs(mcpServerUrl) { } // mcp/arkConfig.ts +init_config2(); configure({ toJsonSchema: { dialect: null @@ -122779,7 +124134,12 @@ var FastMCP = class extends FastMCPEventEmitter { } }; +// mcp/server.ts +init_external(); + // mcp/checkSuite.ts +init_out4(); +init_shared3(); var GetCheckSuiteLogs = type({ check_suite_id: type.number.describe("the id from check_suite.id") }); @@ -122860,6 +124220,12 @@ var GetCheckSuiteLogsTool = tool({ }) }); +// mcp/server.ts +init_comment(); + +// mcp/debug.ts +init_out4(); + // utils/shell.ts import { spawnSync as spawnSync4 } from "node:child_process"; function $(cmd, args3, options) { @@ -122902,6 +124268,7 @@ function $(cmd, args3, options) { } // mcp/debug.ts +init_shared3(); var DebugShellCommand = type({}); var DebugShellCommandTool = tool({ name: "debug_shell_command", @@ -122940,7 +124307,13 @@ var DebugShellCommandTool = tool({ } }); +// mcp/git.ts +init_out4(); +init_cli(); + // utils/secrets.ts +init_external(); +init_github(); function getAllSecrets() { const secrets = []; for (const agent2 of Object.values(agentsManifest)) { @@ -122975,6 +124348,7 @@ function containsSecrets(content, secrets) { } // mcp/git.ts +init_shared3(); var CreateBranch = type({ branchName: type.string.describe( "The name of the branch to create (e.g., 'pullfrog/123-fix-bug')" @@ -123082,6 +124456,8 @@ var PushBranchTool = tool({ }); // mcp/issue.ts +init_out4(); +init_shared3(); var Issue = type({ title: type.string.describe("the title of the issue"), body: type.string.describe("the body content of the issue"), @@ -123115,6 +124491,8 @@ var IssueTool = tool({ }); // mcp/issueComments.ts +init_out4(); +init_shared3(); var GetIssueComments = type({ issue_number: type.number.describe("The issue number to get comments for") }); @@ -123146,6 +124524,8 @@ var GetIssueCommentsTool = tool({ }); // mcp/issueEvents.ts +init_out4(); +init_shared3(); var GetIssueEvents = type({ issue_number: type.number.describe("The issue number to get events for") }); @@ -123215,6 +124595,8 @@ var GetIssueEventsTool = tool({ }); // mcp/issueInfo.ts +init_out4(); +init_shared3(); var IssueInfo = type({ issue_number: type.number.describe("The issue number to fetch") }); @@ -123263,6 +124645,8 @@ var IssueInfoTool = tool({ }); // mcp/labels.ts +init_out4(); +init_shared3(); var AddLabelsParams = type({ issue_number: type.number.describe("the issue or PR number to add labels to"), labels: type.string.array().atLeastLength(1).describe("array of label names to add") @@ -123286,6 +124670,9 @@ var AddLabelsTool = tool({ }); // mcp/pr.ts +init_out4(); +init_cli(); +init_shared3(); var PullRequest = type({ title: type.string.describe("the title of the pull request"), body: type.string.describe("the body content of the pull request"), @@ -123330,6 +124717,9 @@ var PullRequestTool = tool({ }); // mcp/prInfo.ts +init_out4(); +init_cli(); +init_shared3(); var PullRequestInfo = type({ pull_number: type.number.describe("The pull request number to fetch") }); @@ -123369,6 +124759,8 @@ var PullRequestInfoTool = tool({ }); // mcp/review.ts +init_out4(); +init_shared3(); var Review = type({ pull_number: type.number.describe("The pull request number to review"), body: type.string.describe( @@ -123437,6 +124829,8 @@ var ReviewTool = tool({ }); // mcp/reviewComments.ts +init_out4(); +init_shared3(); var GetReviewComments = type({ pull_number: type.number.describe("The pull request number"), review_id: type.number.describe("The review ID to get comments for") @@ -123505,6 +124899,8 @@ var ListPullRequestReviewsTool = tool({ }); // mcp/selectMode.ts +init_out4(); +init_shared3(); var SelectMode = type({ modeName: type.string.describe( "the name of the mode to select (e.g., 'Plan', 'Build', 'Review', 'Prompt')" @@ -123532,6 +124928,7 @@ var SelectModeTool = tool({ }); // mcp/server.ts +init_shared3(); async function findAvailablePort(startPort) { const checkPort = (port2) => { return new Promise((resolve) => { @@ -123607,107 +125004,74 @@ async function startMcpHttpServer(state) { }; } -// utils/api.ts -var DEFAULT_REPO_SETTINGS = { - defaultAgent: null, - webAccessLevel: "full_access", - webAccessAllowTrusted: false, - webAccessDomains: "", - modes: [] -}; -async function fetchWorkflowRunInfo(runId) { - const apiUrl = process.env.API_URL || "https://pullfrog.com"; - const timeoutMs = 5e3; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - try { - const response = await fetch(`${apiUrl}/api/workflow-run/${runId}`, { - method: "GET", - headers: { - "Content-Type": "application/json" - }, - signal: controller.signal - }); - clearTimeout(timeoutId); - if (!response.ok) { - return { progressCommentId: null, issueNumber: null }; - } - const data = await response.json(); - return data; - } catch { - clearTimeout(timeoutId); - return { progressCommentId: null, issueNumber: null }; - } -} -async function fetchRepoSettings({ - token, - repoContext -}) { - const settings = await getRepoSettings(token, repoContext); - return settings; -} -async function getRepoSettings(token, repoContext) { - const apiUrl = process.env.API_URL || "https://pullfrog.com"; - const timeoutMs = 5e3; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - try { - const response = await fetch( - `${apiUrl}/api/repo/${repoContext.owner}/${repoContext.name}/settings`, - { - method: "GET", - headers: { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json" - }, - signal: controller.signal - } - ); - clearTimeout(timeoutId); - if (!response.ok) { - return DEFAULT_REPO_SETTINGS; - } - const settings = await response.json(); - if (settings === null) { - return DEFAULT_REPO_SETTINGS; - } - return settings; - } catch { - clearTimeout(timeoutId); - return DEFAULT_REPO_SETTINGS; - } -} +// main.ts +init_api(); +init_cli(); // utils/errorReport.ts -function isMcpContextInitialized() { - try { - getMcpContext(); - return true; - } catch { - return false; +init_dist_src5(); +init_api(); +init_github(); +function getProgressCommentIdFromEnv2() { + const envCommentId = process.env.PULLFROG_PROGRESS_COMMENT_ID; + if (envCommentId) { + const parsed2 = parseInt(envCommentId, 10); + if (!Number.isNaN(parsed2)) { + return parsed2; + } } + return null; } async function reportErrorToComment({ error: error41, title }) { - if (!isMcpContextInitialized()) { - log.debug("skipping error comment update: MCP context not initialized"); - return; - } - try { - const formattedError = title ? `${title} + const formattedError = title ? `${title} ${error41}` : `\u274C ${error41}`; - await reportProgress({ body: formattedError }); - } catch (reportError) { - const errorMessage = reportError instanceof Error ? reportError.message : String(reportError); - log.warning(`failed to report error to comment: ${errorMessage}`); + let commentId = getProgressCommentIdFromEnv2(); + if (!commentId) { + const runId = process.env.GITHUB_RUN_ID; + if (runId) { + try { + const workflowRunInfo = await fetchWorkflowRunInfo(runId); + if (workflowRunInfo.progressCommentId) { + const parsed2 = parseInt(workflowRunInfo.progressCommentId, 10); + if (!Number.isNaN(parsed2)) { + commentId = parsed2; + process.env.PULLFROG_PROGRESS_COMMENT_ID = workflowRunInfo.progressCommentId; + } + } + } catch { + } + } } + if (!commentId) { + try { + const { reportProgress: reportProgress2 } = await Promise.resolve().then(() => (init_comment(), comment_exports)); + await reportProgress2({ body: formattedError }); + return; + } catch { + return; + } + } + const repoContext = parseRepoContext(); + const token = getGitHubInstallationToken(); + const octokit = new Octokit2({ auth: token }); + await octokit.rest.issues.updateComment({ + owner: repoContext.owner, + repo: repoContext.name, + comment_id: commentId, + body: formattedError + }); } +// main.ts +init_github(); + // utils/setup.ts import { execSync } from "node:child_process"; +init_cli(); function setupGitConfig() { const repoDir = process.cwd(); log.info("\u{1F527} Setting up git configuration..."); @@ -123771,6 +125135,7 @@ function setupGitBranch(payload) { } // utils/timer.ts +init_cli(); var Timer = class { initialTimestamp; lastCheckpointTimestamp = null; @@ -123799,9 +125164,10 @@ var Inputs = type({ }); async function main(inputs) { let mcpServerClose; + let payload; try { const timer = new Timer(); - const payload = parsePayload(inputs); + payload = parsePayload(inputs); const partialCtx = await initializeContext(inputs, payload); const ctx = partialCtx; timer.checkpoint("initializeContext"); @@ -123821,19 +125187,24 @@ async function main(inputs) { await validateApiKey(ctx); const result = await runAgent(ctx); const mainResult = await handleAgentResult(result); - await ensureProgressCommentUpdated(); return mainResult; } catch (error41) { const errorMessage = error41 instanceof Error ? error41.message : "Unknown error occurred"; log.error(errorMessage); - await reportErrorToComment({ error: errorMessage }); + try { + await reportErrorToComment({ error: errorMessage }); + } catch { + } await log.writeSummary(); - await ensureProgressCommentUpdated(); return { success: false, error: errorMessage }; } finally { + try { + await ensureProgressCommentUpdated(payload); + } catch { + } if (mcpServerClose) { await mcpServerClose(); } @@ -124070,6 +125441,7 @@ async function handleAgentResult(result) { } // entry.ts +init_cli(); async function run() { if (process.env.GITHUB_WORKSPACE && process.cwd() !== process.env.GITHUB_WORKSPACE) { log.debug(`Changing to GITHUB_WORKSPACE: ${process.env.GITHUB_WORKSPACE}`); diff --git a/main.ts b/main.ts index 6ede00a..40eef6d 100644 --- a/main.ts +++ b/main.ts @@ -52,12 +52,13 @@ export interface MainResult { export async function main(inputs: Inputs): Promise { let mcpServerClose: (() => Promise) | undefined; + let payload: Payload | undefined; try { const timer = new Timer(); // parse payload early to extract agent - const payload = parsePayload(inputs); + payload = parsePayload(inputs); const partialCtx = await initializeContext(inputs, payload); const ctx = partialCtx as MainContext; @@ -86,21 +87,29 @@ export async function main(inputs: Inputs): Promise { const result = await runAgent(ctx); const mainResult = await handleAgentResult(result); - // ensure progress comment is updated if it was never updated during execution - await ensureProgressCommentUpdated(); return mainResult; } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown error occurred"; log.error(errorMessage); - await reportErrorToComment({ error: errorMessage }); + try { + await reportErrorToComment({ error: errorMessage }); + } catch { + // error reporting failed, but don't let it mask the original error + } await log.writeSummary(); - // ensure progress comment is updated if it was never updated during execution - await ensureProgressCommentUpdated(); return { success: false, error: errorMessage, }; } finally { + // ensure progress comment is updated if it was never updated during execution + // do this before revoking the token so we can still make API calls + try { + await ensureProgressCommentUpdated(payload); + } catch { + // error updating comment, but don't let it mask the original error + } + if (mcpServerClose) { await mcpServerClose(); } diff --git a/mcp/comment.ts b/mcp/comment.ts index ae3da2e..77c5394 100644 --- a/mcp/comment.ts +++ b/mcp/comment.ts @@ -1,7 +1,10 @@ +import { Octokit } from "@octokit/rest"; import { type } from "arktype"; +import { LEAPING_INTO_ACTION_PREFIX } from "../../utils/github/leapingComment.ts"; import type { Payload } from "../external.ts"; import { agentsManifest } from "../external.ts"; -import { parseRepoContext } from "../utils/github.ts"; +import { fetchWorkflowRunInfo } from "../utils/api.ts"; +import { getGitHubInstallationToken, parseRepoContext } from "../utils/github.ts"; import { contextualize, getMcpContext, tool } from "./shared.ts"; const PULLFROG_DIVIDER = ""; @@ -178,8 +181,7 @@ export async function reportProgress({ body }: { body: string }): Promise< // no existing comment - create one const issueNumber = ctx.payload.event.issue_number; if (issueNumber === undefined) { - // fail silently - cannot create comment without issue_number - return undefined; + throw new Error("cannot create progress comment: no issue_number found in the payload event"); } const result = await ctx.octokit.rest.issues.createComment({ @@ -209,13 +211,6 @@ export const ReportProgressTool = tool({ execute: contextualize(async ({ body }) => { const result = await reportProgress({ body }); - if (!result) { - return { - success: false, - message: "cannot create progress comment: no issue_number found in the payload event", - }; - } - return { success: true, ...result, @@ -234,39 +229,93 @@ export function wasProgressCommentUpdated(): boolean { * Ensure the progress comment is updated with a generic error message if it was never updated. * This should be called after agent execution completes to handle cases where the agent * exited without ever calling reportProgress. + * + * Works even if MCP context is not initialized (e.g., if error occurs before MCP server starts). + * Will fetch comment ID from database if not available in environment variable. */ -export async function ensureProgressCommentUpdated(): Promise { - // only update if we have a progress comment ID from env var and it was never updated - const existingCommentId = getProgressCommentId(); - if (!existingCommentId || progressCommentWasUpdated) { +export async function ensureProgressCommentUpdated(payload?: Payload): Promise { + // skip if comment was already updated during execution + if (progressCommentWasUpdated) { return; } - // check if MCP context is initialized (MCP server started) + // try to get comment ID from env var first, then from database if needed + let existingCommentId = getProgressCommentId(); + + // if not in env var, try fetching from database using run ID + if (!existingCommentId) { + const runId = process.env.GITHUB_RUN_ID; + if (runId) { + try { + const workflowRunInfo = await fetchWorkflowRunInfo(runId); + if (workflowRunInfo.progressCommentId) { + existingCommentId = parseInt(workflowRunInfo.progressCommentId, 10); + // cache it in env var for future use + if (!Number.isNaN(existingCommentId)) { + process.env.PULLFROG_PROGRESS_COMMENT_ID = workflowRunInfo.progressCommentId; + } + } + } catch { + // database fetch failed, continue without comment ID + } + } + } + + // if still no comment ID, nothing to update + if (!existingCommentId) { + return; + } + + // check if comment still says "leaping into action" - if it's been updated with an error, don't overwrite it + const repoContext = parseRepoContext(); + const token = getGitHubInstallationToken(); + const octokit = new Octokit({ auth: token }); + + try { + const existingComment = await octokit.rest.issues.getComment({ + owner: repoContext.owner, + repo: repoContext.name, + comment_id: existingCommentId, + }); + + const commentBody = existingComment.data.body || ""; + // if comment doesn't start with the leaping prefix, it's already been updated with an error or progress + if (!commentBody.startsWith(LEAPING_INTO_ACTION_PREFIX)) { + return; + } + } catch { + // can't fetch comment, skip update + return; + } + + // try to get payload from MCP context if available, otherwise use provided payload + let resolvedPayload: Payload | undefined; try { const ctx = getMcpContext(); - const repoContext = parseRepoContext(); - const runId = process.env.GITHUB_RUN_ID; - const workflowRunLink = runId - ? `[workflow](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})` - : "workflow"; + resolvedPayload = ctx.payload; + } catch { + // MCP context not initialized, use provided payload + resolvedPayload = payload; + } - const errorMessage = `❌ this run croaked + const runId = process.env.GITHUB_RUN_ID; + const workflowRunLink = runId + ? `[workflow](https://github.com/${repoContext.owner}/${repoContext.name}/actions/runs/${runId})` + : "workflow"; + + const errorMessage = `❌ this run croaked The workflow encountered an error before any progress could be reported. Please check the ${workflowRunLink} for details.`; - const bodyWithFooter = addFooter(errorMessage, ctx.payload); + // add footer if we have payload, otherwise use plain message + const body = resolvedPayload ? addFooter(errorMessage, resolvedPayload) : errorMessage; - await ctx.octokit.rest.issues.updateComment({ - owner: ctx.owner, - repo: ctx.name, - comment_id: existingCommentId, - body: bodyWithFooter, - }); - } catch { - // fail silently - MCP context not initialized or other error - // don't want to fail the workflow if we can't update the comment - } + await octokit.rest.issues.updateComment({ + owner: repoContext.owner, + repo: repoContext.name, + comment_id: existingCommentId, + body, + }); } export const ReplyToReviewComment = type({ diff --git a/package.json b/package.json index c4250e0..5ae7d66 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pullfrog/action", - "version": "0.0.130", + "version": "0.0.131", "type": "module", "files": [ "index.js", diff --git a/utils/errorReport.ts b/utils/errorReport.ts index a2b3f95..8ac55f6 100644 --- a/utils/errorReport.ts +++ b/utils/errorReport.ts @@ -1,24 +1,21 @@ -import { reportProgress } from "../mcp/comment.ts"; -import { getMcpContext } from "../mcp/shared.ts"; -import { log } from "./cli.ts"; +import { Octokit } from "@octokit/rest"; +import { fetchWorkflowRunInfo } from "./api.ts"; +import { getGitHubInstallationToken, parseRepoContext } from "./github.ts"; /** - * Check if MCP context is initialized (i.e., MCP server has started) + * Get progress comment ID from environment variable or database. */ -function isMcpContextInitialized(): boolean { - try { - getMcpContext(); - return true; - } catch { - return false; +function getProgressCommentIdFromEnv(): number | null { + const envCommentId = process.env.PULLFROG_PROGRESS_COMMENT_ID; + if (envCommentId) { + const parsed = parseInt(envCommentId, 10); + if (!Number.isNaN(parsed)) { + return parsed; + } } + return null; } -/** - * Report an error to the GitHub working comment. - * Formats the error message for GitHub markdown and updates the progress comment. - * Handles failures gracefully - logs but doesn't throw. - */ export async function reportErrorToComment({ error, title, @@ -26,18 +23,52 @@ export async function reportErrorToComment({ error: string; title?: string; }): Promise { - // only report if MCP context is initialized (MCP server has started) - if (!isMcpContextInitialized()) { - log.debug("skipping error comment update: MCP context not initialized"); - return; + const formattedError = title ? `${title}\n\n${error}` : `❌ ${error}`; + + // try to get comment ID from env var first, then from database if needed + let commentId = getProgressCommentIdFromEnv(); + + // if not in env var, try fetching from database using run ID + if (!commentId) { + const runId = process.env.GITHUB_RUN_ID; + if (runId) { + try { + const workflowRunInfo = await fetchWorkflowRunInfo(runId); + if (workflowRunInfo.progressCommentId) { + const parsed = parseInt(workflowRunInfo.progressCommentId, 10); + if (!Number.isNaN(parsed)) { + commentId = parsed; + // cache it in env var for future use + process.env.PULLFROG_PROGRESS_COMMENT_ID = workflowRunInfo.progressCommentId; + } + } + } catch { + // database fetch failed, continue without comment ID + } + } } - try { - const formattedError = title ? `${title}\n\n${error}` : `❌ ${error}`; - await reportProgress({ body: formattedError }); - } catch (reportError) { - // log but don't throw - we don't want error reporting to fail the workflow - const errorMessage = reportError instanceof Error ? reportError.message : String(reportError); - log.warning(`failed to report error to comment: ${errorMessage}`); + // if no comment ID available, try using reportProgress (requires MCP context) + if (!commentId) { + try { + const { reportProgress } = await import("../mcp/comment.ts"); + await reportProgress({ body: formattedError }); + return; + } catch { + // MCP context not available, can't create/update comment + return; + } } + + // update comment directly using GitHub API + const repoContext = parseRepoContext(); + const token = getGitHubInstallationToken(); + const octokit = new Octokit({ auth: token }); + + await octokit.rest.issues.updateComment({ + owner: repoContext.owner, + repo: repoContext.name, + comment_id: commentId, + body: formattedError, + }); }