{"version":3,"sources":["/Users/erunion/code/readme/oas/packages/parser/dist/index.cjs","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/convert-path-to-posix.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/is-windows.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/url.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/errors.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/schema-resources.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/pointer.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/ref.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/refs.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/plugins.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/parse.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/parsers/json.js","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/str.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/null_core.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/null_json.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/null_yaml11.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/bool_core.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/bool_json.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/bool_yaml11.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/int_core.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/int_json.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/int_yaml11.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/float_core.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/float_json.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/float_yaml11.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/merge.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/binary.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/scalar/timestamp.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/sequence/seq.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/common/object.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/sequence/omap.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/sequence/pairs.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/mapping/map.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/mapping/set.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/schema.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/mapping/real_map.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/tag/mapping/legacy_map.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/common/snippet.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/common/exception.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/parser/parser_scalar.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/common/tagname.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/parser/constructor.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/parser/parser.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/load.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/ast/presenter.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/node_modules/js-yaml/src/dump.ts","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/parsers/yaml.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/parsers/text.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/parsers/binary.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/resolvers/file.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/resolvers/http.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/options.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/normalize-args.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/resolve-external.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/bundle.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/dereference.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/next.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/util/maybe.js","../../../node_modules/@apidevtools/json-schema-ref-parser/dist/lib/index.js","../src/lib/index.ts","../src/repair.ts","../src/util.ts","../src/validators/schema.ts","../src/lib/hasInvalidPaths.ts","../src/lib/reduceAjvErrors.ts","../src/validators/spec/index.ts","../src/validators/spec/openapi.ts","../src/validators/spec/swagger.ts","../src/validators/spec.ts","../src/index.ts"],"names":["openapi","parse","date","strTag","merge","value"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACRA,IAAM,SAAA,EAAW,IAAA;AACF,SAAR,kBAAA,CAAoC,QAAA,EAAU;AACjD,EAAA,MAAM,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AA;AAK0D,EAAA;AAC9B,EAAA;AACnB,IAAA;AACT,EAAA;AAMgD,EAAA;AAC7B,EAAA;AACoB,IAAA;AACuB,MAAA;AAC5D,IAAA;AACO,IAAA;AACT,EAAA;AAE4B,EAAA;AACO,IAAA;AAEa,MAAA;AACL,IAAA;AAE7B,MAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AAG0C,EAAA;AAEL,EAAA;AACuB,IAAA;AAC5D,EAAA;AAEO,EAAA;AACT;AAOgE;AACrB,EAAA;AACC,EAAA;AAE2B,EAAA;AAEzC,EAAA;AACA,IAAA;AAC6B,MAAA;AACvD,IAAA;AACF,EAAA;AAE4B,EAAA;AAC0B,IAAA;AACS,MAAA;AAC7D,IAAA;AAEyD,IAAA;AAC3D,EAAA;AAE2D,EAAA;AACjD,IAAA;AACuC,MAAA;AAC/C,IAAA;AACF,EAAA;AAE0B,EAAA;AAC5B;AtE2gMiE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/erunion/code/readme/oas/packages/parser/dist/index.cjs","sourcesContent":[null,"const win32Sep = \"\\\\\";\nexport default function convertPathToPosix(filePath) {\n    const isExtendedLengthPath = filePath.startsWith(\"\\\\\\\\?\\\\\");\n    if (isExtendedLengthPath) {\n        return filePath;\n    }\n    return filePath.split(win32Sep).join(\"/\");\n}\n","const isWindowsConst = /^win/.test(globalThis.process ? globalThis.process.platform : \"\");\nexport const isWindows = () => isWindowsConst;\n","import convertPathToPosix from \"./convert-path-to-posix.js\";\nconst forwardSlashPattern = /\\//g;\nconst protocolPattern = /^(\\w{2,}):\\/\\//i;\nconst jsonPointerSlash = /~1/g;\nconst jsonPointerTilde = /~0/g;\nimport { isWindows } from \"./is-windows.js\";\nconst isAbsoluteWin32Path = /^[a-zA-Z]:[\\\\/]/;\n// RegExp patterns to URL-encode special characters in local filesystem paths\nconst urlEncodePatterns = [\n    [/\\?/g, \"%3F\"],\n    [/#/g, \"%23\"],\n];\n// RegExp patterns to URL-decode special characters for local filesystem paths\nconst urlDecodePatterns = [/%23/g, \"#\", /%24/g, \"$\", /%26/g, \"&\", /%2C/g, \",\", /%40/g, \"@\"];\nconst unsafeDomainSuffixes = [\".localhost\", \".local\", \".internal\", \".intranet\", \".corp\", \".home\", \".lan\"];\nexport const parse = (u) => new URL(u);\n/**\n * Returns resolved target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.\n *\n * @returns\n */\nexport function resolve(from, to) {\n    // we use a non-existent URL to check if its a relative URL\n    const fromUrl = new URL(convertPathToPosix(from), \"https://aaa.nonexistanturl.com\");\n    const resolvedUrl = new URL(convertPathToPosix(to), fromUrl);\n    const endSpaces = to.match(/(\\s*)$/)?.[1] || \"\";\n    if (resolvedUrl.hostname === \"aaa.nonexistanturl.com\") {\n        // `from` is a relative URL.\n        const { pathname, search, hash } = resolvedUrl;\n        return pathname + search + safeDecodeURIComponent(hash) + endSpaces;\n    }\n    const resolved = resolvedUrl.toString() + endSpaces;\n    // if there is a #, we want to split on the first one only, and decode the part after\n    if (resolved.includes(\"#\")) {\n        const [base, hash] = resolved.split(\"#\", 2);\n        return base + \"#\" + safeDecodeURIComponent(hash || \"\");\n    }\n    return resolved;\n}\nfunction safeDecodeURIComponent(value) {\n    try {\n        return decodeURIComponent(value);\n    }\n    catch {\n        try {\n            // Preserve literal or malformed percent signs while continuing to decode\n            // any valid percent-encoded characters in the same fragment.\n            return decodeURIComponent(value.replace(/%(?![\\dA-F]{2})/gi, \"%25\"));\n        }\n        catch {\n            return value;\n        }\n    }\n}\n/**\n * Returns the current working directory (in Node) or the current page URL (in browsers).\n *\n * @returns\n */\nexport function cwd() {\n    if (typeof window !== \"undefined\" && window.location && window.location.href) {\n        const href = window.location.href;\n        if (!href || !href.startsWith(\"http\")) {\n            // try parsing as url, and if it fails, return root url /\n            try {\n                new URL(href);\n                return href;\n            }\n            catch {\n                return \"/\";\n            }\n        }\n        return href;\n    }\n    if (typeof process !== \"undefined\" && process.cwd) {\n        const path = process.cwd();\n        const lastChar = path.slice(-1);\n        if (lastChar === \"/\" || lastChar === \"\\\\\") {\n            return path;\n        }\n        else {\n            return path + \"/\";\n        }\n    }\n    return \"/\";\n}\n/**\n * Returns the protocol of the given URL, or `undefined` if it has no protocol.\n *\n * @param path\n * @returns\n */\nexport function getProtocol(path) {\n    const match = protocolPattern.exec(path || \"\");\n    if (match) {\n        return match[1].toLowerCase();\n    }\n    return undefined;\n}\n/**\n * Returns the lowercased file extension of the given URL,\n * or an empty string if it has no extension.\n *\n * @param path\n * @returns\n */\nexport function getExtension(path) {\n    const pathEnd = path.search(/[?#]/);\n    const pathname = pathEnd >= 0 ? path.substring(0, pathEnd) : path;\n    const lastSlash = Math.max(pathname.lastIndexOf(\"/\"), pathname.lastIndexOf(\"\\\\\"));\n    const lastDot = pathname.lastIndexOf(\".\");\n    if (lastDot > lastSlash) {\n        return pathname.substring(lastDot).toLowerCase();\n    }\n    return \"\";\n}\n/**\n * Removes the query, if any, from the given path.\n *\n * @param path\n * @returns\n */\nexport function stripQuery(path) {\n    const queryIndex = path.indexOf(\"?\");\n    if (queryIndex >= 0) {\n        path = path.substring(0, queryIndex);\n    }\n    return path;\n}\n/**\n * Returns the hash (URL fragment), of the given path.\n * If there is no hash, then the root hash (\"#\") is returned.\n *\n * @param path\n * @returns\n */\nexport function getHash(path) {\n    if (!path) {\n        return \"#\";\n    }\n    const hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n        return path.substring(hashIndex);\n    }\n    return \"#\";\n}\n/**\n * Removes the hash (URL fragment), if any, from the given path.\n *\n * @param path\n * @returns\n */\nexport function stripHash(path) {\n    if (!path) {\n        return \"\";\n    }\n    const hashIndex = path.indexOf(\"#\");\n    if (hashIndex >= 0) {\n        path = path.substring(0, hashIndex);\n    }\n    return path;\n}\n/**\n * Determines whether the given path is an HTTP(S) URL.\n *\n * @param path\n * @returns\n */\nexport function isHttp(path) {\n    const protocol = getProtocol(path);\n    if (protocol === \"http\" || protocol === \"https\") {\n        return true;\n    }\n    else if (protocol === undefined) {\n        // There is no protocol.  If we're running in a browser, then assume it's HTTP.\n        return typeof window !== \"undefined\";\n    }\n    else {\n        // It's some other protocol, such as \"ftp://\", \"mongodb://\", etc.\n        return false;\n    }\n}\n/**\n * Determines whether the given url is an unsafe or internal url.\n *\n * @param path - The URL or path to check\n * @returns true if the URL is unsafe/internal, false otherwise\n */\nexport function isUnsafeUrl(path) {\n    if (!path || typeof path !== \"string\") {\n        return true;\n    }\n    // Trim whitespace and convert to lowercase for comparison\n    const normalizedPath = path.trim().toLowerCase();\n    // Empty or just whitespace\n    if (!normalizedPath) {\n        return true;\n    }\n    // JavaScript protocols\n    if (normalizedPath.startsWith(\"javascript:\") ||\n        normalizedPath.startsWith(\"vbscript:\") ||\n        normalizedPath.startsWith(\"data:\")) {\n        return true;\n    }\n    // File protocol\n    if (normalizedPath.startsWith(\"file:\")) {\n        return true;\n    }\n    // if we're in the browser, we assume that it is safe\n    if (typeof window !== \"undefined\" && window.location && window.location.href) {\n        return false;\n    }\n    try {\n        // Try to parse as URL\n        const url = new URL(normalizedPath.startsWith(\"//\") ? \"http:\" + normalizedPath : normalizedPath);\n        if (isUnsafeHostname(url.hostname)) {\n            return true;\n        }\n        // Check for non-standard ports that might indicate internal services\n        const port = url.port;\n        if (port && isInternalPort(parseInt(port))) {\n            return true;\n        }\n    }\n    catch {\n        // If URL parsing fails, check if it's a relative path or contains suspicious patterns\n        // Relative paths starting with / are generally safe for same-origin\n        if (normalizedPath.startsWith(\"/\") && !normalizedPath.startsWith(\"//\")) {\n            return false;\n        }\n        if (containsUnsafeHostname(normalizedPath)) {\n            return true;\n        }\n    }\n    return false;\n}\n/**\n * Checks a URL and, in Node.js, returns the exact public addresses that were\n * validated. Callers that perform the request must pin their connection to\n * these addresses; resolving the hostname again would reintroduce a DNS\n * rebinding race between validation and connection establishment.\n */\nexport async function resolveUrlSafety(path) {\n    if (isUnsafeUrl(path)) {\n        return { unsafe: true };\n    }\n    if (typeof path !== \"string\" ||\n        typeof process === \"undefined\" ||\n        !process.versions?.node ||\n        typeof window !== \"undefined\") {\n        return { unsafe: false };\n    }\n    const parsedUrl = new URL(path.startsWith(\"//\") ? `http:${path}` : path);\n    if (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") {\n        return { unsafe: false };\n    }\n    // Keep the Node-only dependency out of browser module graphs. The import is\n    // never evaluated outside Node.js.\n    const dnsModuleName = \"node:dns/promises\";\n    const dns = (await import(dnsModuleName));\n    const addresses = await dns.lookup(normalizeHostname(parsedUrl.hostname), {\n        all: true,\n        verbatim: true,\n    });\n    if (addresses.length === 0 || addresses.some(({ address }) => isUnsafeHostname(address))) {\n        return { unsafe: true };\n    }\n    return { unsafe: false, addresses };\n}\nexport async function isUnsafeUrlWithDns(path) {\n    return (await resolveUrlSafety(path)).unsafe;\n}\n/**\n * Helper function to check if a hostname is local or resolves to a non-public literal address.\n */\nfunction isUnsafeHostname(hostname) {\n    const normalizedHostname = normalizeHostname(hostname);\n    if (!normalizedHostname) {\n        return true;\n    }\n    if (normalizedHostname === \"localhost\" ||\n        unsafeDomainSuffixes.some((suffix) => normalizedHostname.endsWith(suffix))) {\n        return true;\n    }\n    const ipv4 = parseIPv4Address(normalizedHostname);\n    if (ipv4) {\n        return isUnsafeIPv4Address(ipv4);\n    }\n    const ipv6 = parseIPv6Address(normalizedHostname);\n    if (ipv6) {\n        return isUnsafeIPv6Address(ipv6);\n    }\n    return false;\n}\nfunction normalizeHostname(hostname) {\n    let normalizedHostname = hostname.trim().toLowerCase();\n    if (normalizedHostname.startsWith(\"[\") && normalizedHostname.endsWith(\"]\")) {\n        normalizedHostname = normalizedHostname.slice(1, -1);\n    }\n    while (normalizedHostname.endsWith(\".\")) {\n        normalizedHostname = normalizedHostname.slice(0, -1);\n    }\n    return normalizedHostname;\n}\nfunction parseIPv4Address(ip) {\n    const parts = ip.split(\".\");\n    if (parts.length !== 4) {\n        return undefined;\n    }\n    const octets = parts.map((part) => {\n        if (!/^\\d+$/.test(part)) {\n            return Number.NaN;\n        }\n        return Number(part);\n    });\n    if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {\n        return undefined;\n    }\n    return octets;\n}\n/**\n * Helper function to check if an IPv4 address is in a non-public range.\n */\nfunction isUnsafeIPv4Address([a, b, c, d]) {\n    return (a === 0 ||\n        a === 10 ||\n        a === 127 ||\n        (a === 100 && b >= 64 && b <= 127) ||\n        (a === 169 && b === 254) ||\n        (a === 172 && b >= 16 && b <= 31) ||\n        (a === 192 && b === 0 && c === 0) ||\n        (a === 192 && b === 168) ||\n        (a === 198 && (b === 18 || b === 19)) ||\n        a >= 224 ||\n        (a === 255 && b === 255 && c === 255 && d === 255));\n}\nfunction parseIPv6Address(ip) {\n    if (!ip.includes(\":\")) {\n        return undefined;\n    }\n    let normalizedIP = ip;\n    const lastSeparator = normalizedIP.lastIndexOf(\":\");\n    const possibleIPv4 = normalizedIP.slice(lastSeparator + 1);\n    if (possibleIPv4.includes(\".\")) {\n        const ipv4 = parseIPv4Address(possibleIPv4);\n        if (!ipv4) {\n            return undefined;\n        }\n        const firstGroup = ipv4[0] * 256 + ipv4[1];\n        const secondGroup = ipv4[2] * 256 + ipv4[3];\n        normalizedIP = `${normalizedIP.slice(0, lastSeparator + 1)}${firstGroup.toString(16)}:${secondGroup.toString(16)}`;\n    }\n    const halves = normalizedIP.split(\"::\");\n    if (halves.length > 2) {\n        return undefined;\n    }\n    const head = parseIPv6Groups(halves[0]);\n    const tail = halves.length === 2 ? parseIPv6Groups(halves[1]) : [];\n    if (!head || !tail) {\n        return undefined;\n    }\n    if (halves.length === 1) {\n        return head.length === 8 ? head : undefined;\n    }\n    const missingGroups = 8 - head.length - tail.length;\n    if (missingGroups < 1) {\n        return undefined;\n    }\n    return [...head, ...Array(missingGroups).fill(0), ...tail];\n}\nfunction parseIPv6Groups(groups) {\n    if (!groups) {\n        return [];\n    }\n    const parsedGroups = groups.split(\":\").map((group) => {\n        if (!/^[\\da-f]{1,4}$/i.test(group)) {\n            return Number.NaN;\n        }\n        return Number.parseInt(group, 16);\n    });\n    if (parsedGroups.some((group) => !Number.isInteger(group) || group < 0 || group > 0xffff)) {\n        return undefined;\n    }\n    return parsedGroups;\n}\n/**\n * Helper function to check if an IPv6 address is in a non-public range.\n */\nfunction isUnsafeIPv6Address(groups) {\n    if (groups.length !== 8) {\n        return false;\n    }\n    const isUnspecified = groups.every((group) => group === 0);\n    const isLoopback = groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1;\n    const isUniqueLocal = (groups[0] & 0xfe00) === 0xfc00;\n    const isLinkLocal = (groups[0] & 0xffc0) === 0xfe80;\n    const isMulticast = (groups[0] & 0xff00) === 0xff00;\n    if (isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isMulticast) {\n        return true;\n    }\n    const mappedIPv4 = getMappedIPv4Address(groups);\n    return mappedIPv4 ? isUnsafeIPv4Address(mappedIPv4) : false;\n}\nfunction getMappedIPv4Address(groups) {\n    const firstFiveGroupsAreZero = groups.slice(0, 5).every((group) => group === 0);\n    const firstSixGroupsAreZero = firstFiveGroupsAreZero && groups[5] === 0;\n    const isIPv4Mapped = firstFiveGroupsAreZero && groups[5] === 0xffff;\n    if (!firstSixGroupsAreZero && !isIPv4Mapped) {\n        return undefined;\n    }\n    return [Math.floor(groups[6] / 256), groups[6] % 256, Math.floor(groups[7] / 256), groups[7] % 256];\n}\nfunction containsUnsafeHostname(value) {\n    const candidates = value\n        .split(/[\\s/?#]+/)\n        .map((candidate) => candidate.replace(/^[a-z][\\d+.a-z-]*:\\/\\//i, \"\").replace(/:\\d+$/, \"\"))\n        .filter(Boolean);\n    return candidates.some((candidate) => isUnsafeHostname(candidate));\n}\n/**\n * Helper function to check if a port is typically used for internal services\n */\nfunction isInternalPort(port) {\n    const internalPorts = [\n        22, // SSH\n        23, // Telnet\n        25, // SMTP\n        53, // DNS\n        135, // RPC\n        139, // NetBIOS\n        445, // SMB\n        993, // IMAPS\n        995, // POP3S\n        1433, // SQL Server\n        1521, // Oracle\n        3306, // MySQL\n        3389, // RDP\n        5432, // PostgreSQL\n        5900, // VNC\n        6379, // Redis\n        8080, // Common internal web\n        8443, // Common internal HTTPS\n        9200, // Elasticsearch\n        27017, // MongoDB\n    ];\n    return internalPorts.includes(port);\n}\n/**\n * Determines whether the given path is a filesystem path.\n * This includes \"file://\" URLs.\n *\n * @param path\n * @returns\n */\nexport function isFileSystemPath(path) {\n    // @ts-ignore\n    if (typeof window !== \"undefined\" || (typeof process !== \"undefined\" && process.browser)) {\n        // We're running in a browser, so assume that all paths are URLs.\n        // This way, even relative paths will be treated as URLs rather than as filesystem paths\n        return false;\n    }\n    const protocol = getProtocol(path);\n    return protocol === undefined || protocol === \"file\";\n}\n/**\n * Converts a filesystem path to a properly-encoded URL.\n *\n * This is intended to handle situations where JSON Schema $Ref Parser is called\n * with a filesystem path that contains characters which are not allowed in URLs.\n *\n * @example\n * The following filesystem paths would be converted to the following URLs:\n *\n *    <\"!@#$%^&*+=?'>.json              ==>   %3C%22!@%23$%25%5E&*+=%3F\\'%3E.json\n *    C:\\\\My Documents\\\\File (1).json   ==>   C:/My%20Documents/File%20(1).json\n *    file://Project #42/file.json      ==>   file://Project%20%2342/file.json\n *\n * @param path\n * @returns\n */\nexport function fromFileSystemPath(path) {\n    // Step 1: On Windows, replace backslashes with forward slashes,\n    // rather than encoding them as \"%5C\"\n    if (isWindows()) {\n        const projectDir = cwd();\n        const upperPath = path.toUpperCase();\n        const projectDirPosixPath = convertPathToPosix(projectDir);\n        const posixUpper = projectDirPosixPath.toUpperCase();\n        const hasProjectDir = upperPath.includes(posixUpper);\n        const hasProjectUri = upperPath.includes(posixUpper);\n        const isAbsolutePath = isAbsoluteWin32Path.test(path) ||\n            path.startsWith(\"http://\") ||\n            path.startsWith(\"https://\") ||\n            path.startsWith(\"file://\");\n        if (!(hasProjectDir || hasProjectUri || isAbsolutePath) && !projectDir.startsWith(\"http\")) {\n            const join = (a, b) => {\n                if (a.endsWith(\"/\") || a.endsWith(\"\\\\\")) {\n                    return a + b;\n                }\n                else {\n                    return a + \"/\" + b;\n                }\n            };\n            path = join(projectDir, path);\n        }\n        path = convertPathToPosix(path);\n    }\n    // Step 2: `encodeURI` will take care of MOST characters\n    path = encodeURI(path);\n    // Step 3: Manually encode characters that are not encoded by `encodeURI`.\n    // This includes characters such as \"#\" and \"?\", which have special meaning in URLs,\n    // but are just normal characters in a filesystem path.\n    for (const pattern of urlEncodePatterns) {\n        path = path.replace(pattern[0], pattern[1]);\n    }\n    return path;\n}\n/**\n * Converts a URL to a local filesystem path.\n */\nexport function toFileSystemPath(path, keepFileProtocol) {\n    // Bare \"%\" characters are valid in filesystem paths, but they make `decodeURI` throw.\n    // Escape only the non-encoded ones so percent-encoded sequences still decode normally.\n    path = path.replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\");\n    // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc.\n    path = decodeURI(path);\n    // Step 2: Manually decode characters that are not decoded by `decodeURI`.\n    // This includes characters such as \"#\" and \"?\", which have special meaning in URLs,\n    // but are just normal characters in a filesystem path.\n    for (let i = 0; i < urlDecodePatterns.length; i += 2) {\n        path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]);\n    }\n    // Step 3: If it's a \"file://\" URL, then format it consistently\n    // or convert it to a local filesystem path\n    let isFileUrl = path.toLowerCase().startsWith(\"file://\");\n    if (isFileUrl) {\n        // Strip-off the protocol, and the initial \"/\", if there is one\n        path = path.replace(/^file:\\/\\//i, \"\").replace(/^\\//, \"\");\n        // insert a colon (\":\") after the drive letter on Windows\n        if (isWindows() && path[1] === \"/\") {\n            path = `${path[0]}:${path.substring(1)}`;\n        }\n        if (keepFileProtocol) {\n            // Return the consistently-formatted \"file://\" URL\n            path = \"file:///\" + path;\n        }\n        else {\n            // Convert the \"file://\" URL to a local filesystem path.\n            // On Windows, it will start with something like \"C:/\".\n            // On Posix, it will start with \"/\"\n            isFileUrl = false;\n            path = isWindows() ? path : \"/\" + path;\n        }\n    }\n    // Step 4: Normalize Windows paths (unless it's a \"file://\" URL)\n    if (isWindows() && !isFileUrl) {\n        // Replace forward slashes with backslashes\n        path = path.replace(forwardSlashPattern, \"\\\\\");\n        // Capitalize the drive letter\n        if (path.match(/^[a-z]:\\\\/i)) {\n            path = path[0].toUpperCase() + path.substring(1);\n        }\n    }\n    return path;\n}\n/**\n * Converts a $ref pointer to a valid JSON Path.\n *\n * @param pointer\n * @returns\n */\nexport function safePointerToPath(pointer) {\n    if (pointer.length <= 1 || pointer[0] !== \"#\" || pointer[1] !== \"/\") {\n        return [];\n    }\n    return pointer\n        .slice(2)\n        .split(\"/\")\n        .map((value) => {\n        return value.replace(jsonPointerSlash, \"/\").replace(jsonPointerTilde, \"~\");\n    });\n}\n","import { getHash, stripHash, toFileSystemPath } from \"./url.js\";\nconst nonJsonTypes = [\"function\", \"symbol\", \"undefined\"];\nconst protectedProps = [\"constructor\", \"prototype\", \"__proto__\"];\nconst objectPrototype = Object.getPrototypeOf({});\n/**\n * Custom JSON serializer for Error objects.\n * Returns all built-in error properties, as well as extended properties.\n */\nexport function toJSON() {\n    // HACK: We have to cast the objects to `any` so we can use symbol indexers.\n    // see https://github.com/Microsoft/TypeScript/issues/1863\n    const pojo = {};\n    const error = this;\n    for (const key of getDeepKeys(error)) {\n        if (typeof key === \"string\") {\n            const value = error[key];\n            const type = typeof value;\n            if (!nonJsonTypes.includes(type)) {\n                pojo[key] = value;\n            }\n        }\n    }\n    return pojo;\n}\n/**\n * Returns own, inherited, enumerable, non-enumerable, string, and symbol keys of `obj`.\n * Does NOT return members of the base Object prototype, or the specified omitted keys.\n */\nexport function getDeepKeys(obj, omit = []) {\n    let keys = [];\n    // Crawl the prototype chain, finding all the string and symbol keys\n    while (obj && obj !== objectPrototype) {\n        keys = keys.concat(Object.getOwnPropertyNames(obj), Object.getOwnPropertySymbols(obj));\n        obj = Object.getPrototypeOf(obj);\n    }\n    // De-duplicate the list of keys\n    const uniqueKeys = new Set(keys);\n    // Remove any omitted keys\n    for (const key of omit.concat(protectedProps)) {\n        uniqueKeys.delete(key);\n    }\n    return uniqueKeys;\n}\nexport class JSONParserError extends Error {\n    name;\n    message;\n    source;\n    path;\n    code;\n    constructor(message, source) {\n        super();\n        this.code = \"EUNKNOWN\";\n        this.name = \"JSONParserError\";\n        this.message = message;\n        this.source = source;\n        this.path = null;\n    }\n    toJSON = toJSON.bind(this);\n    get footprint() {\n        return `${this.path}+${this.source}+${this.code}+${this.message}`;\n    }\n}\nexport class JSONParserErrorGroup extends Error {\n    files;\n    constructor(parser) {\n        super();\n        this.files = parser;\n        this.name = \"JSONParserErrorGroup\";\n        this.message = `${this.errors.length} error${this.errors.length > 1 ? \"s\" : \"\"} occurred while reading '${toFileSystemPath(parser.$refs._root$Ref.path)}'`;\n    }\n    toJSON = toJSON.bind(this);\n    static getParserErrors(parser) {\n        const errors = [];\n        const footprints = new Set();\n        const refs = [\n            ...Object.values(parser.$refs._$refs),\n            ...Object.values(parser.$refs._aliases),\n        ];\n        for (const $ref of refs) {\n            if ($ref.errors) {\n                for (const error of $ref.errors) {\n                    if (!footprints.has(error.footprint)) {\n                        footprints.add(error.footprint);\n                        errors.push(error);\n                    }\n                }\n            }\n        }\n        return errors;\n    }\n    get errors() {\n        return JSONParserErrorGroup.getParserErrors(this.files);\n    }\n}\nexport class ParserError extends JSONParserError {\n    code = \"EPARSER\";\n    name = \"ParserError\";\n    constructor(message, source) {\n        super(`Error parsing ${source}: ${message}`, source);\n    }\n}\nexport class UnmatchedParserError extends JSONParserError {\n    code = \"EUNMATCHEDPARSER\";\n    name = \"UnmatchedParserError\";\n    constructor(source) {\n        super(`Could not find parser for \"${source}\"`, source);\n    }\n}\nexport class ResolverError extends JSONParserError {\n    code = \"ERESOLVER\";\n    name = \"ResolverError\";\n    ioErrorCode;\n    constructor(ex, source) {\n        super(ex.message || `Error reading file \"${source}\"`, source);\n        if (\"code\" in ex) {\n            this.ioErrorCode = String(ex.code);\n        }\n    }\n}\nexport class UnmatchedResolverError extends JSONParserError {\n    code = \"EUNMATCHEDRESOLVER\";\n    name = \"UnmatchedResolverError\";\n    constructor(source) {\n        super(`Could not find resolver for \"${source}\"`, source);\n    }\n}\nexport class MissingPointerError extends JSONParserError {\n    code = \"EMISSINGPOINTER\";\n    name = \"MissingPointerError\";\n    targetToken;\n    targetRef;\n    targetFound;\n    parentPath;\n    constructor(token, path, targetRef, targetFound, parentPath) {\n        super(`Missing $ref pointer \"${getHash(path)}\". Token \"${token}\" does not exist.`, stripHash(path));\n        this.targetToken = token;\n        this.targetRef = targetRef;\n        this.targetFound = targetFound;\n        this.parentPath = parentPath;\n    }\n}\nexport class TimeoutError extends JSONParserError {\n    code = \"ETIMEOUT\";\n    name = \"TimeoutError\";\n    constructor(timeout) {\n        super(`Dereferencing timeout reached: ${timeout}ms`);\n    }\n}\nexport class InvalidPointerError extends JSONParserError {\n    code = \"EINVALIDPOINTER\";\n    name = \"InvalidPointerError\";\n    constructor(pointer, path) {\n        super(`Invalid $ref pointer \"${pointer}\". Pointers must begin with \"#/\"`, stripHash(path));\n    }\n}\nexport function isHandledError(err) {\n    return err instanceof JSONParserError || err instanceof JSONParserErrorGroup;\n}\nexport function normalizeError(err) {\n    if (err.path === null) {\n        err.path = [];\n    }\n    return err;\n}\n","import * as url from \"./url.js\";\nexport function getSchemaBasePath(basePath, value, legacyId = false) {\n    const schemaId = getSchemaId(value, legacyId);\n    return schemaId ? url.resolve(basePath, schemaId) : basePath;\n}\nexport function usesDynamicIdScope(value) {\n    if (!value || typeof value !== \"object\" || ArrayBuffer.isView(value)) {\n        return false;\n    }\n    // A schema can omit `$schema`, but an explicit identifier still establishes\n    // a base URI for references inside that resource.\n    if (getSchemaId(value)) {\n        return true;\n    }\n    const schema = value.$schema;\n    if (typeof schema === \"string\" &&\n        (schema.includes(\"draft-04/\") ||\n            schema.includes(\"draft-06/\") ||\n            schema.includes(\"draft-07/\") ||\n            schema.includes(\"draft/2019-09/\") ||\n            schema.includes(\"draft/2020-12/\") ||\n            schema.includes(\"oas/3.1/\"))) {\n        return true;\n    }\n    const openapi = value.openapi;\n    return typeof openapi === \"string\" && /^3\\.1(?:\\.|$)/.test(openapi);\n}\nexport function registerSchemaResources($refs, basePath, value, pathType, dynamicIdScope = false) {\n    if (!dynamicIdScope) {\n        return;\n    }\n    const seen = new Set();\n    const visit = (node, scopeBase, inheritedLegacyId) => {\n        if (!node || typeof node !== \"object\" || ArrayBuffer.isView(node) || seen.has(node)) {\n            return;\n        }\n        seen.add(node);\n        const legacyId = getSchemaIdMode(node, inheritedLegacyId);\n        const nextScopeBase = getSchemaBasePath(scopeBase, node, legacyId);\n        if (nextScopeBase !== scopeBase) {\n            $refs._addAlias(nextScopeBase, node, pathType, dynamicIdScope, legacyId);\n        }\n        for (const key of Object.keys(node)) {\n            visit(node[key], nextScopeBase, legacyId);\n        }\n    };\n    visit(value, basePath, false);\n}\nexport function getSchemaId(value, inheritedLegacyId = false) {\n    if (!value || typeof value !== \"object\") {\n        return undefined;\n    }\n    const legacyId = getSchemaIdMode(value, inheritedLegacyId);\n    const schemaId = legacyId ? value.id : value.$id;\n    if (typeof schemaId === \"string\" && schemaId.length > 0) {\n        return schemaId;\n    }\n    return undefined;\n}\nexport function getSchemaIdMode(value, inheritedLegacyId = false) {\n    if (!value || typeof value !== \"object\") {\n        return inheritedLegacyId;\n    }\n    const schema = value.$schema;\n    if (typeof schema === \"string\") {\n        if (schema.includes(\"draft-04/\")) {\n            return true;\n        }\n        if (schema.includes(\"draft-06/\") ||\n            schema.includes(\"draft-07/\") ||\n            schema.includes(\"draft/2019-09/\") ||\n            schema.includes(\"draft/2020-12/\") ||\n            schema.includes(\"oas/3.1/\")) {\n            return false;\n        }\n    }\n    const openapi = value.openapi;\n    if (typeof openapi === \"string\" && /^3\\.1(?:\\.|$)/.test(openapi)) {\n        return false;\n    }\n    return inheritedLegacyId;\n}\n","import $Ref from \"./ref.js\";\nimport * as url from \"./util/url.js\";\nimport { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } from \"./util/errors.js\";\nimport { getSchemaBasePath, getSchemaIdMode } from \"./util/schema-resources.js\";\nexport const nullSymbol = Symbol(\"null\");\nconst slashes = /\\//g;\nconst tildes = /~/g;\nconst escapedSlash = /~1/g;\nconst escapedTilde = /~0/g;\nconst unsafeSetTokens = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n/**\n * This class represents a single JSON pointer and its resolved value.\n *\n * @param $ref\n * @param path\n * @param [friendlyPath] - The original user-specified path (used for error messages)\n * @class\n */\nclass Pointer {\n    /**\n     * The {@link $Ref} object that contains this {@link Pointer} object.\n     */\n    $ref;\n    /**\n     * The file path or URL, containing the JSON pointer in the hash.\n     * This path is relative to the path of the main JSON schema file.\n     */\n    path;\n    /**\n     * The original path or URL, used for error messages.\n     */\n    originalPath;\n    /**\n     * The current base URI used to resolve nested $ref pointers while walking this pointer.\n     */\n    scopeBase;\n    /** Whether the current schema scope uses draft-04's legacy `id` keyword. */\n    legacyIdScope;\n    /**\n     * The value of the JSON pointer.\n     * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).\n     */\n    value;\n    /**\n     * Indicates whether the pointer references itself.\n     */\n    circular;\n    /**\n     * Indicates whether the pointer encountered a cycle elsewhere in its reference chain.\n     */\n    chainCircular;\n    /**\n     * The number of indirect references that were traversed to resolve the value.\n     * Resolving a single pointer may require resolving multiple $Refs.\n     */\n    indirections;\n    constructor($ref, path, friendlyPath) {\n        this.$ref = $ref;\n        this.path = path;\n        this.originalPath = friendlyPath || path;\n        this.scopeBase = $ref.path || url.stripHash(path);\n        this.legacyIdScope = $ref.legacyIdScope;\n        this.value = undefined;\n        this.circular = false;\n        this.chainCircular = false;\n        this.indirections = 0;\n    }\n    /**\n     * Resolves the value of a nested property within the given object.\n     *\n     * @param obj - The object that will be crawled\n     * @param options\n     * @param pathFromRoot - the path of place that initiated resolving\n     *\n     * @returns\n     * Returns a JSON pointer whose {@link Pointer#value} is the resolved value.\n     * If resolving this value required resolving other JSON references, then\n     * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path\n     * of the resolved value.\n     */\n    resolve(obj, options, pathFromRoot, visitedRefPaths = new Set(), resolveFinalReference = true) {\n        const tokens = Pointer.parse(this.path, this.originalPath);\n        const found = [];\n        // Crawl the object, one token at a time\n        this.value = unwrapOrThrow(obj);\n        if (this.$ref.dynamicIdScope && !isAliasedResource(this.$ref)) {\n            this.legacyIdScope = getSchemaIdMode(this.value, this.legacyIdScope);\n            this.scopeBase = getSchemaBasePath(this.scopeBase, this.value, this.legacyIdScope);\n        }\n        for (let i = 0; i < tokens.length; i++) {\n            // During token walking, if the current value is an extended $ref (has sibling keys\n            // alongside $ref, as allowed by JSON Schema 2019-09+), and resolveIf$Ref marks it\n            // as circular because the $ref resolves to the same path we're walking, we should\n            // reset the circular flag and continue walking the object's own properties.\n            // This prevents false circular detection when e.g. a root schema has both\n            // $ref: \"#/$defs/Foo\" and $defs: { Foo: {...} } as siblings.\n            const wasCircular = this.circular;\n            const wasChainCircular = this.chainCircular;\n            const isExtendedRef = $Ref.isExtended$Ref(this.value);\n            if (resolveIf$Ref(this, options, pathFromRoot, visitedRefPaths)) {\n                // The $ref path has changed, so append the remaining tokens to the path\n                this.path = Pointer.join(this.path, tokens.slice(i));\n            }\n            else if (isExtendedRef) {\n                // resolveIf$Ref set circular=true on an extended $ref during token walking.\n                // Since we still have tokens to process, the object should be walked by its\n                // properties, not treated as a circular self-reference.\n                this.circular = wasCircular;\n                this.chainCircular = wasChainCircular;\n            }\n            const token = tokens[i];\n            if (this.value === null || (typeof this.value !== \"object\" && typeof this.value !== \"function\")) {\n                this.value = null;\n                const path = this.$ref.path || \"\";\n                const targetRef = this.path.replace(path, \"\");\n                const targetFound = Pointer.join(\"\", found);\n                const parentPath = pathFromRoot?.replace(path, \"\");\n                throw new MissingPointerError(token, safelyDecodeURI(this.originalPath), targetRef, targetFound, parentPath);\n            }\n            if (this.value[token] === undefined || (this.value[token] === null && i === tokens.length - 1)) {\n                // one final case is if the entry itself includes slashes, and was parsed out as a token - we can join the remaining tokens and try again\n                let didFindSubstringSlashMatch = false;\n                for (let j = tokens.length - 1; j > i; j--) {\n                    const joinedToken = tokens.slice(i, j + 1).join(\"/\");\n                    if (this.value[joinedToken] !== undefined) {\n                        this.value = this.value[joinedToken];\n                        i = j;\n                        didFindSubstringSlashMatch = true;\n                        break;\n                    }\n                }\n                if (didFindSubstringSlashMatch) {\n                    this.chainCircular = wasChainCircular;\n                    continue;\n                }\n                // If the token we're looking for ended up not containing any slashes but is\n                // actually instead pointing to an existing `null` value then we should use that\n                // `null` value.\n                if (token in this.value && this.value[token] === null) {\n                    // We use a `null` symbol for internal tracking to differentiate between a general `null`\n                    // value and our expected `null` value.\n                    this.value = nullSymbol;\n                    this.chainCircular = wasChainCircular;\n                    continue;\n                }\n                this.value = null;\n                const path = this.$ref.path || \"\";\n                const targetRef = this.path.replace(path, \"\");\n                const targetFound = Pointer.join(\"\", found);\n                const parentPath = pathFromRoot?.replace(path, \"\");\n                throw new MissingPointerError(token, safelyDecodeURI(this.originalPath), targetRef, targetFound, parentPath);\n            }\n            else {\n                this.value = this.value[token];\n            }\n            this.chainCircular = wasChainCircular;\n            found.push(token);\n            if (this.$ref.dynamicIdScope) {\n                this.legacyIdScope = getSchemaIdMode(this.value, this.legacyIdScope);\n                this.scopeBase = getSchemaBasePath(this.scopeBase, this.value, this.legacyIdScope);\n            }\n        }\n        // Resolve the final value\n        const finalResolutionBase = this.$ref.dynamicIdScope ? this.scopeBase : this.path;\n        if (resolveFinalReference) {\n            const finalRefPath = this.value?.$ref ? url.resolve(finalResolutionBase, this.value.$ref) : undefined;\n            const canonicalPathFromRoot = typeof pathFromRoot === \"string\" ? url.resolve(this.$ref.$refs._root$Ref.path, pathFromRoot) : pathFromRoot;\n            if ($Ref.isAllowed$Ref(this.value, options) &&\n                finalRefPath === canonicalPathFromRoot &&\n                finalRefPath !== this.path) {\n                this.chainCircular = true;\n            }\n            else if (!this.value || finalRefPath) {\n                resolveIf$Ref(this, options, pathFromRoot, visitedRefPaths);\n            }\n        }\n        return this;\n    }\n    /**\n     * Sets the value of a nested property within the given object.\n     *\n     * @param obj - The object that will be crawled\n     * @param value - the value to assign\n     * @param options\n     *\n     * @returns\n     * Returns the modified object, or an entirely new object if the entire object is overwritten.\n     */\n    set(obj, value, options) {\n        const tokens = Pointer.parse(this.path);\n        let token;\n        if (tokens.length === 0) {\n            // There are no tokens, replace the entire object with the new value\n            this.value = value;\n            return value;\n        }\n        assertSafeSetTokens(this.path, tokens);\n        // Crawl the object, one token at a time\n        this.value = unwrapOrThrow(obj);\n        if (this.$ref.dynamicIdScope && !isAliasedResource(this.$ref)) {\n            this.legacyIdScope = getSchemaIdMode(this.value, this.legacyIdScope);\n            this.scopeBase = getSchemaBasePath(this.scopeBase, this.value, this.legacyIdScope);\n        }\n        for (let i = 0; i < tokens.length - 1; i++) {\n            resolveIf$Ref(this, options);\n            token = tokens[i];\n            if (this.value && this.value[token] !== undefined) {\n                // The token exists\n                this.value = this.value[token];\n            }\n            else {\n                // The token doesn't exist, so create it\n                this.value = setValue(this, token, {});\n            }\n            if (this.$ref.dynamicIdScope) {\n                this.legacyIdScope = getSchemaIdMode(this.value, this.legacyIdScope);\n                this.scopeBase = getSchemaBasePath(this.scopeBase, this.value, this.legacyIdScope);\n            }\n        }\n        // Set the value of the final token\n        resolveIf$Ref(this, options);\n        token = tokens[tokens.length - 1];\n        setValue(this, token, value);\n        // Return the updated object\n        return obj;\n    }\n    /**\n     * Parses a JSON pointer (or a path containing a JSON pointer in the hash)\n     * and returns an array of the pointer's tokens.\n     * (e.g. \"schema.json#/definitions/person/name\" => [\"definitions\", \"person\", \"name\"])\n     *\n     * The pointer is parsed according to RFC 6901\n     * {@link https://tools.ietf.org/html/rfc6901#section-3}\n     *\n     * @param path\n     * @param [originalPath]\n     * @returns\n     */\n    static parse(path, originalPath) {\n        // Get the JSON pointer from the path's hash\n        const pointer = url.getHash(path).substring(1);\n        // If there's no pointer, then there are no tokens,\n        // so return an empty array\n        if (!pointer) {\n            return [];\n        }\n        // Split into an array\n        const split = pointer.split(\"/\");\n        // Decode each part, according to RFC 6901\n        for (let i = 0; i < split.length; i++) {\n            split[i] = split[i].replace(escapedSlash, \"/\").replace(escapedTilde, \"~\");\n        }\n        if (split[0] !== \"\") {\n            throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath);\n        }\n        return split.slice(1);\n    }\n    /**\n     * Creates a JSON pointer path, by joining one or more tokens to a base path.\n     *\n     * @param base - The base path (e.g. \"schema.json#/definitions/person\")\n     * @param tokens - The token(s) to append (e.g. [\"name\", \"first\"])\n     * @returns\n     */\n    static join(base, tokens) {\n        // Ensure that the base path contains a hash\n        if (base.indexOf(\"#\") === -1) {\n            base += \"#\";\n        }\n        // Append each token to the base path\n        tokens = Array.isArray(tokens) ? tokens : [tokens];\n        for (let i = 0; i < tokens.length; i++) {\n            const token = tokens[i];\n            // Encode the token, according to RFC 6901\n            // RFC 6901 only requires encoding ~ as ~0 and / as ~1\n            // We do NOT use encodeURIComponent as it encodes characters like $ which should remain literal\n            base += \"/\" + token.replace(tildes, \"~0\").replace(slashes, \"~1\");\n        }\n        return base;\n    }\n}\nfunction safelyDecodeURI(value) {\n    try {\n        return decodeURI(value);\n    }\n    catch {\n        return value;\n    }\n}\n/**\n * If the given pointer's {@link Pointer#value} is a JSON reference,\n * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value.\n * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the\n * resolution path of the new value.\n *\n * @param pointer\n * @param options\n * @param [pathFromRoot] - the path of place that initiated resolving\n * @returns - Returns `true` if the resolution path changed\n */\nfunction resolveIf$Ref(pointer, options, pathFromRoot, visitedRefPaths = new Set()) {\n    let pathChanged = false;\n    let currentPathFromRoot = pathFromRoot;\n    const addedPaths = [];\n    try {\n        // Pure reference chains can be followed iteratively. Extended refs still use\n        // the existing one-hop behavior because their values must be merged on return.\n        while ($Ref.isAllowed$Ref(pointer.value, options)) {\n            const extended = $Ref.isExtended$Ref(pointer.value);\n            const sourceValue = pointer.value;\n            const parentPath = pointer.path;\n            const resolutionBase = pointer.$ref.dynamicIdScope ? pointer.scopeBase : pointer.path;\n            const $refPath = url.resolve(resolutionBase, pointer.value.$ref);\n            if ($refPath === pointer.path && !isRootPath(currentPathFromRoot)) {\n                // The value is a reference to itself, so there's nothing to do.\n                pointer.circular = true;\n                pointer.chainCircular = true;\n                return pathChanged;\n            }\n            const canonicalPathFromRoot = typeof currentPathFromRoot === \"string\"\n                ? url.resolve(pointer.$ref.$refs._root$Ref.path, currentPathFromRoot)\n                : currentPathFromRoot;\n            if ($refPath === canonicalPathFromRoot && $refPath !== pointer.path) {\n                pointer.chainCircular = true;\n                return pathChanged;\n            }\n            if (visitedRefPaths.has($refPath)) {\n                pointer.chainCircular = true;\n                return pathChanged;\n            }\n            const maxDepth = options?.dereference?.maxDepth ?? 500;\n            if (visitedRefPaths.size >= maxDepth) {\n                throw new RangeError(`Maximum dereference depth (${maxDepth}) exceeded at ${pointer.path}. ` +\n                    `This likely indicates an extremely deep or recursive schema. ` +\n                    `You can increase this limit with the dereference.maxDepth option.`);\n            }\n            visitedRefPaths.add($refPath);\n            addedPaths.push($refPath);\n            const resolved = pointer.$ref.$refs._resolve($refPath, parentPath, options, visitedRefPaths, extended);\n            if (resolved === null) {\n                return pathChanged;\n            }\n            pointer.indirections += resolved.indirections + 1;\n            pointer.chainCircular ||= resolved.circular || resolved.chainCircular;\n            if (extended) {\n                // This JSON reference \"extends\" the resolved value, rather than simply pointing to it.\n                // So the resolved path does NOT change.  Just the value does.\n                if (pointer.chainCircular) {\n                    return pathChanged;\n                }\n                pointer.value = $Ref.dereference(sourceValue, resolved.value, options);\n                return pathChanged;\n            }\n            else {\n                // Resolve the reference\n                pointer.$ref = resolved.$ref;\n                pointer.path = resolved.path;\n                pointer.value = resolved.value;\n                // `pointer.$ref.path` is already the canonical location of the resolved resource.\n                // Re-applying the resource's own `$id` here would duplicate nested path segments\n                // such as `nested/nested/foo.json`.\n                pointer.scopeBase = resolved.scopeBase;\n                pointer.legacyIdScope = resolved.legacyIdScope;\n                currentPathFromRoot = parentPath;\n                pathChanged = true;\n            }\n        }\n        return pathChanged;\n    }\n    finally {\n        for (const path of addedPaths) {\n            visitedRefPaths.delete(path);\n        }\n    }\n}\nexport default Pointer;\n/**\n * Sets the specified token value of the {@link Pointer#value}.\n *\n * The token is evaluated according to RFC 6901.\n * {@link https://tools.ietf.org/html/rfc6901#section-4}\n *\n * @param pointer - The JSON Pointer whose value will be modified\n * @param token - A JSON Pointer token that indicates how to modify `obj`\n * @param value - The value to assign\n * @returns - Returns the assigned value\n */\nfunction setValue(pointer, token, value) {\n    if (pointer.value && typeof pointer.value === \"object\") {\n        if (token === \"-\" && Array.isArray(pointer.value)) {\n            pointer.value.push(value);\n        }\n        else {\n            pointer.value[token] = value;\n        }\n    }\n    else {\n        throw new JSONParserError(`Error assigning $ref pointer \"${pointer.path}\". \\nCannot set \"${token}\" of a non-object.`);\n    }\n    return value;\n}\nfunction assertSafeSetTokens(pointerPath, tokens) {\n    for (const token of tokens) {\n        if (unsafeSetTokens.has(token)) {\n            throw new JSONParserError(`Error assigning $ref pointer \"${pointerPath}\". \\nUnsafe JSON Pointer token \"${token}\" cannot be used for assignment.`);\n        }\n    }\n}\nfunction unwrapOrThrow(value) {\n    if (isHandledError(value)) {\n        throw value;\n    }\n    return value;\n}\nfunction isRootPath(pathFromRoot) {\n    return typeof pathFromRoot == \"string\" && Pointer.parse(pathFromRoot).length == 0;\n}\nfunction isAliasedResource($ref) {\n    return Boolean($ref.path && $ref.path in $ref.$refs._aliases);\n}\n","import Pointer, { nullSymbol } from \"./pointer.js\";\nimport { InvalidPointerError, isHandledError, normalizeError } from \"./util/errors.js\";\nimport { safePointerToPath, stripHash, getHash } from \"./util/url.js\";\n/**\n * This class represents a single JSON reference and its resolved value.\n *\n * @class\n */\nclass $Ref {\n    /**\n     * The file path or URL of the referenced file.\n     * This path is relative to the path of the main JSON schema file.\n     *\n     * This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file.\n     * Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get\n     * specific JSON pointers within the file.\n     *\n     * @type {string}\n     */\n    path;\n    /**\n     * The resolved value of the JSON reference.\n     * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays).\n     *\n     * @type {?*}\n     */\n    value;\n    /**\n     * The {@link $Refs} object that contains this {@link $Ref} object.\n     *\n     * @type {$Refs}\n     */\n    $refs;\n    /**\n     * Indicates the type of {@link $Ref#path} (e.g. \"file\", \"http\", etc.)\n     */\n    pathType;\n    /**\n     * Whether this document/resource should use JSON Schema 2019-09+ nested $id scope semantics.\n     */\n    dynamicIdScope = false;\n    /** Whether this resource uses draft-04's legacy `id` keyword. */\n    legacyIdScope = false;\n    /**\n     * List of all errors. Undefined if no errors.\n     */\n    errors = [];\n    constructor($refs) {\n        this.$refs = $refs;\n    }\n    /**\n     * Pushes an error to errors array.\n     *\n     * @param err - The error to be pushed\n     * @returns\n     */\n    addError(err) {\n        if (this.errors === undefined) {\n            this.errors = [];\n        }\n        const existingErrors = this.errors.map(({ footprint }) => footprint);\n        // the path has been almost certainly set at this point,\n        // but just in case something went wrong, normalizeError injects path if necessary\n        // moreover, certain errors might point at the same spot, so filter them out to reduce noise\n        if (\"errors\" in err && Array.isArray(err.errors)) {\n            this.errors.push(...err.errors.map(normalizeError).filter(({ footprint }) => !existingErrors.includes(footprint)));\n        }\n        else if (!(\"footprint\" in err) || !existingErrors.includes(err.footprint)) {\n            this.errors.push(normalizeError(err));\n        }\n    }\n    /**\n     * Determines whether the given JSON reference exists within this {@link $Ref#value}.\n     *\n     * @param path - The full path being resolved, optionally with a JSON pointer in the hash\n     * @param options\n     * @returns\n     */\n    exists(path, options) {\n        try {\n            this.resolve(path, options);\n            return true;\n        }\n        catch {\n            return false;\n        }\n    }\n    /**\n     * Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value.\n     *\n     * @param path - The full path being resolved, optionally with a JSON pointer in the hash\n     * @param options\n     * @returns - Returns the resolved value\n     */\n    get(path, options) {\n        return this.resolve(path, options)?.value;\n    }\n    /**\n     * Resolves the given JSON reference within this {@link $Ref#value}.\n     *\n     * @param path - The full path being resolved, optionally with a JSON pointer in the hash\n     * @param options\n     * @param friendlyPath - The original user-specified path (used for error messages)\n     * @param pathFromRoot - The path of `obj` from the schema root\n     * @param visitedRefPaths - the active paths in the current reference chain\n     * @param resolveFinalReference - whether to follow a `$ref` at the resolved value\n     * @returns\n     */\n    resolve(path, options, friendlyPath, pathFromRoot, visitedRefPaths, resolveFinalReference = true) {\n        const pointer = new Pointer(this, path, friendlyPath);\n        try {\n            const resolved = pointer.resolve(this.value, options, pathFromRoot, visitedRefPaths, resolveFinalReference);\n            if (resolved.value === nullSymbol) {\n                resolved.value = null;\n            }\n            return resolved;\n        }\n        catch (err) {\n            if (!options || !options.continueOnError || !isHandledError(err)) {\n                throw err;\n            }\n            if (err.path === null) {\n                err.path = safePointerToPath(getHash(pathFromRoot));\n            }\n            if (err instanceof InvalidPointerError) {\n                err.source = safelyDecodeURI(stripHash(pathFromRoot || friendlyPath || path));\n            }\n            this.addError(err);\n            return null;\n        }\n    }\n    /**\n     * Sets the value of a nested property within this {@link $Ref#value}.\n     * If the property, or any of its parents don't exist, they will be created.\n     *\n     * @param path - The full path of the property to set, optionally with a JSON pointer in the hash\n     * @param value - The value to assign\n     */\n    set(path, value) {\n        const pointer = new Pointer(this, path);\n        this.value = pointer.set(this.value, value);\n        if (this.value === nullSymbol) {\n            this.value = null;\n        }\n    }\n    /**\n     * Determines whether the given value is a JSON reference.\n     *\n     * @param value - The value to inspect\n     * @returns\n     */\n    static is$Ref(value) {\n        return (Boolean(value) &&\n            typeof value === \"object\" &&\n            value !== null &&\n            \"$ref\" in value &&\n            typeof value.$ref === \"string\" &&\n            value.$ref.length > 0);\n    }\n    /**\n     * Determines whether the given value is an external JSON reference.\n     *\n     * @param value - The value to inspect\n     * @returns\n     */\n    static isExternal$Ref(value) {\n        return $Ref.is$Ref(value) && value.$ref[0] !== \"#\";\n    }\n    /**\n     * Determines whether the given value is a JSON reference, and whether it is allowed by the options.\n     * For example, if it references an external file, then options.resolve.external must be true.\n     *\n     * @param value - The value to inspect\n     * @param options\n     * @returns\n     */\n    static isAllowed$Ref(value, options) {\n        if (this.is$Ref(value)) {\n            if (value.$ref.substring(0, 2) === \"#/\" || value.$ref === \"#\") {\n                // It's a JSON Pointer reference, which is always allowed\n                return true;\n            }\n            else if (value.$ref[0] !== \"#\" && (!options || options.resolve?.external)) {\n                // It's an external reference, which is allowed by the options\n                return true;\n            }\n        }\n        return undefined;\n    }\n    /**\n     * Determines whether the given value is a JSON reference that \"extends\" its resolved value.\n     * That is, it has extra properties (in addition to \"$ref\"), so rather than simply pointing to\n     * an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved\n     * value, plus the extra properties.\n     *\n     * @example: {\n       person: {\n         properties: {\n           firstName: { type: string }\n           lastName: { type: string }\n         }\n       }\n       employee: {\n         properties: {\n           $ref: #/person/properties\n           salary: { type: number }\n         }\n       }\n     }\n     *  In this example, \"employee\" is an extended $ref, since it extends \"person\" with an additional\n     *  property (salary).  The result is a NEW value that looks like this:\n     *\n     *  {\n     *    properties: {\n     *      firstName: { type: string }\n     *      lastName: { type: string }\n     *      salary: { type: number }\n     *    }\n     *  }\n     *\n     * @param value - The value to inspect\n     * @returns\n     */\n    static isExtended$Ref(value) {\n        return $Ref.is$Ref(value) && Object.keys(value).length > 1;\n    }\n    /**\n     * Returns the resolved value of a JSON Reference.\n     * If necessary, the resolved value is merged with the JSON Reference to create a new object\n     *\n     * @example: {\n    person: {\n      properties: {\n        firstName: { type: string }\n        lastName: { type: string }\n      }\n    }\n    employee: {\n      properties: {\n        $ref: #/person/properties\n        salary: { type: number }\n      }\n    }\n    } When \"person\" and \"employee\" are merged, you end up with the following object:\n     *\n     *  {\n     *    properties: {\n     *      firstName: { type: string }\n     *      lastName: { type: string }\n     *      salary: { type: number }\n     *    }\n     *  }\n     *\n     * @param $ref - The JSON reference object (the one with the \"$ref\" property)\n     * @param resolvedValue - The resolved value, which can be any type\n     * @param options - The options\n     * @returns - Returns the dereferenced value\n     */\n    static dereference($ref, resolvedValue, options) {\n        if (resolvedValue && typeof resolvedValue === \"object\" && $Ref.isExtended$Ref($ref)) {\n            const merged = {};\n            for (const key of Object.keys($ref)) {\n                if (key !== \"$ref\") {\n                    defineDataProperty(merged, key, $ref[key]);\n                }\n            }\n            const mergeKeys = options?.dereference?.mergeKeys ?? true;\n            const resolvedObject = resolvedValue;\n            for (const key of Object.keys(resolvedObject)) {\n                if (!Object.hasOwn(merged, key)) {\n                    defineDataProperty(merged, key, resolvedObject[key]);\n                }\n                else {\n                    // Key is already in merged, so we should merge them if both are objects\n                    if (mergeKeys &&\n                        typeof merged[key] === \"object\" &&\n                        merged[key] !== null &&\n                        typeof resolvedObject[key] === \"object\" &&\n                        resolvedObject[key] !== null) {\n                        defineDataProperty(merged, key, deepMerge(resolvedObject[key], merged[key]));\n                    }\n                }\n            }\n            return merged;\n        }\n        else {\n            // Completely replace the original reference with the resolved value\n            return resolvedValue;\n        }\n    }\n}\nfunction safelyDecodeURI(value) {\n    try {\n        return decodeURI(value);\n    }\n    catch {\n        return value;\n    }\n}\nfunction deepMerge(target, source) {\n    // If either isn't an object, just return source (overwrite)\n    if (typeof target !== \"object\" || target === null) {\n        return source;\n    }\n    if (typeof source !== \"object\" || source === null) {\n        return source;\n    }\n    if (Array.isArray(source)) {\n        return cloneEnumerableProperties(source);\n    }\n    // Ensure we don't mutate target directly\n    const output = cloneEnumerableProperties(target);\n    const targetObject = target;\n    const sourceObject = source;\n    for (const key of Object.keys(sourceObject)) {\n        const sourceValue = sourceObject[key];\n        let mergedValue;\n        if (Array.isArray(sourceValue)) {\n            // Arrays from the extending value replace the target array entirely.\n            mergedValue = cloneEnumerableProperties(sourceValue);\n        }\n        else if (typeof sourceValue === \"object\" && sourceValue !== null) {\n            const targetValue = Object.hasOwn(targetObject, key) ? targetObject[key] : undefined;\n            mergedValue = deepMerge(targetValue, sourceValue);\n        }\n        else {\n            mergedValue = sourceValue;\n        }\n        defineDataProperty(output, key, mergedValue);\n    }\n    return output;\n}\n/**\n * Creates a shallow copy using only enumerable own properties. Defining each key as a data\n * property is important for JSON keys such as `__proto__`, which must not invoke Object.prototype's\n * legacy prototype setter.\n */\nfunction cloneEnumerableProperties(value) {\n    const clone = Array.isArray(value) ? new Array(value.length) : {};\n    const source = value;\n    for (const key of Object.keys(source)) {\n        defineDataProperty(clone, key, source[key]);\n    }\n    return clone;\n}\nfunction defineDataProperty(target, key, value) {\n    Object.defineProperty(target, key, {\n        configurable: true,\n        enumerable: true,\n        value,\n        writable: true,\n    });\n}\nexport default $Ref;\n","import $Ref from \"./ref.js\";\nimport * as url from \"./util/url.js\";\nimport convertPathToPosix from \"./util/convert-path-to-posix.js\";\n/**\n * When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of $RefParser objects.\n *\n * This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References.\n *\n * See https://apidevtools.com/json-schema-ref-parser/docs/refs.html\n */\nexport default class $Refs {\n    /**\n     * This property is true if the schema contains any circular references. You may want to check this property before serializing the dereferenced schema as JSON, since JSON.stringify() does not support circular references by default.\n     *\n     * See https://apidevtools.com/json-schema-ref-parser/docs/refs.html#circular\n     */\n    circular;\n    /**\n     * Returns the paths/URLs of all the files in your schema (including the main schema file).\n     *\n     * See https://apidevtools.com/json-schema-ref-parser/docs/refs.html#pathstypes\n     *\n     * @param types (optional) Optionally only return certain types of paths (\"file\", \"http\", etc.)\n     */\n    paths(...types) {\n        const paths = getPaths(this._$refs, types.flat());\n        return paths.map((path) => {\n            return convertPathToPosix(path.decoded);\n        });\n    }\n    /**\n     * Returns a map of paths/URLs and their correspond values.\n     *\n     * See https://apidevtools.com/json-schema-ref-parser/docs/refs.html#valuestypes\n     *\n     * @param types (optional) Optionally only return values from certain locations (\"file\", \"http\", etc.)\n     */\n    values(...types) {\n        const $refs = this._$refs;\n        const paths = getPaths($refs, types.flat());\n        return paths.reduce((obj, path) => {\n            obj[convertPathToPosix(path.decoded)] = $refs[path.encoded].value;\n            return obj;\n        }, {});\n    }\n    /**\n     * Returns `true` if the given path exists in the schema; otherwise, returns `false`\n     *\n     * See https://apidevtools.com/json-schema-ref-parser/docs/refs.html#existsref\n     *\n     * @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash\n     */\n    /**\n     * Determines whether the given JSON reference exists.\n     *\n     * @param path - The path being resolved, optionally with a JSON pointer in the hash\n     * @param [options]\n     * @returns\n     */\n    exists(path, options) {\n        try {\n            return this._resolve(path, \"\", options) !== null;\n        }\n        catch {\n            return false;\n        }\n    }\n    /**\n     * Resolves the given JSON reference and returns the resolved value.\n     *\n     * @param path - The path being resolved, with a JSON pointer in the hash\n     * @param [options]\n     * @returns - Returns the resolved value\n     */\n    get(path, options) {\n        return this._resolve(path, \"\", options)?.value;\n    }\n    /**\n     * Sets the value at the given path in the schema. If the property, or any of its parents, don't exist, they will be created.\n     *\n     * @param path The JSON Reference path, optionally with a JSON Pointer in the hash\n     * @param value The value to assign. Can be anything (object, string, number, etc.)\n     */\n    set(path, value) {\n        const absPath = url.resolve(this._root$Ref.path, path);\n        const $ref = this._getRef(absPath);\n        if (!$ref) {\n            throw new Error(`Error resolving $ref pointer \"${path}\". \\n\"${url.stripHash(absPath)}\" not found.`);\n        }\n        $ref.set(absPath, value);\n    }\n    /**\n     * Returns the specified {@link $Ref} object, or undefined.\n     *\n     * @param path - The path being resolved, optionally with a JSON pointer in the hash\n     * @returns\n     * @protected\n     */\n    _get$Ref(path) {\n        path = url.resolve(this._root$Ref.path, path);\n        return this._getRef(path);\n    }\n    /**\n     * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.\n     *\n     * @param path  - The file path or URL of the referenced file\n     */\n    _add(path) {\n        const withoutHash = url.stripHash(path);\n        const $ref = new $Ref(this);\n        $ref.path = withoutHash;\n        this._$refs[withoutHash] = $ref;\n        this._root$Ref = this._root$Ref || $ref;\n        return $ref;\n    }\n    _addAlias(path, value, pathType, dynamicIdScope = false, legacyIdScope = false) {\n        const withoutHash = url.stripHash(path);\n        if (!withoutHash || this._$refs[withoutHash] || this._aliases[withoutHash]) {\n            return this._$refs[withoutHash] || this._aliases[withoutHash];\n        }\n        const $ref = new $Ref(this);\n        $ref.path = withoutHash;\n        $ref.pathType = pathType;\n        $ref.value = value;\n        $ref.dynamicIdScope = dynamicIdScope;\n        $ref.legacyIdScope = legacyIdScope;\n        this._aliases[withoutHash] = $ref;\n        return $ref;\n    }\n    /**\n     * Resolves the given JSON reference.\n     *\n     * @param path - The path being resolved, optionally with a JSON pointer in the hash\n     * @param pathFromRoot - The path of `obj` from the schema root\n     * @param [options]\n     * @param visitedRefPaths - the active paths in the current reference chain\n     * @param resolveFinalReference - whether to follow a `$ref` at the resolved value\n     * @returns\n     * @protected\n     */\n    _resolve(path, pathFromRoot, options, visitedRefPaths, resolveFinalReference = true) {\n        const absPath = url.resolve(this._root$Ref.path, path);\n        const $ref = this._getRef(absPath);\n        if (!$ref) {\n            throw new Error(`Error resolving $ref pointer \"${path}\". \\n\"${url.stripHash(absPath)}\" not found.`);\n        }\n        return $ref.resolve(absPath, options, path, pathFromRoot, visitedRefPaths, resolveFinalReference);\n    }\n    /**\n     * A map of paths/urls to {@link $Ref} objects\n     *\n     * @type {object}\n     * @protected\n     */\n    _$refs = {};\n    _aliases = {};\n    /**\n     * The {@link $Ref} object that is the root of the JSON schema.\n     *\n     * @type {$Ref}\n     * @protected\n     */\n    _root$Ref;\n    constructor() {\n        /**\n         * Indicates whether the schema contains any circular references.\n         *\n         * @type {boolean}\n         */\n        this.circular = false;\n        this._$refs = {};\n        this._aliases = {};\n        // @ts-ignore\n        this._root$Ref = null;\n    }\n    /**\n     * Returns the paths of all the files/URLs that are referenced by the JSON schema,\n     * including the schema itself.\n     *\n     * @param [types] - Only return paths of the given types (\"file\", \"http\", etc.)\n     * @returns\n     */\n    /**\n     * Returns the map of JSON references and their resolved values.\n     *\n     * @param [types] - Only return references of the given types (\"file\", \"http\", etc.)\n     * @returns\n     */\n    /**\n     * Returns a POJO (plain old JavaScript object) for serialization as JSON.\n     *\n     * @returns {object}\n     */\n    toJSON = () => this.values();\n    _getRef(path) {\n        const withoutHash = url.stripHash(path);\n        return this._$refs[withoutHash] || this._aliases[withoutHash];\n    }\n}\n/**\n * Returns the encoded and decoded paths keys of the given object.\n *\n * @param $refs - The object whose keys are URL-encoded paths\n * @param [types] - Only return paths of the given types (\"file\", \"http\", etc.)\n * @returns\n */\nfunction getPaths($refs, types) {\n    let paths = Object.keys($refs);\n    // Filter the paths by type\n    types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);\n    if (types.length > 0 && types[0]) {\n        paths = paths.filter((key) => {\n            return types.includes($refs[key].pathType);\n        });\n    }\n    // Decode local filesystem paths\n    return paths.map((path) => {\n        return {\n            encoded: path,\n            decoded: $refs[path].pathType === \"file\" ? url.toFileSystemPath(path, true) : path,\n        };\n    });\n}\n","/**\n * Returns the given plugins as an array, rather than an object map.\n * All other methods in this module expect an array of plugins rather than an object map.\n *\n * @returns\n */\nexport function all(plugins) {\n    return Object.keys(plugins || {})\n        .filter((key) => {\n        return typeof plugins[key] === \"object\";\n    })\n        .map((key) => {\n        plugins[key].name = key;\n        return plugins[key];\n    });\n}\n/**\n * Filters the given plugins, returning only the ones return `true` for the given method.\n */\nexport function filter(plugins, method, file, callback, $refs) {\n    return plugins.filter((plugin) => {\n        return !!getResult(plugin, method, file, callback, $refs);\n    });\n}\n/**\n * Sorts the given plugins, in place, by their `order` property.\n */\nexport function sort(plugins) {\n    return plugins.sort((a, b) => {\n        return (a.order ?? Number.MAX_SAFE_INTEGER) - (b.order ?? Number.MAX_SAFE_INTEGER);\n    });\n}\n/**\n * Runs the specified method of the given plugins, in order, until one of them returns a successful result.\n * Each method can return a synchronous value, a Promise, or call an error-first callback.\n * If the promise resolves successfully, or the callback is called without an error, then the result\n * is immediately returned and no further plugins are called.\n * If the promise rejects, or the callback is called with an error, then the next plugin is called.\n * If ALL plugins fail, then the last error is thrown.\n */\nexport async function run(plugins, method, file, $refs) {\n    let lastError;\n    let index = 0;\n    return new Promise((resolve, reject) => {\n        runNextPlugin();\n        function runNextPlugin() {\n            const plugin = plugins[index++];\n            if (!plugin) {\n                // There are no more functions, so re-throw the last error\n                return reject(lastError);\n            }\n            let settled = false;\n            let callbackCalled = false;\n            const callback = (err, result) => {\n                callbackCalled = true;\n                if (settled) {\n                    return;\n                }\n                settled = true;\n                if (err) {\n                    onError(plugin, err);\n                }\n                else {\n                    onSuccess(plugin, result);\n                }\n            };\n            try {\n                // console.log('  %s', plugin.name);\n                const result = getResult(plugin, method, file, callback, $refs);\n                if (result && typeof result.then === \"function\") {\n                    // A promise was returned\n                    result.then((value) => callback(undefined, value), (error) => callback(error, undefined));\n                }\n                else if (result !== undefined) {\n                    // A synchronous result was returned\n                    callback(undefined, result);\n                }\n                else if (!callbackCalled && !acceptsCallback(plugin, method)) {\n                    callback(new Error(\"No promise has been returned or callback has been called.\"), undefined);\n                }\n            }\n            catch (e) {\n                callback(e, undefined);\n            }\n        }\n        function onSuccess(plugin, result) {\n            // console.log('    success');\n            resolve({\n                plugin,\n                result: result,\n            });\n        }\n        function onError(plugin, error) {\n            // console.log('    %s', err.message || err);\n            lastError = {\n                plugin,\n                error,\n            };\n            runNextPlugin();\n        }\n    });\n}\nfunction acceptsCallback(plugin, method) {\n    const value = plugin[method];\n    return typeof value === \"function\" && value.length >= 2;\n}\n/**\n * Returns the value of the given property.\n * If the property is a function, then the result of the function is returned.\n * If the value is a RegExp, then it will be tested against the file URL.\n * If the value is an array, then it will be compared against the file extension.\n */\nfunction getResult(obj, prop, file, callback, $refs) {\n    const value = obj[prop];\n    if (typeof value === \"function\") {\n        return value.apply(obj, [file, callback, $refs]);\n    }\n    if (!callback) {\n        // The synchronous plugin functions (canParse and canRead)\n        // allow a \"shorthand\" syntax, where the user can match\n        // files by RegExp or by file extension.\n        if (value instanceof RegExp) {\n            value.lastIndex = 0;\n            const matches = value.test(file.url);\n            value.lastIndex = 0;\n            return matches;\n        }\n        else if (typeof value === \"string\") {\n            return value === file.extension;\n        }\n        else if (Array.isArray(value)) {\n            return value.indexOf(file.extension) !== -1;\n        }\n    }\n    return value;\n}\n","import * as url from \"./util/url.js\";\nimport { getSchemaIdMode, registerSchemaResources, usesDynamicIdScope } from \"./util/schema-resources.js\";\nimport { filter, all, sort, run } from \"./util/plugins.js\";\nimport { ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError, } from \"./util/errors.js\";\n/**\n * Reads and parses the specified file path or URL.\n */\nasync function parse(target, $refs, options) {\n    let path = typeof target === \"string\" ? target : target.url;\n    const baseUrl = typeof target === \"string\" ? undefined : target.baseUrl;\n    let reference = typeof target === \"string\" ? undefined : target.reference;\n    // Remove the URL fragment, if any\n    const hashIndex = path.indexOf(\"#\");\n    let hash = \"\";\n    if (hashIndex >= 0) {\n        hash = path.substring(hashIndex);\n        // Remove the URL fragment, if any\n        path = path.substring(0, hashIndex);\n    }\n    if (reference) {\n        const referenceHashIndex = reference.indexOf(\"#\");\n        if (referenceHashIndex >= 0) {\n            reference = reference.substring(0, referenceHashIndex);\n        }\n    }\n    // Add a new $Ref for this file, even though we don't have the value yet.\n    // This ensures that we don't simultaneously read & parse the same file multiple times\n    const $ref = $refs._add(path);\n    // This \"file object\" will be passed to all resolvers and parsers.\n    const file = {\n        url: path,\n        hash,\n        extension: url.getExtension(path),\n        ...(reference !== undefined ? { reference } : {}),\n        ...(baseUrl !== undefined ? { baseUrl } : {}),\n    };\n    // Read the file and then parse the data\n    try {\n        const resolver = await readFile(file, options, $refs);\n        $ref.pathType = resolver.plugin.name;\n        file.data = resolver.result;\n        const parser = await parseFile(file, options, $refs);\n        $ref.value = parser.result;\n        $ref.dynamicIdScope = usesDynamicIdScope($ref.value);\n        $ref.legacyIdScope = getSchemaIdMode($ref.value);\n        registerSchemaResources($refs, $ref.path, $ref.value, $ref.pathType, $ref.dynamicIdScope);\n        return parser.result;\n    }\n    catch (err) {\n        if (isHandledError(err)) {\n            $ref.value = err;\n        }\n        throw err;\n    }\n}\n/**\n * Reads the given file, using the configured resolver plugins\n *\n * @param file           - An object containing information about the referenced file\n * @param file.url       - The full URL of the referenced file\n * @param file.extension - The lowercased file extension (e.g. \".txt\", \".html\", etc.)\n * @param options\n * @param $refs\n * @returns\n * The promise resolves with the raw file contents and the resolver that was used.\n */\nasync function readFile(file, options, $refs) {\n    // console.log('Reading %s', file.url);\n    // Find the resolvers that can read this file\n    let resolvers = all(options.resolve);\n    resolvers = filter(resolvers, \"canRead\", file, undefined, $refs);\n    // Run the resolvers, in order, until one of them succeeds\n    sort(resolvers);\n    try {\n        const data = await run(resolvers, \"read\", file, $refs);\n        return data;\n    }\n    catch (err) {\n        if (!err && options.continueOnError) {\n            // No resolver could be matched\n            throw new UnmatchedResolverError(file.url);\n        }\n        else if (!err || !(\"error\" in err)) {\n            // Throw a generic, friendly error.\n            throw new SyntaxError(`Unable to resolve $ref pointer \"${file.url}\"`, { cause: err });\n        }\n        // Throw the original error, if it's one of our own (user-friendly) errors.\n        else if (err.error instanceof ResolverError) {\n            throw err.error;\n        }\n        else {\n            throw new ResolverError(err, file.url);\n        }\n    }\n}\n/**\n * Parses the given file's contents, using the configured parser plugins.\n *\n * @param file           - An object containing information about the referenced file\n * @param file.url       - The full URL of the referenced file\n * @param file.extension - The lowercased file extension (e.g. \".txt\", \".html\", etc.)\n * @param file.data      - The file contents. This will be whatever data type was returned by the resolver\n * @param options\n * @param $refs\n *\n * @returns\n * The promise resolves with the parsed file contents and the parser that was used.\n */\nasync function parseFile(file, options, $refs) {\n    // Find the parsers that can read this file type.\n    // If none of the parsers are an exact match for this file, then we'll try ALL of them.\n    // This handles situations where the file IS a supported type, just with an unknown extension.\n    const allParsers = all(options.parse);\n    const filteredParsers = filter(allParsers, \"canParse\", file);\n    const parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;\n    // Run the parsers, in order, until one of them succeeds\n    sort(parsers);\n    try {\n        const parser = await run(parsers, \"parse\", file, $refs);\n        if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {\n            throw new SyntaxError(`Error parsing \"${file.url}\" as ${parser.plugin.name}. \\nParsed value is empty`);\n        }\n        else {\n            return parser;\n        }\n    }\n    catch (err) {\n        if (!err && options.continueOnError) {\n            // No resolver could be matched\n            throw new UnmatchedParserError(file.url);\n        }\n        else if (err && err.message && err.message.startsWith(\"Error parsing\")) {\n            throw err;\n        }\n        else if (!err || !(\"error\" in err)) {\n            throw new SyntaxError(`Unable to parse ${file.url}`, { cause: err });\n        }\n        else if (err.error instanceof ParserError) {\n            throw err.error;\n        }\n        else {\n            throw new ParserError(err.error.message, file.url);\n        }\n    }\n}\n/**\n * Determines whether the parsed value is \"empty\".\n *\n * @param value\n * @returns\n */\nfunction isEmpty(value) {\n    return (value === undefined ||\n        (typeof value === \"object\" && Object.keys(value).length === 0) ||\n        (typeof value === \"string\" && value.trim().length === 0) ||\n        (Buffer.isBuffer(value) && value.length === 0));\n}\nexport default parse;\n","import { ParserError } from \"../util/errors.js\";\nexport default {\n    /**\n     * The order that this parser will run, in relation to other parsers.\n     */\n    order: 100,\n    /**\n     * Whether to allow \"empty\" files. This includes zero-byte files, as well as empty JSON objects.\n     */\n    allowEmpty: true,\n    /**\n     * Determines whether this parser can parse a given file reference.\n     * Parsers that match will be tried, in order, until one successfully parses the file.\n     * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case\n     * every parser will be tried.\n     */\n    canParse: \".json\",\n    /**\n     * Allow JSON files with byte order marks (BOM)\n     */\n    allowBOM: true,\n    /**\n     * Parses the given file as JSON\n     */\n    async parse(file) {\n        let data = file.data;\n        if (Buffer.isBuffer(data)) {\n            data = data.toString();\n        }\n        if (typeof data === \"string\") {\n            if (data.trim().length === 0) {\n                return; // This mirrors the YAML behavior\n            }\n            if (this.allowBOM && data.charCodeAt(0) === 0xfeff) {\n                data = data.slice(1);\n            }\n            try {\n                return JSON.parse(data);\n            }\n            catch (e) {\n                throw new ParserError(e.message, file.url);\n            }\n        }\n        else {\n            // data is already a JavaScript value (object, array, number, null, NaN, etc.)\n            return data;\n        }\n    },\n};\n","const NOT_RESOLVED: unique symbol = Symbol('NOT_RESOLVED')\nconst MERGE_KEY: unique symbol = Symbol('MERGE_KEY')\n\ntype ScalarRepresent = (data: any) => string\ntype SequenceRepresent = (data: any) => ArrayLike<unknown>\ntype MappingRepresent = (data: any) => Map<unknown, unknown>\n\ntype IdentifyFn = (data: any) => boolean\ntype RepresentTagNameFn = (data: any) => string\n\ninterface ScalarTagDefinition<Result = unknown> {\n  tagName: string\n  nodeKind: 'scalar'\n  implicit: boolean\n  matchByTagPrefix: boolean\n  // Set of `source.charAt(0)` keys for which `resolve` may succeed (a superset of\n  // what it really matches). A key is either a single character or '' (empty\n  // source). `null` means \"no constraint, always try\". Used by the composer to\n  // dispatch implicit scalars by first character without running every resolver.\n  implicitFirstChars: readonly string[] | null\n  // `isExplicit` is true for an explicit tag (`!!tag`), false for implicit plain\n  // scalar resolution.\n  resolve: (source: string, isExplicit: boolean, tagName: string) => Result | typeof NOT_RESOLVED\n  identify: IdentifyFn | null\n  // A scalar's printed form is text, so `represent` always yields a string. The\n  // factory supplies a `String(data)` default when a tag omits it.\n  represent: ScalarRepresent\n  representTagName: RepresentTagNameFn | null\n}\n\ninterface SequenceTagDefinition<Carrier = unknown, Result = Carrier> {\n  tagName: string\n  nodeKind: 'sequence'\n  implicit: false\n  matchByTagPrefix: boolean\n  create: (tagName: string) => Carrier\n  addItem: (carrier: Carrier, item: unknown, index: number) => void | string\n  finalize: (carrier: Carrier) => Result\n  carrierIsResult: boolean\n  identify: IdentifyFn | null\n  represent: SequenceRepresent\n  representTagName: RepresentTagNameFn | null\n}\n\ninterface MappingTagDefinition<Carrier = unknown, Result = Carrier> {\n  tagName: string\n  nodeKind: 'mapping'\n  implicit: false\n  matchByTagPrefix: boolean\n  create: (tagName: string) => Carrier\n  // Writes a pair. Returns '' on success, a non-empty error message otherwise\n  // (key does not fit the representation, value rejected, ...). Always a string\n  // so the hot path never allocates an exception wrapper.\n  addPair: (carrier: Carrier, key: unknown, value: unknown) => string\n  // Read side, mirrors `Map` — defining a representation means defining how to\n  // read it back. `has` is the hot dedup probe (membership without fetching the\n  // value); `keys`/`get` are used only on the cold merge path (`<<`).\n  has: (carrier: Carrier, key: unknown) => boolean\n  keys: (result: Result) => Iterable<unknown>\n  get: (result: Result, key: unknown) => unknown\n  finalize: (carrier: Carrier) => Result\n  carrierIsResult: boolean\n  identify: IdentifyFn | null\n  represent: MappingRepresent\n  representTagName: RepresentTagNameFn | null\n}\n\ntype TagDefinition =\n  | ScalarTagDefinition<any>\n  | SequenceTagDefinition<any, any>\n  | MappingTagDefinition<any, any>\n\ninterface ScalarTagOptions<Result> {\n  implicit?: boolean\n  matchByTagPrefix?: boolean\n  implicitFirstChars?: readonly string[] | null\n  resolve: ScalarTagDefinition<Result>['resolve']\n  identify?: ScalarTagDefinition<Result>['identify']\n  represent?: ScalarTagDefinition<Result>['represent']\n  representTagName?: ScalarTagDefinition<Result>['representTagName']\n}\n\ntype RepresentOptions<Container, Canonical, Represent> =\n  | {\n      identify?: null\n      represent?: Represent\n      representTagName?: RepresentTagNameFn | null\n    }\n  | (Container extends Canonical\n      ? {\n          identify?: IdentifyFn | null\n          represent?: Represent\n          representTagName?: RepresentTagNameFn | null\n        }\n      : {\n          identify: IdentifyFn\n          represent: Represent\n          representTagName?: RepresentTagNameFn | null\n        })\n\ntype SequenceTagOptions<Carrier, Result = Carrier> = {\n  matchByTagPrefix?: boolean\n  create: SequenceTagDefinition<Carrier, Result>['create']\n  addItem: SequenceTagDefinition<Carrier, Result>['addItem']\n  finalize?: SequenceTagDefinition<Carrier, Result>['finalize']\n} & RepresentOptions<Result, ArrayLike<unknown>, SequenceRepresent>\n\ntype MappingTagOptions<Carrier, Result = Carrier> = {\n  matchByTagPrefix?: boolean\n  create: MappingTagDefinition<Carrier, Result>['create']\n  addPair: MappingTagDefinition<Carrier, Result>['addPair']\n  has: MappingTagDefinition<Carrier, Result>['has']\n  keys: MappingTagDefinition<Carrier, Result>['keys']\n  get: MappingTagDefinition<Carrier, Result>['get']\n  finalize?: MappingTagDefinition<Carrier, Result>['finalize']\n} & RepresentOptions<Result, Map<unknown, unknown>, MappingRepresent>\n\nfunction defineScalarTag<Result> (tagName: string, options: ScalarTagOptions<Result>): ScalarTagDefinition<Result> {\n  return {\n    tagName,\n    nodeKind: 'scalar',\n    implicit: options.implicit ?? false,\n    matchByTagPrefix: options.matchByTagPrefix ?? false,\n    implicitFirstChars: options.implicitFirstChars ?? null,\n    resolve: options.resolve,\n    identify: options.identify ?? null,\n    represent: options.represent ?? (data => String(data)),\n    representTagName: options.representTagName ?? null\n  }\n}\n\nfunction defineSequenceTag<Carrier, Result = Carrier> (tagName: string, options: SequenceTagOptions<Carrier, Result>): SequenceTagDefinition<Carrier, Result> {\n  const carrierIsResult = options.finalize === undefined\n\n  return {\n    tagName,\n    nodeKind: 'sequence',\n    implicit: false,\n    matchByTagPrefix: options.matchByTagPrefix ?? false,\n    create: options.create,\n    addItem: options.addItem,\n    finalize: options.finalize ?? (carrier => carrier as unknown as Result),\n    carrierIsResult,\n    identify: options.identify ?? null,\n    represent: options.represent ?? (data => data as ArrayLike<unknown>),\n    representTagName: options.representTagName ?? null\n  }\n}\n\nfunction defineMappingTag<Carrier, Result = Carrier> (tagName: string, options: MappingTagOptions<Carrier, Result>): MappingTagDefinition<Carrier, Result> {\n  const carrierIsResult = options.finalize === undefined\n\n  return {\n    tagName,\n    nodeKind: 'mapping',\n    implicit: false,\n    matchByTagPrefix: options.matchByTagPrefix ?? false,\n    create: options.create,\n    addPair: options.addPair,\n    has: options.has,\n    keys: options.keys,\n    get: options.get,\n    finalize: options.finalize ?? (carrier => carrier as unknown as Result),\n    carrierIsResult,\n    identify: options.identify ?? null,\n    represent: options.represent ?? (data => data as Map<unknown, unknown>),\n    representTagName: options.representTagName ?? null\n  }\n}\n\nexport {\n  NOT_RESOLVED,\n  MERGE_KEY,\n  defineScalarTag,\n  defineSequenceTag,\n  defineMappingTag,\n\n  type ScalarTagDefinition,\n  type SequenceTagDefinition,\n  type MappingTagDefinition,\n  type TagDefinition,\n  type ScalarTagOptions,\n  type SequenceTagOptions,\n  type MappingTagOptions,\n  type ScalarRepresent,\n  type SequenceRepresent,\n  type MappingRepresent\n}\n","import { defineScalarTag } from '../../tag.ts'\n\nconst strTag = defineScalarTag('tag:yaml.org,2002:str', {\n  resolve: (source) => source,\n  identify: (data) => typeof data === 'string'\n})\n\nexport { strTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst NULL_VALUES = ['', '~', 'null', 'Null', 'NULL']\n\nconst nullCoreTag = defineScalarTag('tag:yaml.org,2002:null', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: '' (empty), '~', 'null'/'Null'/'NULL'.\n  implicitFirstChars: ['', '~', 'n', 'N'],\n  resolve: (source) => {\n    if (NULL_VALUES.indexOf(source) !== -1) return null\n\n    return NOT_RESOLVED\n  },\n  identify: (object) => object === null,\n  represent: () => 'null'\n})\n\nexport { nullCoreTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst nullJsonTag = defineScalarTag('tag:yaml.org,2002:null', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: null.\n  implicitFirstChars: ['n'],\n  resolve: (source, isExplicit) => {\n    if (source === 'null' || (isExplicit && source === '')) return null\n\n    return NOT_RESOLVED\n  },\n  identify: (object) => object === null,\n  represent: () => 'null'\n})\n\nexport { nullJsonTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst NULL_VALUES = ['', '~', 'null', 'Null', 'NULL']\n\nconst nullYaml11Tag = defineScalarTag('tag:yaml.org,2002:null', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: '' (empty), '~', 'null'/'Null'/'NULL'.\n  implicitFirstChars: ['', '~', 'n', 'N'],\n  resolve: (source) => {\n    if (NULL_VALUES.indexOf(source) !== -1) return null\n\n    return NOT_RESOLVED\n  },\n  identify: (object) => object === null,\n  represent: () => 'null'\n})\n\nexport { nullYaml11Tag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst TRUE_VALUES = ['true', 'True', 'TRUE']\nconst FALSE_VALUES = ['false', 'False', 'FALSE']\n\nconst boolCoreTag = defineScalarTag('tag:yaml.org,2002:bool', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: true/True/TRUE, false/False/FALSE.\n  implicitFirstChars: ['t', 'T', 'f', 'F'],\n  resolve: (source) => {\n    if (TRUE_VALUES.indexOf(source) !== -1) return true\n    if (FALSE_VALUES.indexOf(source) !== -1) return false\n\n    return NOT_RESOLVED\n  },\n  identify: (object) => Object.prototype.toString.call(object) === '[object Boolean]',\n  represent: (object) => object ? 'true' : 'false'\n})\n\nexport { boolCoreTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst TRUE_VALUES = ['true']\nconst FALSE_VALUES = ['false']\n\nconst boolJsonTag = defineScalarTag('tag:yaml.org,2002:bool', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: true, false.\n  implicitFirstChars: ['t', 'f'],\n  resolve: (source) => {\n    if (TRUE_VALUES.indexOf(source) !== -1) return true\n    if (FALSE_VALUES.indexOf(source) !== -1) return false\n\n    return NOT_RESOLVED\n  },\n  identify: (object) => Object.prototype.toString.call(object) === '[object Boolean]',\n  represent: (object) => object ? 'true' : 'false'\n})\n\nexport { boolJsonTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst TRUE_VALUES = ['true', 'True', 'TRUE', 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON']\nconst FALSE_VALUES = ['false', 'False', 'FALSE', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF']\n\nconst boolYaml11Tag = defineScalarTag('tag:yaml.org,2002:bool', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs.\n  implicitFirstChars: ['y', 'Y', 'n', 'N', 't', 'T', 'f', 'F', 'o', 'O'],\n  resolve: (source) => {\n    if (TRUE_VALUES.indexOf(source) !== -1) return true\n    if (FALSE_VALUES.indexOf(source) !== -1) return false\n\n    return NOT_RESOLVED\n  },\n  identify: (object) => Object.prototype.toString.call(object) === '[object Boolean]',\n  represent: (object) => object ? 'true' : 'false'\n})\n\nexport { boolYaml11Tag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\n// YAML 1.2 Core schema implicit resolution:\n// [-+]? [0-9]+ | 0o [0-7]+ | 0x [0-9a-fA-F]+\nconst YAML_INTEGER_IMPLICIT_PATTERN = new RegExp(\n  // 0o123\n  '^(?:0o[0-7]+' +\n  // 0x1A\n  '|0x[0-9a-fA-F]+' +\n  // 12345\n  '|[-+]?[0-9]+)$')\n\n// Explicit `!!int` validation is separate from Core implicit resolution.\nconst YAML_INTEGER_EXPLICIT_PATTERN = new RegExp(\n  // 0b1010\n  '^(?:[-+]?0b[0-1]+' +\n  // 0o123\n  '|[-+]?0o[0-7]+' +\n  // 0x1A\n  '|[-+]?0x[0-9a-fA-F]+' +\n  // 12345\n  '|[-+]?[0-9]+)$')\n\nfunction parseYamlInteger (source: string) {\n  let value = source\n  let sign = 1\n\n  if (value[0] === '-' || value[0] === '+') {\n    if (value[0] === '-') sign = -1\n    value = value.slice(1)\n  }\n\n  if (value.startsWith('0b')) return sign * parseInt(value.slice(2), 2)\n  if (value.startsWith('0o')) return sign * parseInt(value.slice(2), 8)\n  if (value.startsWith('0x')) return sign * parseInt(value.slice(2), 16)\n\n  return sign * parseInt(value, 10)\n}\n\nfunction resolveYamlInteger (source: string, isExplicit: boolean) {\n  if (isExplicit) {\n    if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED\n  } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) {\n    return NOT_RESOLVED\n  }\n\n  const result = parseYamlInteger(source)\n  return Number.isFinite(result) ? result : NOT_RESOLVED\n}\n\nconst intCoreTag = defineScalarTag('tag:yaml.org,2002:int', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: optional sign + decimal digit.\n  implicitFirstChars: ['-', '+', ...'0123456789'],\n  resolve: resolveYamlInteger,\n  identify: (object) =>\n    // No ancient boxed numbers support\n    Number.isInteger(object) &&\n    // Negative zero => !!float\n    !Object.is(object, -0) &&\n    // Exponential form => !!float, round-trip for !!int 1e21 will be broken\n    object.toString(10).indexOf('e') < 0,\n  represent: (object: number) => object.toString(10)\n})\n\nexport { intCoreTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\n// YAML 1.2 JSON schema implicit resolution:\n// -? ( 0 | [1-9] [0-9]* )\nconst YAML_INTEGER_IMPLICIT_PATTERN = new RegExp(\n  '^-?(?:0|[1-9][0-9]*)$')\n\n// Explicit `!!int` validation is separate from JSON implicit resolution.\nconst YAML_INTEGER_EXPLICIT_PATTERN = new RegExp(\n  // 0b1010\n  '^(?:[-+]?0b[0-1]+' +\n  // 0o123\n  '|[-+]?0o[0-7]+' +\n  // 0x1A\n  '|[-+]?0x[0-9a-fA-F]+' +\n  // 12345\n  '|[-+]?[0-9]+)$')\n\nfunction parseYamlInteger (source: string) {\n  let value = source\n  let sign = 1\n\n  if (value[0] === '-' || value[0] === '+') {\n    if (value[0] === '-') sign = -1\n    value = value.slice(1)\n  }\n\n  if (value.startsWith('0b')) return sign * parseInt(value.slice(2), 2)\n  if (value.startsWith('0o')) return sign * parseInt(value.slice(2), 8)\n  if (value.startsWith('0x')) return sign * parseInt(value.slice(2), 16)\n\n  return sign * parseInt(value, 10)\n}\n\nfunction resolveYamlInteger (source: string, isExplicit: boolean) {\n  if (isExplicit) {\n    if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED\n  } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) {\n    return NOT_RESOLVED\n  }\n\n  const result = parseYamlInteger(source)\n  return Number.isFinite(result) ? result : NOT_RESOLVED\n}\n\nconst intJsonTag = defineScalarTag('tag:yaml.org,2002:int', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: optional '-' or digit.\n  implicitFirstChars: ['-', ...'0123456789'],\n  resolve: resolveYamlInteger,\n  identify: (object) =>\n    // No ancient boxed numbers support\n    Number.isInteger(object) &&\n    // Negative zero => !!float\n    !Object.is(object, -0) &&\n    // Exponential form => !!float, round-trip for !!int 1e21 will be broken\n    object.toString(10).indexOf('e') < 0,\n  represent: (object: number) => object.toString(10)\n})\n\nexport { intJsonTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst YAML_INTEGER_PATTERN = new RegExp(\n  // 0b1010\n  '^(?:[-+]?0b[0-1_]+' +\n  // 0123\n  '|[-+]?0[0-7_]+' +\n  // 0x1A\n  '|[-+]?0x[0-9a-fA-F_]+' +\n  // 1:23\n  '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+' +\n  // 12345\n  '|[-+]?(?:0|[1-9][0-9_]*))$')\n\nfunction parseYamlInteger (source: string) {\n  let value = source.replace(/_/g, '')\n  let sign = 1\n\n  if (value[0] === '-' || value[0] === '+') {\n    if (value[0] === '-') sign = -1\n    value = value.slice(1)\n  }\n\n  if (value.startsWith('0b')) return sign * parseInt(value.slice(2), 2)\n  if (value.startsWith('0x')) return sign * parseInt(value.slice(2), 16)\n\n  if (value.includes(':')) {\n    let result = 0\n    for (const part of value.split(':')) result = result * 60 + Number(part)\n    return sign * result\n  }\n\n  if (value !== '0' && value[0] === '0') return sign * parseInt(value, 8)\n\n  return sign * parseInt(value, 10)\n}\n\nfunction resolveYamlInteger (source: string) {\n  if (!YAML_INTEGER_PATTERN.test(source)) return NOT_RESOLVED\n\n  const result = parseYamlInteger(source)\n  return Number.isFinite(result) ? result : NOT_RESOLVED\n}\n\nconst intYaml11Tag = defineScalarTag('tag:yaml.org,2002:int', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: optional sign + decimal digit.\n  implicitFirstChars: ['-', '+', ...'0123456789'],\n  resolve: resolveYamlInteger,\n  identify: (object) =>\n    // No ancient boxed numbers support\n    Number.isInteger(object) &&\n    // Negative zero => !!float\n    !Object.is(object, -0) &&\n    // Exponential form => !!float, round-trip for !!int 1e21 will be broken\n    object.toString(10).indexOf('e') < 0,\n  represent: (object: number) => object.toString(10)\n})\n\nexport { intYaml11Tag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst YAML_FLOAT_PATTERN = new RegExp(\n  // 2.5e4, 2.5 and integers\n  '^(?:[-+]?[0-9]+(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' +\n  // .2e4, .2\n  '|[-+]?\\\\.[0-9]+(?:[eE][-+]?[0-9]+)?' +\n  // .inf\n  '|[-+]?\\\\.(?:inf|Inf|INF)' +\n  // .nan\n  '|\\\\.(?:nan|NaN|NAN))$')\n\nconst YAML_FLOAT_SPECIAL_PATTERN = new RegExp(\n  '^(?:' +\n  // .inf\n  '[-+]?\\\\.(?:inf|Inf|INF)' +\n  // .nan\n  '|\\\\.(?:nan|NaN|NAN))$')\n\nfunction resolveYamlFloat (source: string) {\n  if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED\n\n  let value = source.toLowerCase()\n  const sign = value[0] === '-' ? -1 : 1\n\n  if ('+-'.includes(value[0])) value = value.slice(1)\n\n  if (value === '.inf') return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY\n  if (value === '.nan') return NaN\n\n  const result = sign * parseFloat(value)\n\n  if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result\n  return NOT_RESOLVED\n}\n\nfunction representYamlFloat (object: number) {\n  if (isNaN(object)) return '.nan'\n  if (object === Number.POSITIVE_INFINITY) return '.inf'\n  if (object === Number.NEGATIVE_INFINITY) return '-.inf'\n  if (Object.is(object, -0)) return '-0.0'\n\n  const result = object.toString(10)\n  return /^[-+]?[0-9]+e/.test(result) ? result.replace('e', '.e') : result\n}\n\nconst floatCoreTag = defineScalarTag('tag:yaml.org,2002:float', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: optional sign, '.', or digit\n  // ('.inf'/'.nan' start with '.').\n  implicitFirstChars: ['-', '+', '.', ...'0123456789'],\n  resolve: resolveYamlFloat,\n  identify: (object) =>\n    // No ancient boxed numbers support\n    typeof object === 'number' &&\n    (\n      // We land here all numbers, not handled (declined) by !!int `.identify`\n      // The same condition as for !!int, but reversed.\n\n      // Filter out integers...\n      !Number.isInteger(object) ||\n      // but allow negative zero\n      Object.is(object, -0) ||\n      // and integers with exponential form\n      object.toString(10).indexOf('e') >= 0\n    ),\n  represent: representYamlFloat\n})\n\nexport { floatCoreTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\n// YAML 1.2 JSON schema implicit resolution:\n// -? ( 0 | [1-9] [0-9]* ) ( \\. [0-9]* )? ( [eE] [-+]? [0-9]+ )?\nconst YAML_FLOAT_IMPLICIT_PATTERN = new RegExp(\n  // 2.5e4, 2.5 and integers\n  '^-?(?:0|[1-9][0-9]*)(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$')\n\n// Explicit `!!float` validation is separate from JSON implicit resolution.\nconst YAML_FLOAT_EXPLICIT_PATTERN = new RegExp(\n  // 2.5e4, 2.5 and integers\n  '^(?:[-+]?[0-9]+(?:\\\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?' +\n  // .2e4, .2\n  '|[-+]?\\\\.[0-9]+(?:[eE][-+]?[0-9]+)?' +\n  // .inf\n  '|[-+]?\\\\.(?:inf|Inf|INF)' +\n  // .nan\n  '|\\\\.(?:nan|NaN|NAN))$')\n\nfunction resolveYamlFloat (source: string, isExplicit: boolean) {\n  if (isExplicit) {\n    if (!YAML_FLOAT_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED\n\n    let value = source.toLowerCase()\n    const sign = value[0] === '-' ? -1 : 1\n\n    if ('+-'.includes(value[0])) value = value.slice(1)\n\n    if (value === '.inf') return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY\n    if (value === '.nan') return NaN\n\n    const result = sign * parseFloat(value)\n    return Number.isFinite(result) ? result : NOT_RESOLVED\n  }\n\n  if (!YAML_FLOAT_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED\n\n  const result = Number(source)\n\n  if (Number.isFinite(result)) return result\n  return NOT_RESOLVED\n}\n\nfunction representYamlFloat (object: number) {\n  if (isNaN(object)) return '.nan'\n  if (object === Number.POSITIVE_INFINITY) return '.inf'\n  if (object === Number.NEGATIVE_INFINITY) return '-.inf'\n  if (Object.is(object, -0)) return '-0.0'\n\n  const result = object.toString(10)\n  return /^[-+]?[0-9]+e/.test(result) ? result.replace('e', '.e') : result\n}\n\nconst floatJsonTag = defineScalarTag('tag:yaml.org,2002:float', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: optional '-' or digit.\n  implicitFirstChars: ['-', ...'0123456789'],\n  resolve: resolveYamlFloat,\n  identify: (object) =>\n    // No ancient boxed numbers support\n    typeof object === 'number' &&\n    (\n      // We land here all numbers, not handled (declined) by !!int `.identify`\n      // The same condition as for !!int, but reversed.\n\n      // Filter out integers...\n      !Number.isInteger(object) ||\n      // but allow negative zero\n      Object.is(object, -0) ||\n      // and integers with exponential form\n      object.toString(10).indexOf('e') >= 0\n    ),\n  represent: representYamlFloat\n})\n\nexport { floatJsonTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst YAML_FLOAT_PATTERN = new RegExp(\n  // 2.5e4, 2.5 and integers\n  '^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\\\.[0-9_]*)(?:[eE][-+][0-9]+)?' +\n  // 190:20:30.15\n  '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*' +\n  // .inf\n  '|[-+]?\\\\.(?:inf|Inf|INF)' +\n  // .nan\n  '|\\\\.(?:nan|NaN|NAN))$')\n\nconst YAML_FLOAT_SPECIAL_PATTERN = new RegExp(\n  '^(?:' +\n  // .inf\n  '[-+]?\\\\.(?:inf|Inf|INF)' +\n  // .nan\n  '|\\\\.(?:nan|NaN|NAN))$')\n\nfunction resolveYamlFloat (source: string) {\n  if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED\n\n  let value = source.toLowerCase().replace(/_/g, '')\n  const sign = value[0] === '-' ? -1 : 1\n\n  if ('+-'.includes(value[0])) value = value.slice(1)\n\n  if (value === '.inf') return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY\n  if (value === '.nan') return NaN\n\n  let result = 0\n\n  if (value.includes(':')) {\n    for (const part of value.split(':')) result = result * 60 + Number(part)\n    result *= sign\n  } else {\n    result = sign * parseFloat(value)\n  }\n\n  if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result\n  return NOT_RESOLVED\n}\n\nfunction representYamlFloat (object: number) {\n  if (isNaN(object)) return '.nan'\n  if (object === Number.POSITIVE_INFINITY) return '.inf'\n  if (object === Number.NEGATIVE_INFINITY) return '-.inf'\n  if (Object.is(object, -0)) return '-0.0'\n\n  const result = object.toString(10)\n  return /^[-+]?[0-9]+e/.test(result) ? result.replace('e', '.e') : result\n}\n\nconst floatYaml11Tag = defineScalarTag('tag:yaml.org,2002:float', {\n  implicit: true,\n  // Superset of source.charAt(0) over all matched inputs: optional sign, '.', or digit\n  // ('.inf'/'.nan' start with '.').\n  implicitFirstChars: ['-', '+', '.', ...'0123456789'],\n  resolve: resolveYamlFloat,\n  identify: (object) =>\n    // No ancient boxed numbers support\n    typeof object === 'number' &&\n    (\n      // We land here all numbers, not handled (declined) by !!int `.identify`\n      // The same condition as for !!int, but reversed.\n\n      // Filter out integers...\n      !Number.isInteger(object) ||\n      // but allow negative zero\n      Object.is(object, -0) ||\n      // and integers with exponential form\n      object.toString(10).indexOf('e') >= 0\n    ),\n  represent: representYamlFloat\n})\n\nexport { floatYaml11Tag }\n","import { defineScalarTag, MERGE_KEY, NOT_RESOLVED } from '../../tag.ts'\n\nconst mergeTag = defineScalarTag('tag:yaml.org,2002:merge', {\n  implicit: true,\n  // source.charAt(0) over matched implicit inputs: '<' ('<<').\n  implicitFirstChars: ['<'],\n  resolve: (source, isExplicit) => {\n    if (source === '<<' || (isExplicit && source === '')) return MERGE_KEY\n    return NOT_RESOLVED\n  }\n})\n\nexport { mergeTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/\n\nfunction resolveYamlBinary (source: string) {\n  // Strip allowed whitespace first, so validation stays a plain base64 check.\n  const input = source.replace(/\\s/g, '')\n  if (input.length % 4 !== 0 || !BASE64_PATTERN.test(input)) return NOT_RESOLVED\n\n  const binary = atob(input)\n  const result = new Uint8Array(binary.length)\n  for (let index = 0; index < binary.length; index++) {\n    result[index] = binary.charCodeAt(index)\n  }\n  return result\n}\n\nfunction representYamlBinary (object: Uint8Array) {\n  let binary = ''\n  for (let index = 0; index < object.length; index++) {\n    binary += String.fromCharCode(object[index])\n  }\n  return btoa(binary)\n}\n\nconst binaryTag = defineScalarTag('tag:yaml.org,2002:binary', {\n  resolve: resolveYamlBinary,\n  identify: (object) => Object.prototype.toString.call(object) === '[object Uint8Array]',\n  represent: representYamlBinary\n})\n\nexport { binaryTag }\n","import { defineScalarTag, NOT_RESOLVED } from '../../tag.ts'\n\nconst YAML_DATE_REGEXP = new RegExp(\n  '^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$')\n\nconst YAML_TIMESTAMP_REGEXP = new RegExp(\n  '^([0-9][0-9][0-9][0-9])' +\n  '-([0-9][0-9]?)' +\n  '-([0-9][0-9]?)' +\n  '(?:[Tt]|[ \\\\t]+)' +\n  '([0-9][0-9]?)' +\n  ':([0-9][0-9])' +\n  ':([0-9][0-9])' +\n  '(?:\\\\.([0-9]*))?' +\n  '(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)' +\n  '(?::([0-9][0-9]))?))?$')\n\nfunction resolveYamlTimestamp (source: string) {\n  let match = YAML_DATE_REGEXP.exec(source)\n  if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(source)\n  if (match === null) return NOT_RESOLVED\n\n  const year = +(match[1])\n  const month = +(match[2]) - 1\n  const day = +(match[3])\n\n  // Date-only form (`YYYY-MM-DD`) has no time captures.\n  if (!match[4]) {\n    const date = new Date(Date.UTC(year, month, day))\n    // Reject dates that JS would normalize, e.g. 2023-02-29 -> 2023-03-01.\n    if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) {\n      return NOT_RESOLVED\n    }\n    return date\n  }\n\n  const hour = +(match[4])\n  const minute = +(match[5])\n  const second = +(match[6])\n  let fraction = 0\n\n  // Reject times that JS would normalize into the next minute/hour/day.\n  if (hour > 23 || minute > 59 || second > 59) return NOT_RESOLVED\n\n  if (match[7]) {\n    let value = match[7].slice(0, 3)\n    while (value.length < 3) value += '0'\n    fraction = +value\n  }\n\n  const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction))\n\n  // Reject invalid calendar dates before applying timezone offset.\n  if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) {\n    return NOT_RESOLVED\n  }\n\n  if (match[9]) {\n    const offsetHour = +(match[10])\n    const offsetMinute = +(match[11] || 0)\n    // Reject timezone offsets that JS date arithmetic would otherwise accept.\n    if (offsetHour > 23 || offsetMinute > 59) return NOT_RESOLVED\n\n    const offset = (offsetHour * 60 + offsetMinute) * 60000\n    date.setTime(date.getTime() - (match[9] === '-' ? -offset : offset))\n  }\n\n  return date\n}\n\nconst timestampTag = defineScalarTag('tag:yaml.org,2002:timestamp', {\n  implicit: true,\n  // Both patterns start with a 4-digit year, so source.charAt(0) is always a digit.\n  implicitFirstChars: [...'0123456789'],\n  resolve: resolveYamlTimestamp,\n  identify: (object) => object instanceof Date,\n  represent: (object: Date) => object.toISOString()\n})\n\nexport { timestampTag }\n","import { defineSequenceTag } from '../../tag.ts'\n\nconst seqTag = defineSequenceTag('tag:yaml.org,2002:seq', {\n  create: () => [] as unknown[],\n  addItem: (container, item) => {\n    container.push(item)\n  },\n  identify: Array.isArray\n})\n\nexport { seqTag }\n","function isPlainObject (data: unknown): boolean {\n  if (data === null || typeof data !== 'object' || Array.isArray(data)) return false\n  const prototype = Object.getPrototypeOf(data)\n  return prototype === null || prototype === Object.prototype\n}\n\n// Project `object` onto `keys`. Absent keys are skipped (so the result can be\n// safely spread over defaults without clobbering them with `undefined`), hence\n// the `Partial` return.\nfunction pick<T extends object, K extends keyof T> (object: T, keys: readonly K[]): Partial<Pick<T, K>> {\n  const result: Partial<Pick<T, K>> = {}\n  for (const key of keys) {\n    if (object[key] !== undefined) result[key] = object[key]\n  }\n  return result\n}\n\nexport {\n  isPlainObject,\n  pick\n}\n","import { defineSequenceTag } from '../../tag.ts'\nimport { isPlainObject } from '../../common/object.ts'\n\ninterface OmapCarrier {\n  list: unknown[]\n  seen: Set<unknown>\n}\n\nconst omapTag = defineSequenceTag('tag:yaml.org,2002:omap', {\n  create: (): OmapCarrier => ({ list: [], seen: new Set() }),\n  addItem: (carrier, item) => {\n    let key: unknown\n\n    if (item instanceof Map) {\n      if (item.size !== 1) return 'cannot resolve an ordered map item'\n      key = item.keys().next().value\n    } else if (isPlainObject(item)) {\n      const itemKeys = Object.keys(item as Record<string, unknown>)\n      if (itemKeys.length !== 1) return 'cannot resolve an ordered map item'\n      key = itemKeys[0]\n    } else {\n      return 'cannot resolve an ordered map item'\n    }\n\n    if (carrier.seen.has(key)) return 'duplicate key in ordered map'\n    carrier.seen.add(key)\n    carrier.list.push(item)\n    return ''\n  },\n  finalize: (carrier): unknown[] => carrier.list\n})\n\nexport { omapTag }\n","import { defineSequenceTag } from '../../tag.ts'\n\ntype Pair = [unknown, unknown]\n\nconst pairsTag = defineSequenceTag('tag:yaml.org,2002:pairs', {\n  create: () => [] as Pair[],\n  addItem: (container, item) => {\n    if (item instanceof Map) {\n      if (item.size !== 1) return 'cannot resolve a pairs item'\n\n      container.push(item.entries().next().value!)\n      return ''\n    }\n\n    if (Object.prototype.toString.call(item) !== '[object Object]') {\n      return 'cannot resolve a pairs item'\n    }\n\n    const object = item as Record<string, unknown>\n    const keys = Object.keys(object)\n\n    if (keys.length !== 1) return 'cannot resolve a pairs item'\n\n    container.push([keys[0], object[keys[0]]] satisfies Pair)\n    return ''\n  }\n})\n\nexport { pairsTag }\n","import { defineMappingTag } from '../../tag.ts'\nimport { isPlainObject } from '../../common/object.ts'\n\ntype StringMapping = Record<string, unknown>\n\nconst mapTag = defineMappingTag('tag:yaml.org,2002:map', {\n  create: (): StringMapping => ({}),\n  identify: isPlainObject,\n  // Dump side: wrap the plain object into the canonical `Map` form the writer\n  // walks. Shallow — keys/values stay references to the originals.\n  represent: (o: StringMapping) => {\n    const map = new Map<string, unknown>()\n    for (const key of Object.keys(o)) map.set(key, o[key])\n    return map\n  },\n  addPair: (container, key, value) => {\n    if (key !== null && typeof key === 'object') {\n      return 'object-based map does not support complex keys'\n    }\n    const normalizedKey = String(key)\n    if (normalizedKey === '__proto__') {\n      // Define as an own data property so a literal `__proto__` key stays data\n      // and never invokes the prototype setter.\n      Object.defineProperty(container, normalizedKey, {\n        value, enumerable: true, configurable: true, writable: true\n      })\n    } else {\n      container[normalizedKey] = value\n    }\n    return ''\n  },\n  // hasOwn, not `in`: a plain object inherits `toString` and friends.\n  has: (container, key) => {\n    if (key !== null && typeof key === 'object') return false\n    return Object.prototype.hasOwnProperty.call(container, String(key))\n  },\n  keys: (container) => Object.keys(container),\n  get: (container, key) => container[String(key)]\n})\n\nexport { mapTag, isPlainObject, type StringMapping }\n","import { defineMappingTag } from '../../tag.ts'\n\nconst setTag = defineMappingTag('tag:yaml.org,2002:set', {\n  create: () => new Set<unknown>(),\n  identify: (data) => data instanceof Set,\n  represent: (data: Set<unknown>) => {\n    const map = new Map<unknown, null>()\n    for (const key of data) map.set(key, null)\n    return map\n  },\n  addPair: (container, key, value) => {\n    if (value !== null) return 'cannot resolve a set item'\n    container.add(key)\n    return ''\n  },\n  has: (container, key) => container.has(key),\n  keys: (container) => container.keys(),\n  get: () => null\n})\n\nexport { setTag }\n","import {\n  type MappingTagDefinition,\n  type ScalarTagDefinition,\n  type SequenceTagDefinition,\n  type TagDefinition\n} from './tag.ts'\nimport { strTag } from './tag/scalar/str.ts'\nimport { nullCoreTag } from './tag/scalar/null_core.ts'\nimport { nullJsonTag } from './tag/scalar/null_json.ts'\nimport { nullYaml11Tag } from './tag/scalar/null_yaml11.ts'\nimport { boolCoreTag } from './tag/scalar/bool_core.ts'\nimport { boolJsonTag } from './tag/scalar/bool_json.ts'\nimport { boolYaml11Tag } from './tag/scalar/bool_yaml11.ts'\nimport { intCoreTag } from './tag/scalar/int_core.ts'\nimport { intJsonTag } from './tag/scalar/int_json.ts'\nimport { intYaml11Tag } from './tag/scalar/int_yaml11.ts'\nimport { floatCoreTag } from './tag/scalar/float_core.ts'\nimport { floatJsonTag } from './tag/scalar/float_json.ts'\nimport { floatYaml11Tag } from './tag/scalar/float_yaml11.ts'\nimport { mergeTag } from './tag/scalar/merge.ts'\nimport { binaryTag } from './tag/scalar/binary.ts'\nimport { timestampTag } from './tag/scalar/timestamp.ts'\nimport { seqTag } from './tag/sequence/seq.ts'\nimport { omapTag } from './tag/sequence/omap.ts'\nimport { pairsTag } from './tag/sequence/pairs.ts'\nimport { mapTag } from './tag/mapping/map.ts'\nimport { setTag } from './tag/mapping/set.ts'\n\ninterface TagDefinitionMap {\n  scalar: Record<string, ScalarTagDefinition>\n  sequence: Record<string, SequenceTagDefinition>\n  mapping: Record<string, MappingTagDefinition>\n}\n\ninterface TagDefinitionListMap {\n  scalar: ScalarTagDefinition[]\n  sequence: SequenceTagDefinition[]\n  mapping: MappingTagDefinition[]\n}\n\nfunction createTagDefinitionMap (): TagDefinitionMap {\n  return {\n    scalar: {},\n    sequence: {},\n    mapping: {}\n  }\n}\n\nfunction createTagDefinitionListMap (): TagDefinitionListMap {\n  return {\n    scalar: [],\n    sequence: [],\n    mapping: []\n  }\n}\n\nfunction compileTags (tags: readonly TagDefinition[]) {\n  const result: TagDefinition[] = []\n\n  for (const tag of tags) {\n    let index = result.length\n\n    for (let previousIndex = 0; previousIndex < result.length; previousIndex++) {\n      const previous = result[previousIndex]\n\n      if (previous.nodeKind === tag.nodeKind &&\n          previous.tagName === tag.tagName &&\n          previous.matchByTagPrefix === tag.matchByTagPrefix) {\n        index = previousIndex\n        break\n      }\n    }\n\n    result[index] = tag\n  }\n\n  return result\n}\n\nclass Schema {\n  readonly tags: readonly TagDefinition[]\n  readonly implicitScalarTags: readonly ScalarTagDefinition[]\n  // Dispatch implicit scalar resolvers by `source.charAt(0)`. Each bucket holds the\n  // resolvers that may match that key, in schema order; a key absent from the map\n  // uses `implicitScalarAnyFirstChar` (resolvers that declared no first-char\n  // constraint, so they apply to any first character).\n  readonly implicitScalarByFirstChar: ReadonlyMap<string, readonly ScalarTagDefinition[]>\n  readonly implicitScalarAnyFirstChar: readonly ScalarTagDefinition[]\n  // The default scalar tag (`!!str`), resolved once so the composer's fallback for\n  // unresolved plain scalars avoids a keyed lookup per scalar.\n  readonly defaultScalarTag: ScalarTagDefinition\n  // The default container tags (`!!seq` / `!!map`), used by the dumper: when a\n  // value is identified by its default tag, the tag is implicit and not printed.\n  // Undefined if the schema does not define them (then such values can't be dumped).\n  readonly defaultSequenceTag: SequenceTagDefinition | undefined\n  readonly defaultMappingTag: MappingTagDefinition | undefined\n  readonly exact: TagDefinitionMap\n  readonly prefix: TagDefinitionListMap\n\n  constructor (tags: readonly TagDefinition[]) {\n    const compiledTags = compileTags(tags)\n    const implicitScalarTags: ScalarTagDefinition[] = []\n    const exact = createTagDefinitionMap()\n    const prefix = createTagDefinitionListMap()\n\n    for (const tag of compiledTags) {\n      if (tag.nodeKind === 'scalar' && tag.implicit) {\n        if (tag.matchByTagPrefix) {\n          throw new Error('Implicit scalar tags cannot match by tag prefix')\n        }\n\n        implicitScalarTags.push(tag)\n      }\n\n      switch (tag.nodeKind) {\n        case 'scalar':\n          if (tag.matchByTagPrefix) prefix.scalar.push(tag)\n          else exact.scalar[tag.tagName] = tag\n          break\n        case 'sequence':\n          if (tag.matchByTagPrefix) prefix.sequence.push(tag)\n          else exact.sequence[tag.tagName] = tag\n          break\n        case 'mapping':\n          if (tag.matchByTagPrefix) prefix.mapping.push(tag)\n          else exact.mapping[tag.tagName] = tag\n          break\n      }\n    }\n\n    const implicitScalarAnyFirstChar = implicitScalarTags.filter(tag => tag.implicitFirstChars === null)\n\n    const keys = new Set<string>()\n    for (const tag of implicitScalarTags) {\n      if (tag.implicitFirstChars !== null) {\n        for (const key of tag.implicitFirstChars) keys.add(key)\n      }\n    }\n\n    const implicitScalarByFirstChar = new Map<string, ScalarTagDefinition[]>()\n    for (const key of keys) {\n      implicitScalarByFirstChar.set(key, implicitScalarTags.filter(tag =>\n        tag.implicitFirstChars === null || tag.implicitFirstChars.indexOf(key) !== -1))\n    }\n\n    const defaultScalarTag = exact.scalar['tag:yaml.org,2002:str']\n    if (!defaultScalarTag) throw new Error('schema does not define the default scalar tag (tag:yaml.org,2002:str)')\n\n    this.tags = compiledTags\n    this.implicitScalarTags = implicitScalarTags\n    this.implicitScalarByFirstChar = implicitScalarByFirstChar\n    this.implicitScalarAnyFirstChar = implicitScalarAnyFirstChar\n    this.defaultScalarTag = defaultScalarTag\n    this.defaultSequenceTag = exact.sequence['tag:yaml.org,2002:seq']\n    this.defaultMappingTag = exact.mapping['tag:yaml.org,2002:map']\n    this.exact = exact\n    this.prefix = prefix\n  }\n\n  withTags (...tags: Array<TagDefinition | readonly TagDefinition[]>): Schema {\n    let flatTags: TagDefinition[] = []\n    for (const tag of tags) flatTags = flatTags.concat(tag)\n\n    return new Schema([...this.tags, ...flatTags])\n  }\n}\n\nconst FAILSAFE_SCHEMA = new Schema([\n  strTag,\n  seqTag,\n  mapTag\n])\n\nconst JSON_SCHEMA = new Schema([\n  ...FAILSAFE_SCHEMA.tags,\n  nullJsonTag,\n  boolJsonTag,\n  intJsonTag,\n  floatJsonTag\n])\n\nconst CORE_SCHEMA = new Schema([\n  ...FAILSAFE_SCHEMA.tags,\n  nullCoreTag,\n  boolCoreTag,\n  intCoreTag,\n  floatCoreTag\n])\n\nconst YAML11_SCHEMA = new Schema([\n  ...FAILSAFE_SCHEMA.tags,\n  nullYaml11Tag,\n  boolYaml11Tag,\n  intYaml11Tag,\n  floatYaml11Tag,\n  timestampTag,\n  mergeTag,\n  binaryTag,\n  omapTag,\n  pairsTag,\n  setTag\n])\n\nexport {\n  Schema,\n  FAILSAFE_SCHEMA,\n  JSON_SCHEMA,\n  CORE_SCHEMA,\n  YAML11_SCHEMA,\n\n  type TagDefinitionMap,\n  type TagDefinitionListMap\n}\n","import { defineMappingTag } from '../../tag.ts'\nimport { isPlainObject } from '../../common/object.ts'\n\ntype RealMapping = Map<unknown, unknown>\n\n// A mapping represented as a real `Map`: keys keep their constructed type,\n// nothing is stringified. Drop-in replacement for the default `!!map` tag\n// (same tag name) — `CORE_SCHEMA.withTags(realMapTag)`.\nconst realMapTag = defineMappingTag('tag:yaml.org,2002:map', {\n  create: () => new Map<unknown, unknown>(),\n  addPair: (container: RealMapping, key, value) => {\n    container.set(key, value)\n    return ''\n  },\n  has: (container: RealMapping, key) => container.has(key),\n  keys: (container: RealMapping) => container.keys(),\n  get: (container: RealMapping, key) => container.get(key),\n  // Dump side: handle both a real `Map` and a plain object, so this tag fully\n  // replaces the default map representation when dumping too.\n  identify: (data) => data instanceof Map || isPlainObject(data),\n  // Dump side: the canonical mapping form is a `Map`. A real `Map` passes\n  // through untouched (keys keep their type); a plain object is wrapped\n  // shallowly. Lossless — nothing is stringified.\n  represent: (data) => {\n    if (data instanceof Map) return data\n    const map = new Map<unknown, unknown>()\n    const obj = data as Record<string, unknown>\n    for (const key of Object.keys(obj)) map.set(key, obj[key])\n    return map\n  }\n})\n\nexport { realMapTag }\n","import { defineMappingTag } from '../../tag.ts'\nimport { isPlainObject } from '../../common/object.ts'\n\ntype StringMapping = Record<string, unknown>\n\n// Coerce a constructed key into the string identity a `{}` representation uses.\n// Returns null for a nested array key (an array element that is itself an\n// array), which would otherwise blow up exponentially when stringified via\n// aliases.\nfunction normalizeKey (key: unknown): string | null {\n  if (Array.isArray(key)) {\n    const array = Array.prototype.slice.call(key) as unknown[]\n\n    for (let index = 0; index < array.length; index++) {\n      if (Array.isArray(array[index])) return null\n\n      if (typeof array[index] === 'object' &&\n          Object.prototype.toString.call(array[index]) === '[object Object]') {\n        array[index] = '[object Object]'\n      }\n    }\n\n    return String(array)\n  }\n\n  if (typeof key === 'object' &&\n      Object.prototype.toString.call(key) === '[object Object]') {\n    return '[object Object]'\n  }\n\n  return String(key)\n}\n\nconst legacyMapTag = defineMappingTag('tag:yaml.org,2002:map', {\n  create: (): StringMapping => ({}),\n  identify: isPlainObject,\n  // Dump side: wrap the plain object into the canonical `Map` form the writer\n  // walks. Shallow — keys/values stay references to the originals.\n  represent: (o: StringMapping) => {\n    const map = new Map<string, unknown>()\n    for (const key of Object.keys(o)) map.set(key, o[key])\n    return map\n  },\n  addPair: (container, key, value) => {\n    const normalizedKey = normalizeKey(key)\n    if (normalizedKey === null) return 'nested arrays are not supported inside keys'\n    if (normalizedKey === '__proto__') {\n      // Define as an own data property so a literal `__proto__` key stays data\n      // and never invokes the prototype setter.\n      Object.defineProperty(container, normalizedKey, {\n        value, enumerable: true, configurable: true, writable: true\n      })\n    } else {\n      container[normalizedKey] = value\n    }\n    return ''\n  },\n  // hasOwn, not `in`: a plain object inherits `toString` and friends.\n  has: (container, key) => {\n    const normalizedKey = normalizeKey(key)\n    return normalizedKey !== null && Object.prototype.hasOwnProperty.call(container, normalizedKey)\n  },\n  keys: (container) => Object.keys(container),\n  get: (container, key) => container[String(key)]\n})\n\nexport { legacyMapTag, isPlainObject, type StringMapping }\n","export interface SnippetMark {\n  name?: string | null\n  buffer: string\n  position: number\n  line: number\n  column: number\n  snippet?: string | null\n}\n\ninterface SnippetOptions {\n  maxLength?: number\n  indent?: number\n  linesBefore?: number\n  linesAfter?: number\n}\n\nconst DEFAULT_SNIPPET_OPTIONS: Required<SnippetOptions> = {\n  maxLength: 79,\n  indent: 1,\n  linesBefore: 3,\n  linesAfter: 2\n}\n\n// get snippet for a single line, respecting maxLength\nfunction getLine (buffer: string, lineStart: number, lineEnd: number, position: number, maxLineLength: number) {\n  let head = ''\n  let tail = ''\n  const maxHalfLength = Math.floor(maxLineLength / 2) - 1\n\n  if (position - lineStart > maxHalfLength) {\n    head = ' ... '\n    lineStart = position - maxHalfLength + head.length\n  }\n\n  if (lineEnd - position > maxHalfLength) {\n    tail = ' ...'\n    lineEnd = position + maxHalfLength - tail.length\n  }\n\n  return {\n    str: head + buffer.slice(lineStart, lineEnd).replace(/\\t/g, '→') + tail,\n    pos: position - lineStart + head.length // relative position\n  }\n}\n\nfunction padStart (string: string, max: number) {\n  // max() protects from negativa value, to avoid exception.\n  return ' '.repeat(Math.max(max - string.length, 0)) + string\n}\n\nfunction makeSnippet (mark: SnippetMark, options?: SnippetOptions) {\n  if (!mark.buffer) return null\n\n  const opts = { ...DEFAULT_SNIPPET_OPTIONS, ...options }\n\n  const re = /\\r?\\n|\\r|\\0/g\n  const lineStarts = [0]\n  const lineEnds: number[] = []\n  let match: RegExpExecArray | null\n  let foundLineNo = -1\n\n  while ((match = re.exec(mark.buffer))) {\n    lineEnds.push(match.index)\n    lineStarts.push(match.index + match[0].length)\n\n    if (mark.position <= match.index && foundLineNo < 0) {\n      foundLineNo = lineStarts.length - 2\n    }\n  }\n\n  if (foundLineNo < 0) foundLineNo = lineStarts.length - 1\n\n  let result = ''\n  const lineNoLength = Math.min(mark.line + opts.linesAfter, lineEnds.length).toString().length\n  const maxLineLength = opts.maxLength - (opts.indent + lineNoLength + 3)\n\n  for (let i = 1; i <= opts.linesBefore; i++) {\n    if (foundLineNo - i < 0) break\n    const line = getLine(\n      mark.buffer,\n      lineStarts[foundLineNo - i],\n      lineEnds[foundLineNo - i],\n      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),\n      maxLineLength\n    )\n    result = `${' '.repeat(opts.indent)}${padStart((mark.line - i + 1).toString(), lineNoLength)} | ${line.str}\\n${result}`\n  }\n\n  const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength)\n  result += `${' '.repeat(opts.indent)}${padStart((mark.line + 1).toString(), lineNoLength)} | ${line.str}\\n`\n  result += `${'-'.repeat(opts.indent + lineNoLength + 3 + line.pos)}^\\n`\n\n  for (let i = 1; i <= opts.linesAfter; i++) {\n    if (foundLineNo + i >= lineEnds.length) break\n    const line = getLine(\n      mark.buffer,\n      lineStarts[foundLineNo + i],\n      lineEnds[foundLineNo + i],\n      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),\n      maxLineLength\n    )\n    result += `${' '.repeat(opts.indent)}${padStart((mark.line + i + 1).toString(), lineNoLength)} | ${line.str}\\n`\n  }\n\n  return result.replace(/\\n$/, '')\n}\n\nexport default makeSnippet\n","import makeSnippet, { type SnippetMark } from './snippet.ts'\n\n// YAML error class. http://stackoverflow.com/questions/8458984\n//\nfunction formatError (exception: YAMLException, compact?: boolean) {\n  let where = ''\n\n  if (!exception.mark) return exception.reason\n\n  if (exception.mark.name) {\n    where += `in \"${exception.mark.name}\" `\n  }\n\n  where += `(${exception.mark.line + 1}:${exception.mark.column + 1})`\n\n  if (!compact && exception.mark.snippet) {\n    where += `\\n\\n${exception.mark.snippet}`\n  }\n\n  return `${exception.reason} ${where}`\n}\n\nclass YAMLException extends Error {\n  reason: string\n  mark?: SnippetMark\n\n  constructor (reason: string, mark?: SnippetMark) {\n    super()\n\n    this.name = 'YAMLException'\n    this.reason = reason\n    this.mark = mark\n    this.message = formatError(this, false)\n\n    // Guard for ancient browsers\n    if (Error.captureStackTrace) {\n      // Include stack trace in error object,\n      Error.captureStackTrace(this, this.constructor)\n    }\n  }\n\n  toString (compact?: boolean) {\n    return `${this.name}: ${formatError(this, compact)}`\n  }\n}\n\n// Build a YAMLException with a source snippet and throw it. `source` is the\n// raw input text (no parser sentinel); `position` is an offset into it.\nfunction throwErrorAt (source: string, position: number, message: string, filename = ''): never {\n  let line = 0\n  let lineStart = 0\n\n  for (let index = 0; index < position; index++) {\n    const ch = source.charCodeAt(index)\n\n    if (ch === 0x0A/* LF */) {\n      line++\n      lineStart = index + 1\n    } else if (ch === 0x0D/* CR */) {\n      line++\n      if (source.charCodeAt(index + 1) === 0x0A/* LF */) index++\n      lineStart = index + 1\n    }\n  }\n\n  const mark: SnippetMark = {\n    name: filename,\n    buffer: source,\n    position,\n    line,\n    column: position - lineStart\n  }\n\n  mark.snippet = makeSnippet(mark)\n  throw new YAMLException(message, mark)\n}\n\nexport { YAMLException, throwErrorAt }\n","import {\n  SCALAR_STYLE_SINGLE_QUOTED,\n  SCALAR_STYLE_DOUBLE_QUOTED,\n  SCALAR_STYLE_LITERAL_BLOCK,\n  SCALAR_STYLE_FOLDED_BLOCK,\n  CHOMPING_STRIP,\n  CHOMPING_KEEP,\n  type ScalarEvent\n} from './events.ts'\n\nconst NO_RANGE = -1\n\n// --- character helpers (mirrors src/loader.ts, kept self-contained here) ---\n\nfunction simpleEscapeSequence (c: number) {\n  switch (c) {\n    case 0x30/* 0 */: return '\\x00'\n    case 0x61/* a */: return '\\x07'\n    case 0x62/* b */: return '\\x08'\n    case 0x74/* t */: return '\\x09'\n    case 0x09/* Tab */: return '\\x09'\n    case 0x6E/* n */: return '\\x0A'\n    case 0x76/* v */: return '\\x0B'\n    case 0x66/* f */: return '\\x0C'\n    case 0x72/* r */: return '\\x0D'\n    case 0x65/* e */: return '\\x1B'\n    case 0x20/* Space */: return ' '\n    case 0x22/* \" */: return '\\x22'\n    case 0x2F/* / */: return '/'\n    case 0x5C/* \\ */: return '\\x5C'\n    case 0x4E/* N */: return '\\x85'\n    case 0x5F/* _ */: return '\\xA0'\n    case 0x4C/* L */: return '\\u2028'\n    case 0x50/* P */: return '\\u2029'\n    default: return ''\n  }\n}\n\nconst simpleEscapeCheck = new Array(256)\nconst simpleEscapeMap = new Array(256)\nfor (let i = 0; i < 256; i++) {\n  simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0\n  simpleEscapeMap[i] = simpleEscapeSequence(i)\n}\n\nfunction charFromCodepoint (c: number) {\n  if (c <= 0xFFFF) {\n    return String.fromCharCode(c)\n  }\n  return String.fromCharCode(\n    ((c - 0x010000) >> 10) + 0xD800,\n    ((c - 0x010000) & 0x03FF) + 0xDC00\n  )\n}\n\nfunction fromHexCode (c: number) {\n  if (c >= 0x30/* 0 */ && c <= 0x39/* 9 */) return c - 0x30\n  const lc = c | 0x20\n  // Double-quoted scalar ranges are validated by parser.ts before cooking.\n  return lc - 0x61 + 10\n}\n\nfunction escapedHexLen (c: number) {\n  if (c === 0x78/* x */) return 2\n  if (c === 0x75/* u */) return 4\n  // Double-quoted scalar ranges are validated by parser.ts before cooking.\n  return 8\n}\n\n// --- line folding helpers ---\n\n// Skip a run of line breaks plus the leading whitespace of the following\n// lines, returning the number of line breaks consumed and the new position.\nfunction skipFoldedBreaks (input: string, position: number, end: number) {\n  let breaks = 0\n\n  while (position < end) {\n    const ch = input.charCodeAt(position)\n\n    if (ch === 0x0A/* LF */) {\n      breaks++\n      position++\n    } else if (ch === 0x0D/* CR */) {\n      breaks++\n      position++\n      if (input.charCodeAt(position) === 0x0A/* LF */) position++\n    } else if (ch === 0x20/* Space */ || ch === 0x09/* Tab */) {\n      position++\n    } else {\n      break\n    }\n  }\n\n  return { position, breaks }\n}\n\n// Folding of line breaks between content chunks: a single break becomes a\n// space, several breaks become (count - 1) newlines.\nfunction foldedBreaks (count: number) {\n  if (count === 1) return ' '\n  // Called only after skipFoldedBreaks() consumed at least one line break.\n  return '\\n'.repeat(count - 1)\n}\n\n// --- per-style extractors ---\n\nfunction getPlainValue (input: string, start: number, end: number) {\n  let result = ''\n  let position = start\n  let captureStart = start\n  let captureEnd = start\n\n  while (position < end) {\n    const ch = input.charCodeAt(position)\n\n    if (ch === 0x0A/* LF */ || ch === 0x0D/* CR */) {\n      result += input.slice(captureStart, captureEnd)\n      const fold = skipFoldedBreaks(input, position, end)\n      result += foldedBreaks(fold.breaks)\n      position = captureStart = captureEnd = fold.position\n    } else {\n      position++\n      if (ch !== 0x20/* Space */ && ch !== 0x09/* Tab */) captureEnd = position\n    }\n  }\n\n  return result + input.slice(captureStart, captureEnd)\n}\n\nfunction getSingleQuotedValue (input: string, start: number, end: number) {\n  let result = ''\n  let position = start\n  let captureStart = start\n  let captureEnd = start\n\n  while (position < end) {\n    const ch = input.charCodeAt(position)\n\n    if (ch === 0x27/* ' */) {\n      // Within the stored range every quote is part of an escaped '' pair.\n      result += input.slice(captureStart, position) + \"'\"\n      position += 2\n      captureStart = captureEnd = position\n    } else if (ch === 0x0A/* LF */ || ch === 0x0D/* CR */) {\n      result += input.slice(captureStart, captureEnd)\n      const fold = skipFoldedBreaks(input, position, end)\n      result += foldedBreaks(fold.breaks)\n      position = captureStart = captureEnd = fold.position\n    } else {\n      position++\n      if (ch !== 0x20/* Space */ && ch !== 0x09/* Tab */) captureEnd = position\n    }\n  }\n\n  // Whitespace right before the closing quote is significant (it is only\n  // stripped when followed by a line break).\n  return result + input.slice(captureStart, end)\n}\n\nfunction getDoubleQuotedValue (input: string, start: number, end: number) {\n  let result = ''\n  let position = start\n  let captureStart = start\n  let captureEnd = start\n\n  while (position < end) {\n    const ch = input.charCodeAt(position)\n\n    if (ch === 0x5C/* \\ */) {\n      result += input.slice(captureStart, position)\n      position++\n      const escaped = input.charCodeAt(position)\n\n      if (escaped === 0x0A/* LF */ || escaped === 0x0D/* CR */) {\n        // Escaped line break: a line continuation that joins with nothing.\n        position = skipFoldedBreaks(input, position, end).position\n      } else if (escaped < 256 && simpleEscapeCheck[escaped]) {\n        result += simpleEscapeMap[escaped]\n        position++\n      } else {\n        // parser.ts has already rejected unknown escapes and invalid hex digits.\n        let hexLength = escapedHexLen(escaped)\n        let hexResult = 0\n\n        for (; hexLength > 0; hexLength--) {\n          position++\n          const digit = fromHexCode(input.charCodeAt(position))\n          hexResult = (hexResult << 4) + digit\n        }\n\n        result += charFromCodepoint(hexResult)\n        position++\n      }\n\n      captureStart = captureEnd = position\n    } else if (ch === 0x0A/* LF */ || ch === 0x0D/* CR */) {\n      result += input.slice(captureStart, captureEnd)\n      const fold = skipFoldedBreaks(input, position, end)\n      result += foldedBreaks(fold.breaks)\n      position = captureStart = captureEnd = fold.position\n    } else {\n      position++\n      if (ch !== 0x20/* Space */ && ch !== 0x09/* Tab */) captureEnd = position\n    }\n  }\n\n  return result + input.slice(captureStart, end)\n}\n\nfunction getBlockValue (\n  input: string,\n  start: number,\n  end: number,\n  indent: number,\n  chomping: number,\n  folded: boolean\n) {\n  const textIndent = indent < 0 ? 0 : indent\n  // The range starts at column 0 of the first line and includes every line\n  // break, including those of trailing blank lines.\n  const region = input.slice(start, end).replace(/\\r\\n?/g, '\\n')\n  // An empty range is a block with no lines at all (e.g. an empty `|+`) and\n  // must stay empty; a naive split would invent a phantom blank line. Otherwise\n  // a trailing line break leaves a trailing '' from split() that is not a real\n  // line (just the terminator of the last one), so drop it. Interior blank\n  // lines are kept.\n  const lines = region === ''\n    ? []\n    : (region.endsWith('\\n') ? region.slice(0, -1) : region).split('\\n')\n\n  let result = ''\n  let didReadContent = false\n  let emptyLines = 0\n  let atMoreIndented = false\n\n  for (const line of lines) {\n    // Whitespace beyond the content indentation is part of the content, so the\n    // indentation scan stops at textIndent. A line is empty only when nothing\n    // remains after the (capped) indentation.\n    // indent < 0 means no content line was detected (a wholly blank block), so\n    // every line is an empty line.\n    let column = 0\n    while (column < textIndent && line.charCodeAt(column) === 0x20/* Space */) column++\n\n    if (indent < 0 || column >= line.length) {\n      emptyLines++\n      continue\n    }\n\n    const content = line.slice(textIndent)\n    const first = content.charCodeAt(0)\n\n    if (folded) {\n      if (first === 0x20/* Space */ || first === 0x09/* Tab */) {\n        // More-indented lines are not folded.\n        atMoreIndented = true\n        result += '\\n'.repeat(didReadContent ? 1 + emptyLines : emptyLines)\n      } else if (atMoreIndented) {\n        atMoreIndented = false\n        result += '\\n'.repeat(emptyLines + 1)\n      } else if (emptyLines === 0) {\n        if (didReadContent) result += ' '\n      } else {\n        result += '\\n'.repeat(emptyLines)\n      }\n    } else {\n      result += '\\n'.repeat(didReadContent ? 1 + emptyLines : emptyLines)\n    }\n\n    result += content\n    didReadContent = true\n    emptyLines = 0\n  }\n\n  if (chomping === CHOMPING_KEEP) {\n    result += '\\n'.repeat(didReadContent ? 1 + emptyLines : emptyLines)\n  } else if (chomping !== CHOMPING_STRIP) {\n    if (didReadContent) result += '\\n'\n  }\n\n  return result\n}\n\nfunction getScalarValue (input: string, scalar: ScalarEvent): string {\n  if (scalar.valueStart === NO_RANGE) return ''\n\n  const { valueStart, valueEnd } = scalar\n\n  // Fast path: the parser marked this scalar as a verbatim slice of the input\n  // (single-line plain / quoted with no escapes or folded breaks), so the\n  // per-style char loop below would just reproduce the slice.\n  if (scalar.fast) return input.slice(valueStart, valueEnd)\n\n  switch (scalar.style) {\n    case SCALAR_STYLE_SINGLE_QUOTED:\n      return getSingleQuotedValue(input, valueStart, valueEnd)\n    case SCALAR_STYLE_DOUBLE_QUOTED:\n      return getDoubleQuotedValue(input, valueStart, valueEnd)\n    case SCALAR_STYLE_LITERAL_BLOCK:\n      return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, false)\n    case SCALAR_STYLE_FOLDED_BLOCK:\n      return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, true)\n    default:\n      return getPlainValue(input, valueStart, valueEnd)\n  }\n}\n\nexport {\n  getScalarValue\n}\n","const DEFAULT_TAG_HANDLERS: Readonly<Record<string, string>> = {\n  '!': '!',\n  '!!': 'tag:yaml.org,2002:'\n}\n\nfunction tagPercentEncode (source: string) {\n  return encodeURI(source).replace(/!/g, '%21')\n}\n\nfunction tagNameFull (rawTag: string, tagHandlers?: Readonly<Record<string, string>>) {\n  if (rawTag.startsWith('!<') && rawTag.endsWith('>')) {\n    return decodeURIComponent(rawTag.slice(2, -1))\n  }\n\n  const handleEnd = rawTag.indexOf('!', 1)\n  const handle = handleEnd === -1 ? '!' : rawTag.slice(0, handleEnd + 1)\n  const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle\n\n  return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length))\n}\n\nfunction tagNameShort (fullTag: string) {\n  let tag = fullTag\n\n  if (tag.charCodeAt(0) === 0x21) {\n    tag = tag.slice(1)\n    return `!${tagPercentEncode(tag)}`\n  }\n\n  if (tag.slice(0, 18) === 'tag:yaml.org,2002:') {\n    return `!!${tagPercentEncode(tag.slice(18))}`\n  }\n\n  return `!<${tagPercentEncode(tag)}>`\n}\n\nexport {\n  tagNameFull,\n  tagNameShort\n}\n","import {\n  EVENT_ALIAS,\n  EVENT_DOCUMENT,\n  EVENT_MAPPING,\n  EVENT_POP,\n  EVENT_SCALAR,\n  EVENT_SEQUENCE,\n  SCALAR_STYLE_PLAIN,\n  type Event,\n  type TagHandlers,\n  type MappingEvent,\n  type ScalarEvent,\n  type SequenceEvent\n} from './events.ts'\nimport { getScalarValue } from './parser_scalar.ts'\nimport { CORE_SCHEMA, type Schema } from '../schema.ts'\nimport {\n  MERGE_KEY,\n  NOT_RESOLVED,\n  type MappingTagDefinition,\n  type ScalarTagDefinition,\n  type SequenceTagDefinition\n} from '../tag.ts'\nimport { YAMLException, throwErrorAt } from '../common/exception.ts'\nimport { tagNameFull } from '../common/tagname.ts'\n\nconst NO_RANGE = -1\n\ninterface DocumentFrame {\n  kind: 'document'\n  position: number\n  value: unknown\n  hasValue: boolean\n}\n\ninterface SequenceFrame {\n  kind: 'sequence'\n  position: number\n  value: any\n  tag: SequenceTagDefinition<any, any>\n  anchor: Anchor | null\n  index: number\n  // True when this sequence is the source list of a `<<` merge (`<<: [...]`).\n  // Each element is validated as a mapping on arrival; the materialized list is\n  // then delivered to the target mapping, which folds the elements in.\n  merge: boolean\n}\n\ninterface MappingFrame {\n  kind: 'mapping'\n  position: number\n  value: any\n  tag: MappingTagDefinition<any, any>\n  anchor: Anchor | null\n  key: unknown\n  keyPosition: number\n  hasKey: boolean\n  // Keys brought in by a merge that an explicit pair is still allowed to\n  // override. Lazily allocated: stays null for mappings without `<<`.\n  overridable: Set<unknown> | null\n}\n\ntype Frame = DocumentFrame | SequenceFrame | MappingFrame\n\ntype AnyTag = ScalarTagDefinition | SequenceTagDefinition<any, any> | MappingTagDefinition<any, any>\n\ninterface ValueAndTag {\n  value: unknown\n  tag: AnyTag\n}\n\ninterface Anchor {\n  value: unknown\n  tag: AnyTag\n  isValueFinal: boolean\n}\n\ninterface ConstructorOptions {\n  source: string\n  filename?: string\n  schema?: Schema\n  json?: boolean\n  maxTotalMergeKeys?: number\n  maxAliases?: number\n}\n\n// `source` is input data, not config — so it has no default here.\nconst DEFAULT_CONSTRUCTOR_OPTIONS: Required<Omit<ConstructorOptions, 'source'>> = {\n  filename: '',\n  schema: CORE_SCHEMA,\n  json: false,\n  maxTotalMergeKeys: 10000,\n  maxAliases: -1\n}\n\ninterface ConstructorState extends Required<ConstructorOptions> {\n  events: Event[]\n  documents: unknown[]\n  eventIndex: number\n  position: number\n  frames: Frame[]\n  anchors: Map<string, Anchor>\n  tagHandlers: TagHandlers\n  totalMergeKeys: number\n  aliasCount: number\n}\n\nfunction eventPosition (event: Event) {\n  if ('tagStart' in event && event.tagStart !== NO_RANGE) return event.tagStart\n  if ('anchorStart' in event && event.anchorStart !== NO_RANGE) return event.anchorStart\n  if ('valueStart' in event && event.valueStart !== NO_RANGE) return event.valueStart\n  if ('start' in event) return event.start\n  return 0\n}\n\nfunction throwError (state: ConstructorState, message: string): never {\n  throwErrorAt(state.source, state.position, message, state.filename)\n}\n\nfunction finalizeCollection (\n  state: ConstructorState,\n  position: number,\n  tag: SequenceTagDefinition<any, any> | MappingTagDefinition<any, any>,\n  carrier: unknown\n) {\n  try {\n    return tag.finalize(carrier)\n  } catch (error) {\n    if (error instanceof YAMLException) throw error\n    throwErrorAt(\n      state.source,\n      position,\n      error instanceof Error ? error.message : String(error),\n      state.filename\n    )\n  }\n}\n\nfunction lookupTag<T extends ScalarTagDefinition | SequenceTagDefinition | MappingTagDefinition> (\n  exact: Record<string, T>,\n  prefix: readonly T[],\n  tagName: string\n): T | undefined {\n  const exactTag = exact[tagName]\n  if (exactTag) return exactTag\n\n  for (const tag of prefix) {\n    if (tagName.startsWith(tag.tagName)) return tag\n  }\n\n  return undefined\n}\n\nfunction findExplicitTag<T extends ScalarTagDefinition | SequenceTagDefinition | MappingTagDefinition> (\n  state: ConstructorState,\n  exact: Record<string, T>,\n  prefix: readonly T[],\n  tagName: string,\n  nodeKind: T['nodeKind']\n) {\n  const tag = lookupTag(exact, prefix, tagName)\n  if (tag) return tag\n\n  throwError(state, `unknown ${nodeKind} tag !<${tagName}>`)\n}\n\nfunction constructScalar (\n  state: ConstructorState,\n  event: ScalarEvent\n): ValueAndTag {\n  const source = getScalarValue(state.source, event)\n  const rawTag = event.tagStart === NO_RANGE\n    ? ''\n    : state.source.slice(event.tagStart, event.tagEnd)\n  const strTag = state.schema.defaultScalarTag\n\n  if (rawTag !== '') {\n    if (rawTag === '!') return { value: source, tag: strTag }\n\n    const tagName = tagNameFull(rawTag, state.tagHandlers)\n    const scalarTag = lookupTag(state.schema.exact.scalar, state.schema.prefix.scalar, tagName)\n\n    if (scalarTag) {\n      const result = scalarTag.resolve(source, true, tagName)\n\n      if (result === NOT_RESOLVED) {\n        throwError(state, `cannot resolve a node with !<${tagName}> explicit tag`)\n      }\n\n      return { value: result, tag: scalarTag }\n    }\n\n    // An empty node carrying a collection tag (e.g. `!!map`, `!!seq`) is emitted\n    // by the parser as a scalar event, since there is no collection syntax to key\n    // off. Resolve it here by the explicit tag's kind into an empty collection.\n    const collectionTagDef =\n      lookupTag(state.schema.exact.mapping, state.schema.prefix.mapping, tagName) ??\n      lookupTag(state.schema.exact.sequence, state.schema.prefix.sequence, tagName)\n\n    if (collectionTagDef) {\n      if (source !== '') {\n        throwError(state, `cannot resolve a node with !<${tagName}> explicit tag`)\n      }\n\n      const carrier = collectionTagDef.create(tagName)\n      const value = collectionTagDef.carrierIsResult\n        ? carrier\n        : finalizeCollection(state, state.position, collectionTagDef, carrier)\n      return { value, tag: collectionTagDef }\n    }\n\n    throwError(state, `unknown scalar tag !<${tagName}>`)\n  }\n\n  if (event.style === SCALAR_STYLE_PLAIN) {\n    // charAt(0) (not source[0]) yields '' for an empty source, which is the key\n    // the null tag declares; source[0] would be undefined and miss that bucket.\n    const candidates = state.schema.implicitScalarByFirstChar.get(source.charAt(0)) ??\n      state.schema.implicitScalarAnyFirstChar\n    for (const tag of candidates) {\n      const result = tag.resolve(source, false, tag.tagName)\n      if (result !== NOT_RESOLVED) return { value: result, tag }\n    }\n  }\n\n  return { value: strTag.resolve(source, false, strTag.tagName), tag: strTag }\n}\n\nfunction collectionTag<Tag extends SequenceTagDefinition | MappingTagDefinition> (\n  state: ConstructorState,\n  event: SequenceEvent | MappingEvent,\n  exact: Record<string, Tag>,\n  prefix: readonly Tag[],\n  defaultTagName: string,\n  nodeKind: Tag['nodeKind']\n) {\n  const rawTag = event.tagStart === NO_RANGE\n    ? ''\n    : state.source.slice(event.tagStart, event.tagEnd)\n  const tagName = rawTag === '' || rawTag === '!'\n    ? defaultTagName\n    : tagNameFull(rawTag, state.tagHandlers)\n\n  return {\n    tagName,\n    tag: findExplicitTag(state, exact, prefix, tagName, nodeKind)\n  }\n}\n\n// A merge source must be a mapping; every mapping tag exposes the read side.\nfunction isMappingTag (tag: AnyTag): tag is MappingTagDefinition<any, any> {\n  return tag.nodeKind === 'mapping'\n}\n\n// Fold the keys of one mapping source into the target frame, honoring merge\n// precedence: an already-present key (explicit or from an earlier source) wins.\nfunction mergeKeys (state: ConstructorState, frame: MappingFrame, source: unknown, sourceTag: MappingTagDefinition<any, any>) {\n  for (const sourceKey of sourceTag.keys(source)) {\n    if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) {\n      throwError(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`)\n    }\n\n    if (frame.tag.has(frame.value, sourceKey)) continue\n\n    const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey))\n    if (err) throwError(state, err)\n    ;(frame.overridable ??= new Set()).add(sourceKey)\n  }\n}\n\n// The value of a `<<` key: either a mapping (fold its keys) or a sequence of\n// mappings (fold each). A merge sequence has already had every element validated\n// as a mapping on arrival (see addValue), and its elements were built by the\n// target's own mapping tag, so they are read back with it.\nfunction mergeSource (state: ConstructorState, frame: MappingFrame, source: unknown, sourceTag: AnyTag) {\n  state.position = frame.keyPosition\n\n  if (isMappingTag(sourceTag)) {\n    mergeKeys(state, frame, source, sourceTag)\n  } else if (sourceTag.nodeKind === 'sequence' && Array.isArray(source)) {\n    for (const element of source) {\n      mergeKeys(state, frame, element, frame.tag)\n    }\n  } else {\n    throwError(state, 'cannot merge mappings; the provided source object is unacceptable')\n  }\n}\n\nfunction addMappingValue (state: ConstructorState, frame: MappingFrame, key: unknown, value: unknown, tag: AnyTag) {\n  state.position = frame.keyPosition\n\n  // `<<` is intercepted before dedup, so a repeated merge key is allowed.\n  if (key === MERGE_KEY) {\n    mergeSource(state, frame, value, tag)\n    return\n  }\n\n  if (!state.json && frame.tag.has(frame.value, key) && !frame.overridable?.has(key)) {\n    throwError(state, 'duplicated mapping key')\n  }\n\n  const err = frame.tag.addPair(frame.value, key, value)\n  if (err) throwError(state, err)\n  frame.overridable?.delete(key)\n}\n\nfunction addValue (state: ConstructorState, value: unknown, tag: AnyTag) {\n  const frame = state.frames[state.frames.length - 1]!\n\n  if (frame.kind === 'document') {\n    frame.value = value\n    frame.hasValue = true\n  } else if (frame.kind === 'sequence') {\n    if (frame.merge) {\n      // Element of a `<<: [...]` list: validate it is a mapping, then collect\n      // it like any other item for the target to fold in.\n      if (!isMappingTag(tag)) {\n        throwError(state, 'cannot merge mappings; the provided source object is unacceptable')\n      }\n    }\n    const err = frame.tag.addItem(frame.value, value, frame.index++)\n    if (err) throwError(state, err)\n  } else if (frame.hasKey) {\n    const key = frame.key\n    frame.key = undefined\n    frame.hasKey = false\n    addMappingValue(state, frame, key, value, tag)\n  } else {\n    frame.key = value\n    frame.keyPosition = state.position\n    frame.hasKey = true\n  }\n}\n\nfunction storeAnchor (\n  state: ConstructorState,\n  event: ScalarEvent | SequenceEvent | MappingEvent,\n  value: unknown,\n  tag: AnyTag,\n  isValueFinal: boolean\n): Anchor | null {\n  if (event.anchorStart !== NO_RANGE) {\n    const anchor = {\n      value,\n      tag,\n      isValueFinal\n    }\n    state.anchors.set(state.source.slice(event.anchorStart, event.anchorEnd), anchor)\n    return anchor\n  }\n\n  return null\n}\n\nfunction constructFromEvents (events: Event[], options: ConstructorOptions): unknown[] {\n  const state: ConstructorState = {\n    ...DEFAULT_CONSTRUCTOR_OPTIONS,\n    ...options,\n    events,\n    documents: [],\n    eventIndex: 0,\n    position: 0,\n    frames: [],\n    anchors: new Map(),\n    tagHandlers: Object.create(null),\n    totalMergeKeys: 0,\n    aliasCount: 0\n  }\n\n  while (state.eventIndex < state.events.length) {\n    const event = state.events[state.eventIndex++]\n    state.position = eventPosition(event)\n\n    switch (event.type) {\n      case EVENT_DOCUMENT:\n        state.anchors = new Map()\n        state.aliasCount = 0\n        state.tagHandlers = Object.create(null)\n        for (const directive of event.directives) {\n          if (directive.kind === 'tag') state.tagHandlers[directive.handle] = directive.prefix\n        }\n        state.frames.push({ kind: 'document', position: state.position, value: undefined, hasValue: false })\n        break\n\n      case EVENT_SCALAR: {\n        const { value, tag } = constructScalar(state, event)\n        storeAnchor(state, event, value, tag, true)\n        addValue(state, value, tag)\n        break\n      }\n\n      case EVENT_SEQUENCE: {\n        const definition = collectionTag(\n          state,\n          event,\n          state.schema.exact.sequence,\n          state.schema.prefix.sequence,\n          'tag:yaml.org,2002:seq',\n          'sequence'\n        )\n        const value = definition.tag.create(definition.tagName)\n        const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult)\n\n        // `<<: [...]` — the parent mapping is waiting on a merge key, so this\n        // sequence is a list of merge sources: its elements must be mappings.\n        // It is still built and delivered as a normal value; the target folds it.\n        const parent = state.frames[state.frames.length - 1]\n        const merge = parent !== undefined && parent.kind === 'mapping' &&\n          parent.hasKey && parent.key === MERGE_KEY\n\n        state.frames.push({\n          kind: 'sequence', position: state.position, value, tag: definition.tag, anchor, index: 0, merge\n        })\n        break\n      }\n\n      case EVENT_MAPPING: {\n        const definition = collectionTag(\n          state,\n          event,\n          state.schema.exact.mapping,\n          state.schema.prefix.mapping,\n          'tag:yaml.org,2002:map',\n          'mapping'\n        )\n        const value = definition.tag.create(definition.tagName)\n        const anchor = storeAnchor(state, event, value, definition.tag, definition.tag.carrierIsResult)\n        state.frames.push({\n          kind: 'mapping',\n          position: state.position,\n          value,\n          tag: definition.tag,\n          anchor,\n          key: undefined,\n          keyPosition: state.position,\n          hasKey: false,\n          overridable: null\n        })\n        break\n      }\n\n      case EVENT_ALIAS: {\n        if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) {\n          throwError(state, `aliases exceeded maxAliases (${state.maxAliases})`)\n        }\n\n        const name = state.source.slice(event.anchorStart, event.anchorEnd)\n        const anchor = state.anchors.get(name)\n        if (!anchor) {\n          throwError(state, `unidentified alias \"${name}\"`)\n        }\n        if (!anchor.isValueFinal) {\n          throwError(state, `recursive alias \"${name}\" is not supported for tag ${anchor.tag.tagName} because it uses finalize()`)\n        }\n        addValue(state, anchor.value, anchor.tag)\n        break\n      }\n\n      case EVENT_POP: {\n        const frame = state.frames.pop()!\n\n        if (frame.kind === 'document') {\n          state.documents.push(frame.value)\n        } else {\n          const value = frame.tag.carrierIsResult\n            ? frame.value\n            : finalizeCollection(state, frame.position, frame.tag, frame.value)\n          if (frame.anchor) {\n            frame.anchor.value = value\n            frame.anchor.isValueFinal = true\n          }\n          addValue(state, value, frame.tag)\n        }\n        break\n      }\n    }\n  }\n\n  return state.documents\n}\n\nexport {\n  constructFromEvents,\n  DEFAULT_CONSTRUCTOR_OPTIONS,\n  type ConstructorOptions\n}\n","import {\n  EVENT_DOCUMENT,\n  EVENT_SEQUENCE,\n  EVENT_MAPPING,\n  EVENT_SCALAR,\n  EVENT_ALIAS,\n  EVENT_POP,\n  SCALAR_STYLE_PLAIN,\n  SCALAR_STYLE_SINGLE_QUOTED,\n  SCALAR_STYLE_DOUBLE_QUOTED,\n  SCALAR_STYLE_LITERAL_BLOCK,\n  SCALAR_STYLE_FOLDED_BLOCK,\n  COLLECTION_STYLE_BLOCK,\n  COLLECTION_STYLE_FLOW,\n  CHOMPING_CLIP,\n  CHOMPING_STRIP,\n  CHOMPING_KEEP,\n  type Event,\n  type ScalarStyle,\n  type CollectionStyle,\n  type Chomping,\n  type DocumentDirective,\n  type TagHandlers\n} from './events.ts'\nimport { throwErrorAt } from '../common/exception.ts'\n\nconst NO_RANGE = -1\nconst HAS_OWN = Object.prototype.hasOwnProperty\n\nconst CONTEXT_FLOW_IN = 1\nconst CONTEXT_FLOW_OUT = 2\nconst CONTEXT_BLOCK_IN = 3\nconst CONTEXT_BLOCK_OUT = 4\n\n// eslint-disable-next-line no-control-regex\nconst PATTERN_NON_PRINTABLE = /[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_FLOW_INDICATORS = /[,\\[\\]{}]/\n// YAML 1.2.2, [91] c-tag-handle.\n// eslint-disable-next-line no-useless-escape\nconst PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/\n// YAML 1.2.2, [39] ns-uri-char.\n// eslint-disable-next-line no-useless-escape\nconst NS_URI_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\\-#;/?:@&=+$,_.!~*'()\\[\\]])`\n// YAML 1.2.2, [40] ns-tag-char = ns-uri-char - \"!\" - c-flow-indicator.\n// eslint-disable-next-line no-useless-escape\nconst NS_TAG_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\\-#;/?:@&=+$.~*'()_])`\nconst PATTERN_TAG_URI = new RegExp(`^(?:${NS_URI_CHAR})*$`)\n// YAML 1.2.2, [99] c-ns-shorthand-tag suffix part.\nconst PATTERN_TAG_SUFFIX = new RegExp(`^(?:${NS_TAG_CHAR})+$`)\n// YAML 1.2.2, [93] ns-tag-prefix.\nconst PATTERN_TAG_PREFIX = new RegExp(`^(?:!(?:${NS_URI_CHAR})*|${NS_TAG_CHAR}(?:${NS_URI_CHAR})*)$`)\n\ntype NodeContext =\n  typeof CONTEXT_FLOW_IN | typeof CONTEXT_FLOW_OUT |\n  typeof CONTEXT_BLOCK_IN | typeof CONTEXT_BLOCK_OUT\n\ninterface NodeProperties {\n  anchorStart: number\n  anchorEnd: number\n  tagStart: number\n  tagEnd: number\n}\n\ninterface ParserSnapshot {\n  position: number\n  line: number\n  lineStart: number\n  lineIndent: number\n  firstTabInLine: number\n  eventsLength: number\n}\n\ninterface ParserOptions {\n  filename?: string\n  maxDepth?: number\n}\n\nconst DEFAULT_PARSER_OPTIONS: Required<ParserOptions> = {\n  filename: '',\n  maxDepth: 100\n}\n\ninterface ParserState extends Required<ParserOptions> {\n  input: string\n  length: number\n  position: number\n  line: number\n  lineStart: number\n  lineIndent: number\n  firstTabInLine: number\n  depth: number\n  directives: DocumentDirective[]\n  tagHandlers: TagHandlers\n  events: Event[]\n}\n\nfunction addDocumentEvent (\n  state: ParserState,\n  explicitStart: boolean,\n  explicitEnd: boolean\n) {\n  state.events.push({\n    type: EVENT_DOCUMENT,\n    explicitStart,\n    explicitEnd,\n    directives: state.directives\n  })\n}\n\nfunction addSequenceEvent (\n  state: ParserState,\n  start: number,\n  anchorStart: number,\n  anchorEnd: number,\n  tagStart: number,\n  tagEnd: number,\n  style: CollectionStyle\n) {\n  state.events.push({\n    type: EVENT_SEQUENCE,\n    start,\n    anchorStart,\n    anchorEnd,\n    tagStart,\n    tagEnd,\n    style\n  })\n}\n\nfunction addMappingEvent (\n  state: ParserState,\n  start: number,\n  anchorStart: number,\n  anchorEnd: number,\n  tagStart: number,\n  tagEnd: number,\n  style: CollectionStyle\n) {\n  state.events.push({\n    type: EVENT_MAPPING,\n    start,\n    anchorStart,\n    anchorEnd,\n    tagStart,\n    tagEnd,\n    style\n  })\n}\n\nfunction insertFlowPairMappingEvent (state: ParserState, snapshot: ParserSnapshot) {\n  state.events.splice(snapshot.eventsLength, 0, {\n    type: EVENT_MAPPING,\n    start: snapshot.position,\n    anchorStart: NO_RANGE,\n    anchorEnd: NO_RANGE,\n    tagStart: NO_RANGE,\n    tagEnd: NO_RANGE,\n    style: COLLECTION_STYLE_FLOW\n  })\n}\n\nfunction addScalarEvent (\n  state: ParserState,\n  valueStart: number,\n  valueEnd: number,\n  anchorStart: number,\n  anchorEnd: number,\n  tagStart: number,\n  tagEnd: number,\n  style: ScalarStyle,\n  chomping: Chomping = CHOMPING_CLIP,\n  indent = -1,\n  fast = false\n) {\n  state.events.push({\n    type: EVENT_SCALAR,\n    valueStart,\n    valueEnd,\n    anchorStart,\n    anchorEnd,\n    tagStart,\n    tagEnd,\n    style,\n    chomping,\n    indent,\n    fast\n  })\n}\n\nfunction addAliasEvent (\n  state: ParserState,\n  anchorStart: number,\n  anchorEnd: number\n) {\n  state.events.push({\n    type: EVENT_ALIAS,\n    anchorStart,\n    anchorEnd\n  })\n}\n\nfunction addPopEvent (state: ParserState) {\n  state.events.push({ type: EVENT_POP })\n}\n\nfunction addEmptyScalarEvent (state: ParserState) {\n  addScalarEvent(\n    state,\n    NO_RANGE,\n    NO_RANGE,\n    NO_RANGE,\n    NO_RANGE,\n    NO_RANGE,\n    NO_RANGE,\n    SCALAR_STYLE_PLAIN\n  )\n}\n\nfunction emptyProperties (): NodeProperties {\n  return {\n    anchorStart: NO_RANGE,\n    anchorEnd: NO_RANGE,\n    tagStart: NO_RANGE,\n    tagEnd: NO_RANGE\n  }\n}\n\nfunction snapshotState (state: ParserState): ParserSnapshot {\n  return {\n    position: state.position,\n    line: state.line,\n    lineStart: state.lineStart,\n    lineIndent: state.lineIndent,\n    firstTabInLine: state.firstTabInLine,\n    eventsLength: state.events.length\n  }\n}\n\nfunction restoreState (state: ParserState, snapshot: ParserSnapshot) {\n  state.position = snapshot.position\n  state.line = snapshot.line\n  state.lineStart = snapshot.lineStart\n  state.lineIndent = snapshot.lineIndent\n  state.firstTabInLine = snapshot.firstTabInLine\n  state.events.length = snapshot.eventsLength\n}\n\nfunction throwError (state: ParserState, message: string): never {\n  throwErrorAt(state.input.slice(0, state.length), state.position, message, state.filename)\n}\n\nfunction isEol (c: number) {\n  return c === 0x0A/* LF */ || c === 0x0D/* CR */\n}\n\nfunction isWhiteSpace (c: number) {\n  return c === 0x09/* Tab */ || c === 0x20/* Space */\n}\n\nfunction isWsOrEol (c: number) {\n  return isWhiteSpace(c) || isEol(c)\n}\n\nfunction isWsOrEolOrEnd (c: number) {\n  return c === 0 || isWsOrEol(c)\n}\n\nfunction isFlowIndicator (c: number) {\n  return c === 0x2C/* , */ ||\n         c === 0x5B/* [ */ ||\n         c === 0x5D/* ] */ ||\n         c === 0x7B/* { */ ||\n         c === 0x7D/* } */\n}\n\nfunction fromDecimalCode (c: number) {\n  return c >= 0x30/* 0 */ && c <= 0x39/* 9 */ ? c - 0x30 : -1\n}\n\nfunction fromHexCode (c: number) {\n  if (c >= 0x30/* 0 */ && c <= 0x39/* 9 */) return c - 0x30\n  const lc = c | 0x20\n  if (lc >= 0x61/* a */ && lc <= 0x66/* f */) return lc - 0x61 + 10\n  return -1\n}\n\nfunction escapedHexLen (c: number) {\n  if (c === 0x78/* x */) return 2\n  if (c === 0x75/* u */) return 4\n  if (c === 0x55/* U */) return 8\n  return 0\n}\n\nfunction isSimpleEscape (c: number) {\n  return c === 0x30/* 0 */ ||\n         c === 0x61/* a */ ||\n         c === 0x62/* b */ ||\n         c === 0x74/* t */ ||\n         c === 0x09/* Tab */ ||\n         c === 0x6E/* n */ ||\n         c === 0x76/* v */ ||\n         c === 0x66/* f */ ||\n         c === 0x72/* r */ ||\n         c === 0x65/* e */ ||\n         c === 0x20/* Space */ ||\n         c === 0x22/* \" */ ||\n         c === 0x2F/* / */ ||\n         c === 0x5C/* \\ */ ||\n         c === 0x4E/* N */ ||\n         c === 0x5F/* _ */ ||\n         c === 0x4C/* L */ ||\n         c === 0x50/* P */\n}\n\n// Precondition: state.position points at LF or CR.\nfunction consumeLineBreak (state: ParserState) {\n  const ch = state.input.charCodeAt(state.position)\n\n  if (ch === 0x0A/* LF */) {\n    state.position++\n  } else {\n    state.position++\n    if (state.input.charCodeAt(state.position) === 0x0A/* LF */) state.position++\n  }\n\n  state.line++\n  state.lineStart = state.position\n  state.lineIndent = 0\n  state.firstTabInLine = -1\n}\n\nfunction skipSeparationSpace (state: ParserState, allowComments: boolean) {\n  let lineBreaks = 0\n  let ch = state.input.charCodeAt(state.position)\n  let hasSeparation = state.position === state.lineStart ||\n    isWsOrEol(state.input.charCodeAt(state.position - 1))\n\n  while (ch !== 0) {\n    while (isWhiteSpace(ch)) {\n      hasSeparation = true\n      if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {\n        state.firstTabInLine = state.position\n      }\n      ch = state.input.charCodeAt(++state.position)\n    }\n\n    if (allowComments && hasSeparation && ch === 0x23/* # */) {\n      do { ch = state.input.charCodeAt(++state.position) }\n      while (!isEol(ch) && ch !== 0)\n    }\n\n    if (!isEol(ch)) break\n\n    consumeLineBreak(state)\n    lineBreaks++\n    hasSeparation = true\n    ch = state.input.charCodeAt(state.position)\n\n    while (ch === 0x20/* Space */) {\n      state.lineIndent++\n      ch = state.input.charCodeAt(++state.position)\n    }\n  }\n\n  return lineBreaks\n}\n\nfunction testDocumentSeparator (state: ParserState, position = state.position) {\n  const ch = state.input.charCodeAt(position)\n\n  if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&\n      ch === state.input.charCodeAt(position + 1) &&\n      ch === state.input.charCodeAt(position + 2)) {\n    const following = state.input.charCodeAt(position + 3)\n    return following === 0 || isWsOrEol(following)\n  }\n\n  return false\n}\n\nfunction skipUntilLineEnd (state: ParserState) {\n  let ch = state.input.charCodeAt(state.position)\n\n  while (ch !== 0 && !isEol(ch)) {\n    ch = state.input.charCodeAt(++state.position)\n  }\n}\n\nfunction checkPrintable (state: ParserState, start: number, end: number) {\n  if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) {\n    throwError(state, 'the stream contains non-printable characters')\n  }\n}\n\nfunction readTagProperty (state: ParserState, props: NodeProperties, inFlow: boolean) {\n  if (state.input.charCodeAt(state.position) !== 0x21/* ! */) return false\n  if (props.tagStart !== NO_RANGE) throwError(state, 'duplication of a tag property')\n\n  const start = state.position\n  let isVerbatim = false\n  let isNamed = false\n  let tagHandle = '!'\n  let ch = state.input.charCodeAt(++state.position)\n\n  if (ch === 0x3C/* < */) {\n    isVerbatim = true\n    ch = state.input.charCodeAt(++state.position)\n  } else if (ch === 0x21/* ! */) {\n    isNamed = true\n    tagHandle = '!!'\n    ch = state.input.charCodeAt(++state.position)\n  }\n\n  let suffixStart = state.position\n  let tagName\n\n  if (isVerbatim) {\n    while (ch !== 0 && ch !== 0x3E/* > */) ch = state.input.charCodeAt(++state.position)\n    if (ch !== 0x3E/* > */) throwError(state, 'unexpected end of the stream within a verbatim tag')\n    tagName = state.input.slice(suffixStart, state.position)\n    state.position++\n  } else {\n    while (ch !== 0 && !isWsOrEol(ch) && !(inFlow && isFlowIndicator(ch))) {\n      if (ch === 0x21/* ! */) {\n        if (!isNamed) {\n          tagHandle = state.input.slice(suffixStart - 1, state.position + 1)\n          if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, 'named tag handle cannot contain such characters')\n          isNamed = true\n          suffixStart = state.position + 1\n        } else {\n          throwError(state, 'tag suffix cannot contain exclamation marks')\n        }\n      }\n\n      ch = state.input.charCodeAt(++state.position)\n    }\n\n    tagName = state.input.slice(suffixStart, state.position)\n    if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, 'tag suffix cannot contain flow indicator characters')\n  }\n\n  if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) {\n    throwError(state, `tag name cannot contain such characters: ${tagName}`)\n  }\n  try {\n    decodeURIComponent(tagName)\n  } catch {\n    throwError(state, `tag name is malformed: ${tagName}`)\n  }\n\n  if (!isVerbatim && tagHandle !== '!' && tagHandle !== '!!' && !HAS_OWN.call(state.tagHandlers, tagHandle)) {\n    throwError(state, `undeclared tag handle \"${tagHandle}\"`)\n  }\n\n  props.tagStart = start\n  props.tagEnd = state.position\n  return true\n}\n\nfunction readAnchorProperty (state: ParserState, props: NodeProperties) {\n  if (state.input.charCodeAt(state.position) !== 0x26/* & */) return false\n  if (props.anchorStart !== NO_RANGE) throwError(state, 'duplication of an anchor property')\n\n  state.position++\n  const start = state.position\n\n  while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) {\n    state.position++\n  }\n\n  if (state.position === start) throwError(state, 'name of an anchor node must contain at least one character')\n\n  props.anchorStart = start\n  props.anchorEnd = state.position\n  return true\n}\n\nfunction readAlias (state: ParserState, props: NodeProperties) {\n  if (state.input.charCodeAt(state.position) !== 0x2A/* * */) return false\n  if (props.anchorStart !== NO_RANGE || props.tagStart !== NO_RANGE) {\n    throwError(state, 'alias node should not have any properties')\n  }\n\n  state.position++\n  const start = state.position\n\n  while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) {\n    state.position++\n  }\n\n  if (state.position === start) throwError(state, 'name of an alias node must contain at least one character')\n\n  addAliasEvent(state, start, state.position)\n  return true\n}\n\nfunction readFlowScalarBreak (state: ParserState, nodeIndent: number) {\n  skipSeparationSpace(state, false)\n\n  if (state.lineIndent < nodeIndent) {\n    throwError(state, 'deficient indentation')\n  }\n}\n\nfunction readSingleQuotedScalar (state: ParserState, nodeIndent: number, props: NodeProperties) {\n  if (state.input.charCodeAt(state.position) !== 0x27/* ' */) return false\n\n  state.position++\n  const start = state.position\n  // A single-quoted scalar is sliceable verbatim when it has no '' escape pairs\n  // and no folded line breaks (see getScalarValue fast path).\n  let simple = true\n\n  while (state.input.charCodeAt(state.position) !== 0) {\n    const ch = state.input.charCodeAt(state.position)\n\n    if (ch === 0x27/* ' */) {\n      if (state.input.charCodeAt(state.position + 1) === 0x27/* ' */) {\n        simple = false\n        state.position += 2\n        continue\n      }\n\n      const end = state.position\n      state.position++\n      addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE_SINGLE_QUOTED, CHOMPING_CLIP, -1, simple)\n      return true\n    }\n\n    if (isEol(ch)) {\n      simple = false\n      readFlowScalarBreak(state, nodeIndent)\n    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n      throwError(state, 'unexpected end of the document within a single quoted scalar')\n    } else if (ch !== 0x09/* Tab */ && ch < 0x20) {\n      throwError(state, 'expected valid JSON character')\n    } else {\n      state.position++\n    }\n  }\n\n  throwError(state, 'unexpected end of the stream within a single quoted scalar')\n}\n\nfunction readDoubleQuotedScalar (state: ParserState, nodeIndent: number, props: NodeProperties) {\n  if (state.input.charCodeAt(state.position) !== 0x22/* \" */) return false\n\n  state.position++\n  const start = state.position\n  // A double-quoted scalar is sliceable verbatim when it has no \\ escapes and\n  // no folded line breaks (see getScalarValue fast path).\n  let simple = true\n\n  while (state.input.charCodeAt(state.position) !== 0) {\n    const ch = state.input.charCodeAt(state.position)\n\n    if (ch === 0x22/* \" */) {\n      const end = state.position\n      state.position++\n      addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE_DOUBLE_QUOTED, CHOMPING_CLIP, -1, simple)\n      return true\n    }\n\n    if (ch === 0x5C/* \\ */) {\n      simple = false\n      const escaped = state.input.charCodeAt(++state.position)\n\n      if (isEol(escaped)) {\n        readFlowScalarBreak(state, nodeIndent)\n      } else if (isSimpleEscape(escaped)) {\n        state.position++\n      } else {\n        let hexLength = escapedHexLen(escaped)\n\n        if (hexLength === 0) throwError(state, 'unknown escape sequence')\n\n        while (hexLength-- > 0) {\n          state.position++\n          if (fromHexCode(state.input.charCodeAt(state.position)) < 0) {\n            throwError(state, 'expected hexadecimal character')\n          }\n        }\n        state.position++\n      }\n    } else if (isEol(ch)) {\n      simple = false\n      readFlowScalarBreak(state, nodeIndent)\n    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {\n      throwError(state, 'unexpected end of the document within a double quoted scalar')\n    } else if (ch !== 0x09/* Tab */ && ch < 0x20) {\n      throwError(state, 'expected valid JSON character')\n    } else {\n      state.position++\n    }\n  }\n\n  throwError(state, 'unexpected end of the stream within a double quoted scalar')\n}\n\nfunction readBlockScalar (state: ParserState, parentIndent: number, props: NodeProperties) {\n  const ch = state.input.charCodeAt(state.position)\n  let chomping: Chomping = CHOMPING_CLIP\n  let indent = -1\n  let detectedIndent = false\n\n  if (ch !== 0x7C/* | */ && ch !== 0x3E/* > */) return false\n\n  const style = ch === 0x7C/* | */ ? SCALAR_STYLE_LITERAL_BLOCK : SCALAR_STYLE_FOLDED_BLOCK\n  state.position++\n\n  while (state.input.charCodeAt(state.position) !== 0) {\n    const current = state.input.charCodeAt(state.position)\n    const digit = fromDecimalCode(current)\n\n    if (current === 0x2B/* + */ || current === 0x2D/* - */) {\n      if (chomping !== CHOMPING_CLIP) throwError(state, 'repeat of a chomping mode identifier')\n      chomping = current === 0x2B/* + */ ? CHOMPING_KEEP : CHOMPING_STRIP\n      state.position++\n    } else if (digit >= 0) {\n      if (digit === 0) {\n        throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one')\n      }\n      if (detectedIndent) throwError(state, 'repeat of an indentation width identifier')\n      indent = parentIndent + digit - 1\n      detectedIndent = true\n      state.position++\n    } else {\n      break\n    }\n  }\n\n  let hadWhitespace = false\n  while (isWhiteSpace(state.input.charCodeAt(state.position))) {\n    hadWhitespace = true\n    state.position++\n  }\n  if (hadWhitespace && state.input.charCodeAt(state.position) === 0x23/* # */) skipUntilLineEnd(state)\n\n  if (isEol(state.input.charCodeAt(state.position))) {\n    consumeLineBreak(state)\n  } else if (state.input.charCodeAt(state.position) !== 0) {\n    throwError(state, 'a line break is expected')\n  }\n\n  let contentIndent = detectedIndent ? indent : -1\n  let maxLeadingIndent = 0\n  const valueStart = state.position\n  let valueEnd = state.position\n\n  while (state.input.charCodeAt(state.position) !== 0) {\n    const linePosition = state.position\n    let column = 0\n\n    while (state.input.charCodeAt(linePosition + column) === 0x20/* Space */) column++\n\n    const first = state.input.charCodeAt(linePosition + column)\n    if (first === 0) {\n      // End of input acts as a line terminator, but there is no line break to\n      // include here. A final all-spaces line still counts: when the block has a\n      // content indent, the spaces beyond it are real content; in a wholly blank\n      // block (contentIndent < 0) the spaces form a blank line that chomping must\n      // see, exactly as it would if the line ended with a break. Capture the line\n      // in both cases; otherwise the block ends at the start of this empty line.\n      if (contentIndent >= 0) {\n        if (column > contentIndent) valueEnd = linePosition + column\n      } else if (column > 0) {\n        valueEnd = linePosition + column\n      }\n      break\n    }\n    if (linePosition === state.lineStart && testDocumentSeparator(state, linePosition)) break\n\n    if (!detectedIndent && contentIndent === -1 && isEol(first)) {\n      maxLeadingIndent = Math.max(maxLeadingIndent, column)\n    }\n\n    if (!detectedIndent && contentIndent === -1 && !isEol(first)) {\n      if (first === 0x09/* Tab */ && column < parentIndent) {\n        state.position = linePosition + column\n        throwError(state, 'tab characters must not be used in indentation')\n      }\n      if (column < maxLeadingIndent) {\n        state.position = linePosition + column\n        throwError(state, 'bad indentation of a mapping entry')\n      }\n    }\n\n    if (contentIndent === -1 && first !== 0 && !isEol(first) && column < parentIndent) {\n      state.lineIndent = column\n      state.position = linePosition + column\n      break\n    }\n\n    if (!detectedIndent && first !== 0 && !isEol(first) && contentIndent === -1) {\n      contentIndent = column\n    }\n\n    const requiredIndent = contentIndent === -1 ? parentIndent + 1 : contentIndent\n    if (first !== 0 && !isEol(first) && column < requiredIndent) {\n      state.lineIndent = column\n      state.position = linePosition + column\n      break\n    }\n\n    skipUntilLineEnd(state)\n    valueEnd = state.position\n    if (isEol(state.input.charCodeAt(state.position))) {\n      consumeLineBreak(state)\n      // Include the line break in the range so trailing blank lines are\n      // preserved. This is what lets cook tell apart an empty `|+` (range \"\",\n      // value \"\") from a `|+` with one blank line (range \"\\n\", value \"\\n\").\n      // De-indent and chomping are applied later in getScalarValue.\n      valueEnd = state.position\n    }\n  }\n\n  checkPrintable(state, valueStart, valueEnd)\n  addScalarEvent(\n    state,\n    valueStart,\n    valueEnd,\n    props.anchorStart,\n    props.anchorEnd,\n    props.tagStart,\n    props.tagEnd,\n    style,\n    chomping,\n    contentIndent\n  )\n  return true\n}\n\nfunction canStartPlainScalar (state: ParserState, nodeContext: NodeContext) {\n  const ch = state.input.charCodeAt(state.position)\n  const inFlow = nodeContext === CONTEXT_FLOW_IN\n\n  if (ch === 0 ||\n      isWsOrEol(ch) ||\n      ch === 0x23/* # */ ||\n      ch === 0x26/* & */ ||\n      ch === 0x2A/* * */ ||\n      ch === 0x21/* ! */ ||\n      ch === 0x7C/* | */ ||\n      ch === 0x3E/* > */ ||\n      ch === 0x27/* ' */ ||\n      ch === 0x22/* \" */ ||\n      ch === 0x25/* % */ ||\n      ch === 0x40/* @ */ ||\n      ch === 0x60/* ` */ ||\n      (inFlow && isFlowIndicator(ch))) {\n    return false\n  }\n\n  if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {\n    const following = state.input.charCodeAt(state.position + 1)\n    if (isWsOrEolOrEnd(following) || (inFlow && isFlowIndicator(following))) return false\n  }\n\n  return true\n}\n\nfunction readPlainScalar (state: ParserState, nodeIndent: number, nodeContext: NodeContext, props: NodeProperties) {\n  if (!canStartPlainScalar(state, nodeContext)) return false\n\n  const start = state.position\n  let end = state.position\n  let ch = state.input.charCodeAt(state.position)\n  const inFlow = nodeContext === CONTEXT_FLOW_IN\n  // A single-line plain scalar is sliceable verbatim: the parser already trims\n  // trailing whitespace from the range, so no folding is needed (see\n  // getScalarValue fast path). Folded line breaks make it non-simple.\n  let multiline = false\n\n  while (ch !== 0) {\n    if (state.position === state.lineStart && testDocumentSeparator(state)) break\n\n    if (ch === 0x3A/* : */) {\n      const following = state.input.charCodeAt(state.position + 1)\n      if (isWsOrEolOrEnd(following) || (inFlow && isFlowIndicator(following))) break\n    } else if (ch === 0x23/* # */) {\n      const preceding = state.input.charCodeAt(state.position - 1)\n      if (isWsOrEol(preceding)) break\n    } else if (inFlow && isFlowIndicator(ch)) {\n      break\n    } else if (isEol(ch)) {\n      const savedPosition = state.position\n      const savedLine = state.line\n      const savedLineStart = state.lineStart\n      const savedLineIndent = state.lineIndent\n\n      skipSeparationSpace(state, false)\n\n      if (state.lineIndent >= nodeIndent) {\n        multiline = true\n        ch = state.input.charCodeAt(state.position)\n        continue\n      }\n\n      state.position = savedPosition\n      state.line = savedLine\n      state.lineStart = savedLineStart\n      state.lineIndent = savedLineIndent\n      break\n    }\n\n    if (!isWhiteSpace(ch)) end = state.position + 1\n    ch = state.input.charCodeAt(++state.position)\n  }\n\n  if (end === start) return false\n\n  checkPrintable(state, start, end)\n  addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE_PLAIN, CHOMPING_CLIP, -1, !multiline)\n  return true\n}\n\nfunction findBlockMappingColon (state: ParserState) {\n  let position = state.position\n  let flowLevel = 0\n\n  while (position < state.length) {\n    const ch = state.input.charCodeAt(position)\n\n    if (isEol(ch)) return -1\n    if (ch === 0x23/* # */ && isWsOrEol(state.input.charCodeAt(position - 1))) return -1\n\n    if ((ch === 0x2A/* * */ || ch === 0x26/* & */) && position === state.position) {\n      do { position++ }\n      while (state.input.charCodeAt(position) !== 0 &&\n             !isWsOrEol(state.input.charCodeAt(position)) &&\n             !isFlowIndicator(state.input.charCodeAt(position)))\n      continue\n    }\n\n    if (ch === 0x5B/* [ */ || ch === 0x7B/* { */) {\n      flowLevel++\n    } else if (ch === 0x5D/* ] */ || ch === 0x7D/* } */) {\n      if (flowLevel > 0) flowLevel--\n    } else if (flowLevel === 0 && ch === 0x3A/* : */ && isWsOrEol(state.input.charCodeAt(position + 1))) {\n      return position\n    }\n\n    if ((flowLevel > 0 || position === state.position) &&\n        (ch === 0x27/* ' */ || ch === 0x22/* \" */)) {\n      const quote = ch\n      position++\n\n      while (position < state.length && state.input.charCodeAt(position) !== quote) {\n        if (state.input.charCodeAt(position) === 0x5C/* \\ */ && quote === 0x22/* \" */) position++\n        position++\n      }\n    }\n\n    position++\n  }\n\n  return -1\n}\n\nfunction skipFlowSeparationSpace (state: ParserState, nodeIndent: number) {\n  const startLine = state.line\n  skipSeparationSpace(state, true)\n\n  if ((state.line > startLine && state.lineIndent < nodeIndent) ||\n      (state.firstTabInLine !== -1 && state.lineIndent < nodeIndent)) {\n    throwError(state, 'deficient indentation')\n  }\n}\n\nfunction readFlowCollection (state: ParserState, nodeIndent: number, props: NodeProperties) {\n  const ch = state.input.charCodeAt(state.position)\n  const isMapping = ch === 0x7B/* { */\n  const start = state.position\n  let readNext = true\n\n  if (ch !== 0x5B/* [ */ && ch !== 0x7B/* { */) return false\n\n  const terminator = isMapping ? 0x7D/* } */ : 0x5D/* ] */\n\n  if (isMapping) {\n    addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE_FLOW)\n  } else {\n    addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE_FLOW)\n  }\n\n  state.position++\n\n  while (state.input.charCodeAt(state.position) !== 0) {\n    skipFlowSeparationSpace(state, nodeIndent)\n\n    let ch = state.input.charCodeAt(state.position)\n\n    if (ch === terminator) {\n      state.position++\n      addPopEvent(state)\n      return true\n    } else if (!readNext) {\n      throwError(state, 'missed comma between flow collection entries')\n    } else if (ch === 0x2C/* , */) {\n      throwError(state, \"expected the node content, but found ','\")\n    }\n\n    let isPair = false\n    let isExplicitPair = false\n\n    if (ch === 0x3F/* ? */ && isWsOrEol(state.input.charCodeAt(state.position + 1))) {\n      isPair = isExplicitPair = true\n      state.position += 1\n      skipFlowSeparationSpace(state, nodeIndent)\n    }\n\n    const entryLine = state.line\n    const entryStart = snapshotState(state)\n\n    const keyWasRead = parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)\n    skipFlowSeparationSpace(state, nodeIndent)\n\n    ch = state.input.charCodeAt(state.position)\n\n    if ((isMapping || isExplicitPair || state.line === entryLine) && ch === 0x3A/* : */) {\n      isPair = true\n      state.position++\n      skipFlowSeparationSpace(state, nodeIndent)\n      if (!isMapping) {\n        insertFlowPairMappingEvent(state, entryStart)\n        if (!keyWasRead) addEmptyScalarEvent(state)\n      } else if (!keyWasRead) {\n        addEmptyScalarEvent(state)\n      }\n      if (!parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)) {\n        addEmptyScalarEvent(state)\n      }\n      skipFlowSeparationSpace(state, nodeIndent)\n      if (!isMapping) addPopEvent(state)\n    } else if (isMapping && isPair) {\n      if (!keyWasRead) addEmptyScalarEvent(state)\n      addEmptyScalarEvent(state)\n    } else if (isMapping) {\n      addEmptyScalarEvent(state)\n    } else if (isPair) {\n      insertFlowPairMappingEvent(state, entryStart)\n      if (!keyWasRead) addEmptyScalarEvent(state)\n      addEmptyScalarEvent(state)\n      addPopEvent(state)\n    }\n\n    ch = state.input.charCodeAt(state.position)\n\n    if (ch === 0x2C/* , */) {\n      readNext = true\n      state.position++\n    } else {\n      readNext = false\n    }\n  }\n\n  throwError(state, 'unexpected end of the stream within a flow collection')\n}\n\nfunction readBlockSequence (state: ParserState, nodeIndent: number, props: NodeProperties) {\n  if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 0x2D/* - */ || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {\n    return false\n  }\n\n  addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE_BLOCK)\n\n  while (state.input.charCodeAt(state.position) === 0x2D/* - */ && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {\n    if (state.firstTabInLine !== -1) {\n      state.position = state.firstTabInLine\n      throwError(state, 'tab characters must not be used in indentation')\n    }\n\n    const entryLine = state.line\n    state.position++\n\n    const hadBreak = skipSeparationSpace(state, true) > 0\n    if (state.firstTabInLine !== -1 &&\n        state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n        isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {\n      throwError(state, 'bad indentation of a sequence entry')\n    }\n\n    if (hadBreak && state.lineIndent <= nodeIndent) {\n      addEmptyScalarEvent(state)\n    } else {\n      parseNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true)\n    }\n\n    skipSeparationSpace(state, true)\n\n    if (state.lineIndent < nodeIndent || state.position >= state.length) break\n    if (state.lineIndent > nodeIndent) throwError(state, 'bad indentation of a sequence entry')\n    if (state.line === entryLine &&\n        state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n        isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {\n      throwError(state, 'bad indentation of a sequence entry')\n    }\n  }\n\n  addPopEvent(state)\n  return true\n}\n\nfunction readBlockMapping (state: ParserState, nodeIndent: number, flowIndent: number, props: NodeProperties) {\n  let atExplicitKey = false\n  let detected = false\n  let mappingOpened = false\n  let pendingExplicitKey = false\n\n  if (state.firstTabInLine !== -1) return false\n\n  let ch = state.input.charCodeAt(state.position)\n\n  while (ch !== 0) {\n    if (!atExplicitKey && state.firstTabInLine !== -1) {\n      state.position = state.firstTabInLine\n      throwError(state, 'tab characters must not be used in indentation')\n    }\n\n    const following = state.input.charCodeAt(state.position + 1)\n    const entryLine = state.line\n\n    if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && isWsOrEolOrEnd(following)) {\n      if (!mappingOpened) {\n        addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE_BLOCK)\n        mappingOpened = true\n      }\n\n      if (ch === 0x3F/* ? */) {\n        if (atExplicitKey) addEmptyScalarEvent(state)\n        detected = true\n        atExplicitKey = true\n      } else if (atExplicitKey) {\n        atExplicitKey = false\n      } else {\n        addEmptyScalarEvent(state)\n        detected = true\n        atExplicitKey = false\n      }\n\n      state.position += 1\n      pendingExplicitKey = true\n    } else {\n      // An explicit key awaiting its value, followed by an implicit key, means\n      // the explicit key's value is empty. Emit it now (append-only) so it is\n      // ordered before the implicit key node read just below.\n      if (atExplicitKey) {\n        addEmptyScalarEvent(state)\n        atExplicitKey = false\n      }\n\n      const beforeKey = snapshotState(state)\n\n      if (!parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {\n        break\n      }\n\n      if (state.line === entryLine) {\n        ch = state.input.charCodeAt(state.position)\n\n        while (isWhiteSpace(ch)) {\n          ch = state.input.charCodeAt(++state.position)\n        }\n\n        if (ch === 0x3A/* : */) {\n          ch = state.input.charCodeAt(++state.position)\n\n          if (!isWsOrEolOrEnd(ch)) {\n            throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping')\n          }\n\n          if (!mappingOpened) {\n            restoreState(state, beforeKey)\n            addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE_BLOCK)\n            mappingOpened = true\n            // The key, the `:` and the space after it were already validated\n            // above, before the rollback. Re-reading the same input cannot\n            // fail, so just consume it again without error checks.\n            parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)\n\n            ch = state.input.charCodeAt(state.position)\n            while (isWhiteSpace(ch)) {\n              ch = state.input.charCodeAt(++state.position)\n            }\n\n            state.position++\n          }\n\n          detected = true\n          atExplicitKey = false\n          pendingExplicitKey = false\n        } else if (detected) {\n          throwError(state, \"expected ':' after a mapping key\")\n        } else {\n          // Not a mapping. If outer properties are pending, roll back so the\n          // caller re-reads this node with them attached (events are append-only).\n          if (props.anchorStart !== NO_RANGE || props.tagStart !== NO_RANGE) {\n            restoreState(state, beforeKey)\n            return false\n          }\n          return true\n        }\n      } else if (detected) {\n        throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key')\n      } else {\n        if (props.anchorStart !== NO_RANGE || props.tagStart !== NO_RANGE) {\n          restoreState(state, beforeKey)\n          return false\n        }\n        return true\n      }\n    }\n\n    if (parseNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, pendingExplicitKey)) {\n      pendingExplicitKey = false\n    }\n\n    if (!atExplicitKey) {\n      if (pendingExplicitKey) {\n        addEmptyScalarEvent(state)\n        pendingExplicitKey = false\n      }\n    }\n\n    skipSeparationSpace(state, true)\n    ch = state.input.charCodeAt(state.position)\n\n    if ((state.line === entryLine || state.lineIndent > nodeIndent) && ch !== 0) {\n      throwError(state, 'bad indentation of a mapping entry')\n    } else if (state.lineIndent < nodeIndent) {\n      break\n    }\n  }\n\n  if (!detected) return false\n  if (atExplicitKey) addEmptyScalarEvent(state)\n  if (mappingOpened) addPopEvent(state)\n  return true\n}\n\nfunction parseNode (\n  state: ParserState,\n  parentIndent: number,\n  nodeContext: NodeContext,\n  allowToSeek: boolean,\n  allowCompact: boolean,\n  allowPropertyMapping = true\n): boolean {\n  if (state.depth >= state.maxDepth) {\n    throwError(state, `nesting exceeded maxDepth (${state.maxDepth})`)\n  }\n\n  state.depth++\n\n  let indentStatus = 1\n  let atNewLine = false\n  let hasContent = false\n  let propertyStart: ParserSnapshot | null = null\n  const props = emptyProperties()\n\n  let allowBlockScalars = nodeContext === CONTEXT_BLOCK_OUT || nodeContext === CONTEXT_BLOCK_IN\n  let allowBlockCollections = allowBlockScalars\n  const allowBlockStyles = allowBlockScalars\n\n  if (allowToSeek && skipSeparationSpace(state, true)) {\n    atNewLine = true\n\n    if (state.lineIndent > parentIndent) {\n      indentStatus = 1\n    } else if (state.lineIndent === parentIndent) {\n      indentStatus = 0\n    } else {\n      indentStatus = -1\n    }\n  }\n\n  if (state.position === state.lineStart && testDocumentSeparator(state)) {\n    state.depth--\n    return false\n  }\n\n  if (indentStatus === 1) {\n    while (true) {\n      const ch = state.input.charCodeAt(state.position)\n      const propertyState = snapshotState(state)\n\n      if (atNewLine &&\n          indentStatus !== 1 &&\n          (ch === 0x21/* ! */ || ch === 0x26/* & */)) {\n        break\n      }\n\n      if (atNewLine &&\n          allowBlockStyles &&\n          (props.tagStart !== NO_RANGE || props.anchorStart !== NO_RANGE) &&\n          (ch === 0x21/* ! */ || ch === 0x26/* & */)) {\n        const fallbackState = snapshotState(state)\n        const flowIndent = parentIndent + 1\n        const mappingIndent = state.position - state.lineStart\n\n        if (readBlockMapping(state, mappingIndent, flowIndent, props) &&\n            state.events[fallbackState.eventsLength]?.type === EVENT_MAPPING) {\n          state.depth--\n          return true\n        }\n\n        restoreState(state, fallbackState)\n      }\n\n      if (atNewLine &&\n          ((ch === 0x21/* ! */ && props.tagStart !== NO_RANGE) ||\n           (ch === 0x26/* & */ && props.anchorStart !== NO_RANGE))) {\n        break\n      }\n\n      if (!readTagProperty(state, props, nodeContext === CONTEXT_FLOW_IN) && !readAnchorProperty(state, props)) {\n        break\n      }\n\n      if (propertyStart === null) propertyStart = propertyState\n\n      if (skipSeparationSpace(state, true)) {\n        atNewLine = true\n        allowBlockCollections = allowBlockStyles\n\n        if (state.lineIndent > parentIndent) {\n          indentStatus = 1\n        } else if (state.lineIndent === parentIndent) {\n          indentStatus = 0\n        } else {\n          indentStatus = -1\n        }\n      } else {\n        allowBlockCollections = false\n      }\n    }\n  }\n\n  if (allowBlockCollections) {\n    allowBlockCollections = atNewLine || allowCompact\n  }\n\n  if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) {\n    const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT\n      ? parentIndent\n      : parentIndent + 1\n    const blockIndent = state.position - state.lineStart\n\n    if (indentStatus === 1) {\n      if ((allowBlockCollections &&\n          (readBlockSequence(state, blockIndent, props) ||\n           readBlockMapping(state, blockIndent, flowIndent, props))) ||\n          readFlowCollection(state, flowIndent, props)) {\n        hasContent = true\n      } else {\n        const ch = state.input.charCodeAt(state.position)\n\n        if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections &&\n            ch !== 0x7C/* | */ && ch !== 0x3E/* > */) {\n          const fallbackState = snapshotState(state)\n          const propertyIndent = propertyStart.position - propertyStart.lineStart\n\n          restoreState(state, propertyStart)\n\n          if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) &&\n              state.events[fallbackState.eventsLength]?.type === EVENT_MAPPING) {\n            hasContent = true\n          } else {\n            restoreState(state, fallbackState)\n          }\n        }\n\n        if (!hasContent &&\n            ((allowBlockScalars && readBlockScalar(state, flowIndent, props)) ||\n             readSingleQuotedScalar(state, flowIndent, props) ||\n             readDoubleQuotedScalar(state, flowIndent, props) ||\n             readAlias(state, props) ||\n             readPlainScalar(state, flowIndent, nodeContext, props))) {\n          hasContent = true\n        }\n      }\n    } else if (indentStatus === 0) {\n      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props)\n    }\n  }\n\n  allowBlockScalars = allowBlockScalars && !hasContent\n\n  if (!hasContent && (props.anchorStart !== NO_RANGE || props.tagStart !== NO_RANGE || allowBlockScalars)) {\n    addScalarEvent(\n      state,\n      NO_RANGE,\n      NO_RANGE,\n      props.anchorStart,\n      props.anchorEnd,\n      props.tagStart,\n      props.tagEnd,\n      SCALAR_STYLE_PLAIN\n    )\n    hasContent = true\n  }\n\n  state.depth--\n  return hasContent || props.anchorStart !== NO_RANGE || props.tagStart !== NO_RANGE\n}\n\nfunction readDirective (state: ParserState) {\n  if (state.lineIndent > 0 || state.input.charCodeAt(state.position) !== 0x25/* % */) return false\n\n  state.position++\n  const nameStart = state.position\n\n  while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++\n\n  const name = state.input.slice(nameStart, state.position)\n  const args: string[] = []\n\n  if (name.length === 0) throwError(state, 'directive name must not be less than one character in length')\n\n  while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) {\n    while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++\n    if (state.input.charCodeAt(state.position) === 0x23/* # */ || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break\n\n    const start = state.position\n    while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++\n    args.push(state.input.slice(start, state.position))\n  }\n\n  if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state)\n\n  if (name === 'YAML') {\n    if (state.directives.some(directive => directive.kind === 'yaml')) throwError(state, 'duplication of %YAML directive')\n    if (args.length !== 1) throwError(state, 'YAML directive accepts exactly one argument')\n\n    const match = /^([0-9]+)\\.([0-9]+)$/.exec(args[0])\n    if (match === null) throwError(state, 'ill-formed argument of the YAML directive')\n    if (parseInt(match[1], 10) !== 1) throwError(state, 'unacceptable YAML version of the document')\n\n    state.directives.push({ kind: 'yaml', version: args[0] })\n  } else if (name === 'TAG') {\n    if (args.length !== 2) throwError(state, 'TAG directive accepts exactly two arguments')\n\n    const [handle, prefix] = args\n    if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, 'ill-formed tag handle (first argument) of the TAG directive')\n    if (HAS_OWN.call(state.tagHandlers, handle)) throwError(state, `there is a previously declared suffix for \"${handle}\" tag handle`)\n    if (!PATTERN_TAG_PREFIX.test(prefix)) throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive')\n    try {\n      decodeURIComponent(prefix)\n    } catch {\n      throwError(state, `tag prefix is malformed: ${prefix}`)\n    }\n\n    state.tagHandlers[handle] = prefix\n    state.directives.push({ kind: 'tag', handle, prefix })\n  }\n\n  return true\n}\n\nfunction readDocument (state: ParserState) {\n  state.directives = []\n  state.tagHandlers = Object.create(null)\n  let hasDirectives = false\n\n  skipSeparationSpace(state, true)\n\n  while (readDirective(state)) {\n    hasDirectives = true\n    skipSeparationSpace(state, true)\n  }\n\n  let explicitStart = false\n  let explicitEnd = false\n  let allowCompact = true\n\n  if (state.lineIndent === 0 &&\n      state.input.charCodeAt(state.position) === 0x2D/* - */ &&\n      state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&\n      state.input.charCodeAt(state.position + 2) === 0x2D/* - */ &&\n      isWsOrEolOrEnd(state.input.charCodeAt(state.position + 3))) {\n    explicitStart = true\n    const markerLine = state.line\n    state.position += 3\n    skipSeparationSpace(state, true)\n    allowCompact = state.line > markerLine\n  } else if (hasDirectives) {\n    throwError(state, 'directives end mark is expected')\n  }\n\n  const documentEventIndex = state.events.length\n  if (!explicitStart &&\n      state.position === state.lineStart &&\n      state.input.charCodeAt(state.position) === 0x2E/* . */ &&\n      testDocumentSeparator(state)) {\n    state.position += 3\n    skipSeparationSpace(state, true)\n    return\n  }\n\n  addDocumentEvent(state, explicitStart, false)\n  if (!parseNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, allowCompact, allowCompact)) {\n    addEmptyScalarEvent(state)\n  }\n  skipSeparationSpace(state, true)\n\n  if (state.position === state.lineStart && testDocumentSeparator(state)) {\n    explicitEnd = state.input.charCodeAt(state.position) === 0x2E/* . */\n    if (explicitEnd) {\n      const markerLine = state.line\n      state.position += 3\n      skipSeparationSpace(state, true)\n      if (state.line === markerLine && state.position < state.length) {\n        throwError(state, 'end of the stream or a document separator is expected')\n      }\n    }\n  }\n\n  const documentEvent = state.events[documentEventIndex]\n  if (documentEvent?.type === EVENT_DOCUMENT) documentEvent.explicitEnd = explicitEnd\n\n  addPopEvent(state)\n\n  if (!explicitEnd &&\n      state.position < state.length &&\n      !(state.position === state.lineStart && testDocumentSeparator(state))) {\n    throwError(state, 'end of the stream or a document separator is expected')\n  }\n}\n\nfunction parseEvents (input: string, options: ParserOptions): Event[] {\n  const length = input.length\n  const state: ParserState = {\n    ...DEFAULT_PARSER_OPTIONS,\n    ...options,\n    input: `${input}\\0`,\n    length,\n    position: 0,\n    line: 0,\n    lineStart: 0,\n    lineIndent: 0,\n    firstTabInLine: -1,\n    depth: 0,\n    directives: [],\n    tagHandlers: Object.create(null),\n    events: []\n  }\n\n  const nullpos = input.indexOf('\\0')\n  if (nullpos !== -1) throwErrorAt(input, nullpos, 'null byte is not allowed in input', state.filename)\n\n  if (state.input.charCodeAt(state.position) === 0xFEFF) state.position++\n\n  while (state.position < state.length) {\n    skipSeparationSpace(state, true)\n    if (state.position >= state.length) break\n    const documentStart = state.position\n    readDocument(state)\n    if (state.position === documentStart) {\n      // Internal progress guard: if readDocument() ever returns without\n      // consuming input, stop here instead of looping forever.\n      /* c8 ignore next */\n      throwError(state, 'can not read a document')\n    }\n  }\n\n  return state.events\n}\n\nexport {\n  parseEvents,\n  DEFAULT_PARSER_OPTIONS,\n  type ParserOptions\n}\n","import { YAMLException } from './common/exception.ts'\nimport { pick } from './common/object.ts'\nimport {\n  constructFromEvents,\n  DEFAULT_CONSTRUCTOR_OPTIONS,\n  type ConstructorOptions\n} from './parser/constructor.ts'\nimport {\n  parseEvents,\n  DEFAULT_PARSER_OPTIONS,\n  type ParserOptions\n} from './parser/parser.ts'\n\n// `source` is supplied by `loadDocuments` itself, not by the public caller.\ninterface LoadOptions extends ParserOptions, Omit<ConstructorOptions, 'source'> {}\n\ntype LoadAllIterator = (document: unknown) => void\n\nconst DEFAULT_LOAD_OPTIONS: Required<LoadOptions> = {\n  ...DEFAULT_PARSER_OPTIONS,\n  ...DEFAULT_CONSTRUCTOR_OPTIONS\n}\n\nfunction loadDocuments (input: string, options: LoadOptions = {}) {\n  const opts = { ...DEFAULT_LOAD_OPTIONS, ...options }\n  const source = String(input)\n\n  const PARSER_OPT_KEYS = Object.keys(DEFAULT_PARSER_OPTIONS) as\n    (keyof typeof DEFAULT_PARSER_OPTIONS)[]\n  const CONSTRUCTOR_OPT_KEYS = Object.keys(DEFAULT_CONSTRUCTOR_OPTIONS) as\n    (keyof typeof DEFAULT_CONSTRUCTOR_OPTIONS)[]\n\n  const events = parseEvents(source, pick(opts, PARSER_OPT_KEYS))\n  return constructFromEvents(events, { ...pick(opts, CONSTRUCTOR_OPT_KEYS), source })\n}\n\n// Signatures with iterator are deprecated. Will be removed in the next versions.\nfunction loadAll (input: string, options?: LoadOptions): unknown[]\nfunction loadAll (input: string, iterator: null, options?: LoadOptions): unknown[]\nfunction loadAll (input: string, iterator: LoadAllIterator, options?: LoadOptions): void\nfunction loadAll (\n  input: string,\n  iteratorOrOptions?: LoadAllIterator | LoadOptions | null,\n  options?: LoadOptions\n) {\n  let iterator: LoadAllIterator | null = null\n\n  if (typeof iteratorOrOptions === 'function') {\n    iterator = iteratorOrOptions\n  } else if (iteratorOrOptions !== null && typeof iteratorOrOptions === 'object') {\n    options = iteratorOrOptions\n  }\n\n  const documents = loadDocuments(input, options)\n\n  if (iterator === null) return documents\n  for (const document of documents) iterator(document)\n}\n\nfunction load (input: string, options?: LoadOptions) {\n  const documents = loadDocuments(input, options)\n\n  if (documents.length === 0) throw new YAMLException('expected a document, but the input is empty')\n  if (documents.length === 1) return documents[0]\n\n  throw new YAMLException('expected a single document in the stream, but found more')\n}\n\nexport {\n  load,\n  loadAll,\n  type LoadOptions\n}\n","// AST → text. Walks the node `kind`; the scalar machinery (style selection,\n// quoting, folding) is driven by node text, not by sniffing a JS value.\n\nimport { YAMLException } from '../common/exception.ts'\nimport { tagNameShort } from '../common/tagname.ts'\nimport { type Schema } from '../schema.ts'\nimport { NOT_RESOLVED, type ScalarTagDefinition } from '../tag.ts'\nimport {\n  type Node,\n  type Document,\n  type ScalarNode,\n  type SequenceNode,\n  type MappingNode\n} from './nodes.ts'\n\nconst CHAR_BOM = 0xFEFF\nconst CHAR_TAB = 0x09 /* Tab */\nconst CHAR_LINE_FEED = 0x0A /* LF */\nconst CHAR_CARRIAGE_RETURN = 0x0D /* CR */\nconst CHAR_SPACE = 0x20 /* Space */\nconst CHAR_EXCLAMATION = 0x21 /* ! */\nconst CHAR_DOUBLE_QUOTE = 0x22 /* \" */\nconst CHAR_SHARP = 0x23 /* # */\nconst CHAR_PERCENT = 0x25 /* % */\nconst CHAR_AMPERSAND = 0x26 /* & */\nconst CHAR_SINGLE_QUOTE = 0x27 /* ' */\nconst CHAR_ASTERISK = 0x2A /* * */\nconst CHAR_COMMA = 0x2C /* , */\nconst CHAR_MINUS = 0x2D /* - */\nconst CHAR_COLON = 0x3A /* : */\nconst CHAR_EQUALS = 0x3D /* = */\nconst CHAR_GREATER_THAN = 0x3E /* > */\nconst CHAR_QUESTION = 0x3F /* ? */\nconst CHAR_COMMERCIAL_AT = 0x40 /* @ */\nconst CHAR_LEFT_SQUARE_BRACKET = 0x5B /* [ */\nconst CHAR_RIGHT_SQUARE_BRACKET = 0x5D /* ] */\nconst CHAR_GRAVE_ACCENT = 0x60 /* ` */\nconst CHAR_LEFT_CURLY_BRACKET = 0x7B /* { */\nconst CHAR_VERTICAL_LINE = 0x7C /* | */\nconst CHAR_RIGHT_CURLY_BRACKET = 0x7D /* } */\n\nconst ESCAPE_SEQUENCES: Record<number, string> = {}\n\nESCAPE_SEQUENCES[0x00] = '\\\\0'\nESCAPE_SEQUENCES[0x07] = '\\\\a'\nESCAPE_SEQUENCES[0x08] = '\\\\b'\nESCAPE_SEQUENCES[0x09] = '\\\\t'\nESCAPE_SEQUENCES[0x0A] = '\\\\n'\nESCAPE_SEQUENCES[0x0B] = '\\\\v'\nESCAPE_SEQUENCES[0x0C] = '\\\\f'\nESCAPE_SEQUENCES[0x0D] = '\\\\r'\nESCAPE_SEQUENCES[0x1B] = '\\\\e'\nESCAPE_SEQUENCES[0x22] = '\\\\\"'\nESCAPE_SEQUENCES[0x5C] = '\\\\\\\\'\nESCAPE_SEQUENCES[0x85] = '\\\\N'\nESCAPE_SEQUENCES[0xA0] = '\\\\_'\nESCAPE_SEQUENCES[0x2028] = '\\\\L'\nESCAPE_SEQUENCES[0x2029] = '\\\\P'\n\ninterface PresenterOptions {\n  schema: Schema\n  indent?: number\n  seqNoIndent?: boolean\n  seqInlineFirst?: boolean\n  sortKeys?: boolean | ((a: any, b: any) => number)\n  lineWidth?: number\n  flowBracketPadding?: boolean\n  flowSkipCommaSpace?: boolean\n  flowSkipColonSpace?: boolean\n  quoteFlowKeys?: boolean\n  quoteStyle?: 'single' | 'double'\n  forceQuotes?: boolean\n  tagBeforeAnchor?: boolean\n}\n\nconst DEFAULT_PRESENTER_OPTIONS: Required<Omit<PresenterOptions, 'schema'>> = {\n  indent: 2,\n  seqNoIndent: false,\n  seqInlineFirst: true,\n  sortKeys: false,\n  lineWidth: 80,\n  flowBracketPadding: false,\n  flowSkipCommaSpace: false,\n  flowSkipColonSpace: false,\n  quoteFlowKeys: false,\n  quoteStyle: 'single',\n  forceQuotes: false,\n  tagBeforeAnchor: false\n}\n\ninterface PresenterState extends Required<PresenterOptions> {\n  defaultScalarTagName: string\n  implicitResolvers: readonly ScalarTagDefinition[]\n}\n\nfunction nodeTagShort (node: Node) {\n  return node.style.tagged ? node.tag : tagNameShort(node.tag)\n}\n\nfunction createPresenterState (options: PresenterOptions): PresenterState {\n  const opts = {\n    ...DEFAULT_PRESENTER_OPTIONS,\n    ...options\n  }\n\n  return {\n    ...opts,\n    defaultScalarTagName: opts.schema.defaultScalarTag.tagName,\n    implicitResolvers: opts.schema.implicitScalarTags\n  }\n}\n\nfunction encodeNonPrintable (character: number) {\n  // YAML non-printable code points are all in BMP (max FFFF);\n  // astral code points are printable and can't come here.\n  const string = character.toString(16).toUpperCase()\n  const handle = character <= 0xFF ? 'x' : 'u'\n  const length = character <= 0xFF ? 2 : 4\n\n  return `\\\\${handle}${'0'.repeat(length - string.length)}${string}`\n}\n\n// Indents every line in a string. Empty lines (\\n only) are not indented.\nfunction indentString (string: string, spaces: number) {\n  const ind = ' '.repeat(spaces)\n  let position = 0\n  let result = ''\n  const length = string.length\n\n  while (position < length) {\n    let line\n    const next = string.indexOf('\\n', position)\n    if (next === -1) {\n      line = string.slice(position)\n      position = length\n    } else {\n      line = string.slice(position, next + 1)\n      position = next + 1\n    }\n\n    if (line.length && line !== '\\n') result += ind\n\n    result += line\n  }\n\n  return result\n}\n\nfunction generateNextLine (state: PresenterState, level: number) {\n  return `\\n${' '.repeat(state.indent * level)}`\n}\n\n// Indentation/width numbers that govern how a scalar lays out at `level`.\n// Scalar-only: collections compute their own indent via `generateNextLine`.\n//   indent      - spaces prepended to the scalar's content (block styles)\n//   blockIndent - the block indentation indicator digit (`|2` / `>2`); at the\n//                 document root (level 0) it is one greater than the spaces we\n//                 actually prepend (reader applies it relative to parent n = -1)\n//   lineWidth   - fold width at this depth, shrinking monotonically toward\n//                 min(state.lineWidth, 40) as indentation deepens; -1 = no limit\nfunction scalarLayout (state: PresenterState, level: number) {\n  const indent = state.indent * Math.max(1, level) // no 0-indent scalars\n  const blockIndent = level === 0 ? state.indent + 1 : state.indent\n  const lineWidth = (state.lineWidth === -1)\n    ? -1\n    : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent)\n\n  return { indent, blockIndent, lineWidth }\n}\n\nfunction resolveImplicitTag (state: PresenterState, str: string) {\n  for (let index = 0, length = state.implicitResolvers.length; index < length; index += 1) {\n    const tagDefinition = state.implicitResolvers[index]\n\n    if (tagDefinition.resolve(str, false, tagDefinition.tagName) !== NOT_RESOLVED) {\n      return tagDefinition.tagName\n    }\n  }\n\n  return state.defaultScalarTagName\n}\n\n// [33] s-white ::= s-space | s-tab\nfunction isWhitespace (c: number) {\n  return c === CHAR_SPACE || c === CHAR_TAB\n}\n\n// Mirrors parser.testDocumentSeparator(): `---` and `...` are document\n// markers when followed by separation whitespace, a line break, or EOF.\nfunction startsWithDocumentSeparator (string: string) {\n  const marker = string.charCodeAt(0)\n\n  if ((marker !== CHAR_MINUS && marker !== 0x2E/* . */) ||\n      string.charCodeAt(1) !== marker || string.charCodeAt(2) !== marker) return false\n\n  if (string.length === 3) return true\n\n  const following = string.charCodeAt(3)\n  return isWhitespace(following) ||\n    following === CHAR_CARRIAGE_RETURN || following === CHAR_LINE_FEED\n}\n\n// Returns true if the character can be printed without escaping.\n// From YAML 1.2: \"any allowed characters known to be non-printable\n// should also be escaped. [However,] This isn’t mandatory\"\n// Derived from nb-char - \\t - #x85 - #xA0 - #x2028 - #x2029.\nfunction isPrintable (c: number) {\n  return (c >= 0x00020 && c <= 0x00007E) ||\n    ((c >= 0x000A1 && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) ||\n    ((c >= 0x0E000 && c <= 0x00FFFD) && c !== CHAR_BOM) ||\n    (c >= 0x10000 && c <= 0x10FFFF)\n}\n\n// [34] ns-char ::= nb-char - s-white\n// [27] nb-char ::= c-printable - b-char - c-byte-order-mark\n// [26] b-char  ::= b-line-feed | b-carriage-return\n// Including s-white (for some reason, examples doesn't match specs in this aspect)\n// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark\nfunction isNsCharOrWhitespace (c: number) {\n  return isPrintable(c) &&\n    c !== CHAR_BOM &&\n    // - b-char\n    c !== CHAR_CARRIAGE_RETURN &&\n    c !== CHAR_LINE_FEED\n}\n\n// [127]  ns-plain-safe(c) ::= c = flow-out  ⇒ ns-plain-safe-out\n//                             c = flow-in   ⇒ ns-plain-safe-in\n//                             c = block-key ⇒ ns-plain-safe-out\n//                             c = flow-key  ⇒ ns-plain-safe-in\n// [128] ns-plain-safe-out ::= ns-char\n// [129]  ns-plain-safe-in ::= ns-char - c-flow-indicator\n// [130]  ns-plain-char(c) ::=  ( ns-plain-safe(c) - “:” - “#” )\n//                            | ( /* An ns-char preceding */ “#” )\n//                            | ( “:” /* Followed by an ns-plain-safe(c) */ )\n// `prev` is the previous code point, or -1 when `c` is the first character\n// (no preceding character). -1 is not a valid code point, so it can never\n// collide with a real one and safely disables the prev-dependent cases below.\nfunction isPlainSafe (c: number, prev: number, inblock: boolean) {\n  const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c)\n  const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c)\n  return (\n    (\n      // ns-plain-safe\n      inblock // c = flow-in\n        ? cIsNsCharOrWhitespace\n        : cIsNsCharOrWhitespace &&\n          // - c-flow-indicator\n          c !== CHAR_COMMA &&\n          c !== CHAR_LEFT_SQUARE_BRACKET &&\n          c !== CHAR_RIGHT_SQUARE_BRACKET &&\n          c !== CHAR_LEFT_CURLY_BRACKET &&\n          c !== CHAR_RIGHT_CURLY_BRACKET\n    ) &&\n    // ns-plain-char\n    c !== CHAR_SHARP && // false on '#'\n    !(prev === CHAR_COLON && !cIsNsChar)\n  ) || // false on ': '\n  (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) || // change to true on '[^ ]#'\n  (prev === CHAR_COLON && cIsNsChar &&\n    // outside block context a following c-flow-indicator is not ns-plain-safe\n    (inblock ||\n      (c !== CHAR_COMMA &&\n       c !== CHAR_LEFT_SQUARE_BRACKET &&\n       c !== CHAR_RIGHT_SQUARE_BRACKET &&\n       c !== CHAR_LEFT_CURLY_BRACKET &&\n       c !== CHAR_RIGHT_CURLY_BRACKET))) // change to true on ':[^ ]'\n}\n\n// Simplified test for values allowed as the first character in plain style.\nfunction isPlainSafeFirst (c: number) {\n  // Uses a subset of ns-char - c-indicator\n  // where ns-char = nb-char - s-white.\n  // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part\n  return isPrintable(c) &&\n    c !== CHAR_BOM &&\n    !isWhitespace(c) && // - s-white\n    // - (c-indicator ::=\n    // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”\n    c !== CHAR_MINUS &&\n    c !== CHAR_QUESTION &&\n    c !== CHAR_COLON &&\n    c !== CHAR_COMMA &&\n    c !== CHAR_LEFT_SQUARE_BRACKET &&\n    c !== CHAR_RIGHT_SQUARE_BRACKET &&\n    c !== CHAR_LEFT_CURLY_BRACKET &&\n    c !== CHAR_RIGHT_CURLY_BRACKET &&\n    // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “\"”\n    c !== CHAR_SHARP &&\n    c !== CHAR_AMPERSAND &&\n    c !== CHAR_ASTERISK &&\n    c !== CHAR_EXCLAMATION &&\n    c !== CHAR_VERTICAL_LINE &&\n    c !== CHAR_EQUALS &&\n    c !== CHAR_GREATER_THAN &&\n    c !== CHAR_SINGLE_QUOTE &&\n    c !== CHAR_DOUBLE_QUOTE &&\n    // | “%” | “@” | “`”)\n    c !== CHAR_PERCENT &&\n    c !== CHAR_COMMERCIAL_AT &&\n    c !== CHAR_GRAVE_ACCENT\n}\n\nfunction isPlainSafeAtStart (string: string, inblock: boolean) {\n  const first = codePointAt(string, 0)\n\n  if (isPlainSafeFirst(first)) return true\n\n  if (\n    string.length > 1 &&\n    (first === CHAR_MINUS || first === CHAR_QUESTION || first === CHAR_COLON)\n  ) {\n    const second = codePointAt(string, 1)\n\n    // The relaxed isPlainSafe() accepts whitespace inside a scalar, but the\n    // indicator exception in ns-plain-first requires an ns-plain-safe\n    // *non-space* character. Otherwise `- value` and `? value` start block\n    // collections instead of plain scalars.\n    return !isWhitespace(second) && isPlainSafe(second, first, inblock)\n  }\n\n  return false\n}\n\n// Simplified test for values allowed as the last character in plain style.\nfunction isPlainSafeLast (c: number) {\n  // just not whitespace or colon, it will be checked to be plain character later\n  return !isWhitespace(c) && c !== CHAR_COLON\n}\n\n// Same as 'string'.codePointAt(pos), but works in older browsers.\nfunction codePointAt (string: string, pos: number) {\n  const first = string.charCodeAt(pos)\n  let second\n\n  if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {\n    second = string.charCodeAt(pos + 1)\n    if (second >= 0xDC00 && second <= 0xDFFF) {\n      // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n      return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000\n    }\n  }\n  return first\n}\n\nfunction needIndentIndicator (string: string) {\n  const leadingSpaceRe = /^\\n* /\n  return leadingSpaceRe.test(string)\n}\n\nconst STYLE_PLAIN = 1\nconst STYLE_SINGLE = 2\nconst STYLE_LITERAL = 3\nconst STYLE_FOLDED = 4\nconst STYLE_DOUBLE = 5\n\ntype ScalarStyleId =\n  typeof STYLE_PLAIN |\n  typeof STYLE_SINGLE |\n  typeof STYLE_LITERAL |\n  typeof STYLE_FOLDED |\n  typeof STYLE_DOUBLE\n\n// Determines which scalar styles are possible and returns the preferred style.\n// lineWidth = -1 => no limit.\n// Pre-conditions: str.length > 0.\n// Post-conditions:\n//    STYLE_PLAIN or STYLE_SINGLE => no \\n are in the string.\n//    STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).\n//    STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).\nfunction chooseScalarStyle (state: PresenterState, string: string, layout: ReturnType<typeof scalarLayout>,\n  singleLineOnly: boolean, forceQuote: boolean, inblock: boolean): ScalarStyleId {\n  const { blockIndent, lineWidth } = layout\n  let i\n  let char = 0\n  let prevChar = -1 // -1 = no previous character yet (see isPlainSafe)\n  let hasLineBreak = false\n  let hasFoldableLine = false // only checked if shouldTrackWidth\n  const shouldTrackWidth = lineWidth !== -1\n  let previousLineBreak = -1 // count the first line correctly\n  // Document markers are recognized as whole tokens at the start of a line,\n  // so character-level plain-scalar checks alone cannot reject them.\n  let plain = !startsWithDocumentSeparator(string) &&\n    isPlainSafeAtStart(string, inblock) &&\n    isPlainSafeLast(codePointAt(string, string.length - 1))\n\n  if (singleLineOnly || forceQuote) {\n    // Case: no block styles.\n    // Check for disallowed characters to rule out plain and single.\n    for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n      char = codePointAt(string, i)\n      if (!isPrintable(char)) {\n        return STYLE_DOUBLE\n      }\n      plain = plain && isPlainSafe(char, prevChar, inblock)\n      prevChar = char\n    }\n  } else {\n    // Case: block styles permitted.\n    for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n      char = codePointAt(string, i)\n      if (char === CHAR_LINE_FEED) {\n        hasLineBreak = true\n        // Check if any line can be folded.\n        if (shouldTrackWidth) {\n          hasFoldableLine = hasFoldableLine ||\n            // Foldable line = too long, and not more-indented.\n            (i - previousLineBreak - 1 > lineWidth &&\n             string[previousLineBreak + 1] !== ' ')\n          previousLineBreak = i\n        }\n      } else if (!isPrintable(char)) {\n        return STYLE_DOUBLE\n      }\n      plain = plain && isPlainSafe(char, prevChar, inblock)\n      prevChar = char\n    }\n    // in case the end is missing a \\n\n    hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&\n      (i - previousLineBreak - 1 > lineWidth &&\n       string[previousLineBreak + 1] !== ' '))\n  }\n  // Although every style can represent \\n without escaping, prefer block styles\n  // for multiline, since they're more readable and they don't add empty lines.\n  // Also prefer folding a super-long line.\n  if (!hasLineBreak && !hasFoldableLine) {\n    // Syntactic verdict only: whether the bare text round-trips to the node's\n    // tag is a semantic check the caller applies (see resolveScalarStyle).\n    if (plain && !forceQuote) return STYLE_PLAIN\n    return state.quoteStyle === 'double' ? STYLE_DOUBLE : STYLE_SINGLE\n  }\n  // Edge case: block indentation indicator can only have one digit.\n  if (blockIndent > 9 && needIndentIndicator(string)) {\n    return STYLE_DOUBLE\n  }\n  // At this point we know block styles are valid.\n  // Prefer literal style unless we want to fold.\n  return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL\n}\n\n// Renders `string` in the given numeric style with the given layout.\n// NB. We drop the last trailing newline (if any) of a returned block scalar\n//  since the dumper adds its own newline. This always works:\n//    • No ending newline => unaffected; already using strip \"-\" chomping.\n//    • Ending newline    => removed then restored.\n//  Importantly, this keeps the \"+\" chomp indicator from gaining an extra line.\nfunction renderScalarStyle (string: string, style: ScalarStyleId, layout: ReturnType<typeof scalarLayout>) {\n  const { indent, blockIndent, lineWidth } = layout\n\n  switch (style) {\n    case STYLE_PLAIN:\n      return encodeFlowBreaks(string, indent)\n    case STYLE_SINGLE:\n      return `'${encodeFlowBreaks(string, indent).replace(/'/g, \"''\")}'`\n    case STYLE_LITERAL:\n      return '|' + blockHeader(string, blockIndent) +\n        dropEndingNewline(indentString(string, indent))\n    case STYLE_FOLDED:\n      return '>' + blockHeader(string, blockIndent) +\n        dropEndingNewline(indentString(foldBlockScalar(string, lineWidth), indent))\n    case STYLE_DOUBLE:\n      return `\"${escapeString(string)}\"`\n  }\n}\n\n// Picks the scalar style for `node`: a style hint carried on the node wins,\n// otherwise the style chosen by the machinery. Returns a numeric STYLE_*.\nfunction resolveScalarStyle (state: PresenterState, node: ScalarNode,\n  layout: ReturnType<typeof scalarLayout>, iskey: boolean, inblock: boolean): ScalarStyleId {\n  // Without knowing if keys are implicit/explicit, assume implicit for safety.\n  const singleLineOnly = iskey || !inblock\n\n  // Style hints carried on the node take precedence. They were valid in their\n  // original context; only a parent change can break them, and only block\n  // styles in a single-line context — quoted styles survive any context. A\n  // rejected block hint falls through to selection by content below.\n  if (node.style.singleQuoted) return STYLE_SINGLE\n  if (node.style.doubleQuoted) return STYLE_DOUBLE\n  if (!singleLineOnly) {\n    if (node.style.literal) return STYLE_LITERAL\n    if (node.style.folded) return STYLE_FOLDED\n  }\n\n  const string = node.value\n\n  if (string.length === 0) {\n    // An empty scalar is safe when its tag is explicit or resolves back to the\n    // node tag (notably, the default null representation). A real empty string\n    // does neither and therefore remains quoted.\n    if (node.style.tagged || resolveImplicitTag(state, string) === node.tag) return STYLE_PLAIN\n    return state.quoteStyle === 'double' ? STYLE_DOUBLE : STYLE_SINGLE\n  }\n\n  // v4's forceQuotes deliberately excluded keys. Keys are still quoted when\n  // syntax or tag resolution requires it, using quoteStyle as the preference.\n  const style = chooseScalarStyle(\n    state, string, layout, singleLineOnly, state.forceQuotes && !iskey, inblock)\n\n  // Plain writes no tag, so it round-trips only if the bare text resolves back\n  // to the node's tag (or the tag gets printed explicitly). Else downgrade.\n  // Downgrade to the preferred quote style here.\n  if (style === STYLE_PLAIN && !node.style.tagged && resolveImplicitTag(state, string) !== node.tag) {\n    return state.quoteStyle === 'double' ? STYLE_DOUBLE : STYLE_SINGLE\n  }\n  return style\n}\n\n// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.\nfunction blockHeader (string: string, indentPerLevel: number) {\n  const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''\n\n  // note the special case: the string '\\n' counts as a \"trailing\" empty line.\n  const clip = string[string.length - 1] === '\\n'\n  const keep = clip && (string[string.length - 2] === '\\n' || string === '\\n')\n  const chomp = keep ? '+' : (clip ? '' : '-')\n\n  return `${indentIndicator}${chomp}\\n`\n}\n\n// Flow scalars (plain, single-quoted) fold line breaks: a run of k source line\n// breaks reparses to k-1 literal `\\n`. So a single break is just line-wrapping\n// (folds back to a space), while a literal `\\n` in the value must be emitted as\n// a blank line (two breaks). Encode each run of p literal `\\n` as p+1 breaks and\n// indent the following content line so the continuation isn't read as a new node\n// (a bare break would yield invalid \"deficient indentation\" output).\n// `foldBlockScalar` can't be reused here: it treats a leading space as a\n// \"more-indented\" line and suppresses the doubling, which a flow scalar must not.\nfunction encodeFlowBreaks (string: string, indent: number) {\n  let nextLF = string.indexOf('\\n')\n  if (nextLF === -1) return string\n\n  const pad = ' '.repeat(indent)\n  let result = string.slice(0, nextLF) // first line follows the quote, no indent\n\n  const lineRe = /(\\n+)([^\\n]*)/g\n  lineRe.lastIndex = nextLF\n  let match\n  while ((match = lineRe.exec(string))) {\n    const breaks = match[1].length\n    const line = match[2]\n    // line === '' only at the end (the greedy \\n+ leaves no empty line mid-string);\n    // pad it so the closing quote carries indent instead of sitting at column 0.\n    result += '\\n'.repeat(breaks + 1) + pad + line\n  }\n\n  return result\n}\n\n// Strips one trailing newline from a block scalar: the dumper adds its own,\n// so without this a \"+\" (keep) chomp would gain an extra blank line.\nfunction dropEndingNewline (string: string) {\n  return string[string.length - 1] === '\\n' ? string.slice(0, -1) : string\n}\n\n// Note: a long line without a suitable break point will exceed the width limit.\n// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.\nfunction foldBlockScalar (string: string, width: number) {\n  // In folded style, $k$ consecutive newlines output as $k+1$ newlines—\n  // unless they're before or after a more-indented line, or at the very\n  // beginning or end, in which case $k$ maps to $k$.\n  // Therefore, parse each chunk as newline(s) followed by a content line.\n  const lineRe = /(\\n+)([^\\n]*)/g\n\n  // first line (possibly an empty line)\n  let nextLF = string.indexOf('\\n')\n  if (nextLF === -1) nextLF = string.length\n  lineRe.lastIndex = nextLF\n  let result = foldLine(string.slice(0, nextLF), width)\n  // If we haven't reached the first content line yet, don't add an extra \\n.\n  let prevMoreIndented = string[0] === '\\n' || string[0] === ' '\n  let moreIndented\n\n  // rest of the lines\n  let match\n  while ((match = lineRe.exec(string))) {\n    const prefix = match[1]\n    const line = match[2]\n\n    moreIndented = (line[0] === ' ')\n    result += prefix +\n      ((!prevMoreIndented && !moreIndented && line !== '') ? '\\n' : '') +\n      foldLine(line, width)\n    prevMoreIndented = moreIndented\n  }\n\n  return result\n}\n\n// Greedy line breaking.\n// Picks the longest line under the limit each time,\n// otherwise settles for the shortest line over the limit.\n// NB. More-indented lines *cannot* be folded, as that would add an extra \\n.\nfunction foldLine (line: string, width: number) {\n  if (line === '' || line[0] === ' ') return line\n\n  // Since a more-indented line adds a \\n, breaks can't be followed by a space.\n  const breakRe = / [^ ]/g // note: the match index will always be <= length-2.\n  let match\n  // start is an inclusive index. end, curr, and next are exclusive.\n  let start = 0\n  let end\n  let curr = 0\n  let next = 0\n  let result = ''\n\n  // Invariants: 0 <= start <= length-1.\n  //   0 <= curr <= next <= max(0, length-2). curr - start <= width.\n  // Inside the loop:\n  //   A match implies length >= 2, so curr and next are <= length-2.\n  while ((match = breakRe.exec(line))) {\n    next = match.index\n    // maintain invariant: curr - start <= width\n    if (next - start > width) {\n      end = (curr > start) ? curr : next // derive end <= length-2\n      result += `\\n${line.slice(start, end)}`\n      // skip the space that was output as \\n\n      start = end + 1                    // derive start <= length-1\n    }\n    curr = next\n  }\n\n  // By the invariants, start <= length-1, so there is something left over.\n  // It is either the whole string or a part starting from non-whitespace.\n  result += '\\n'\n  // Insert a break if the remainder is too long and there is a break available.\n  if (line.length - start > width && curr > start) {\n    result += `${line.slice(start, curr)}\\n${line.slice(curr + 1)}`\n  } else {\n    result += line.slice(start)\n  }\n\n  return result.slice(1) // drop extra \\n joiner\n}\n\nfunction escapeString (string: string) {\n  let result = ''\n  let char = 0\n\n  for (let i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {\n    char = codePointAt(string, i)\n    const escapeSeq = ESCAPE_SEQUENCES[char]\n\n    if (escapeSeq) {\n      result += escapeSeq\n      continue\n    }\n\n    if (isPrintable(char)) {\n      result += string[i]\n      if (char >= 0x10000) result += string[i + 1]\n      continue\n    }\n\n    result += encodeNonPrintable(char)\n  }\n\n  return result\n}\n\nfunction writeFlowSequence (state: PresenterState, level: number, node: SequenceNode) {\n  let result = ''\n\n  for (let index = 0, length = node.items.length; index < length; index += 1) {\n    const item = writeNode(state, level, node.items[index], {})\n    if (result !== '') result += `,${!state.flowSkipCommaSpace ? ' ' : ''}`\n    result += item\n  }\n\n  const pad = state.flowBracketPadding && result !== '' ? ' ' : ''\n  return `[${pad}${result}${pad}]`\n}\n\nfunction writeBlockSequence (state: PresenterState, level: number, node: SequenceNode, compact: boolean) {\n  let result = ''\n\n  for (let index = 0, length = node.items.length; index < length; index += 1) {\n    const item = writeNode(state, level + 1, node.items[index],\n      { block: true, compact: state.seqInlineFirst, isblockseq: true })\n\n    if (!compact || result !== '') {\n      result += generateNextLine(state, level)\n    }\n\n    // No trailing space when the value renders empty (e.g. null → '').\n    if (item === '' || CHAR_LINE_FEED === item.charCodeAt(0)) {\n      result += '-'\n    } else {\n      result += '- '\n    }\n\n    result += item\n  }\n\n  return result\n}\n\nfunction writeFlowMapping (state: PresenterState, level: number, node: MappingNode) {\n  let result = ''\n  const items = sortMappingItems(state, node.items)\n\n  for (const { key, value } of items) {\n    let pairBuffer = ''\n    if (result !== '') pairBuffer += `,${!state.flowSkipCommaSpace ? ' ' : ''}`\n\n    const keyText = writeNode(state, level, key, { iskey: true })\n    const explicitPair = keyText.length > 1024\n\n    if (explicitPair) {\n      pairBuffer += '? '\n    } else if (state.quoteFlowKeys) {\n      pairBuffer += '\"'\n    }\n\n    const valueText = writeNode(state, level, value, {})\n    // No separating space when the value renders empty (e.g. null → '').\n    const sep = state.flowSkipColonSpace || valueText === '' ? '' : ' '\n\n    pairBuffer += `${keyText}${state.quoteFlowKeys && !explicitPair ? '\"' : ''}:${sep}${valueText}`\n\n    result += pairBuffer\n  }\n\n  const pad = state.flowBracketPadding && result !== '' ? ' ' : ''\n  return `{${pad}${result}${pad}}`\n}\n\n// A scalar key sorts by its text; the default sort and a custom comparator both\n// see that, matching the original keys-array sort.\nfunction sortKeyValue (key: Node): any {\n  return key.kind === 'scalar' ? key.value : key\n}\n\nfunction sortMappingItems (state: PresenterState, items: MappingNode['items']) {\n  if (!state.sortKeys) return items\n\n  const copy = items.slice()\n\n  if (state.sortKeys === true) {\n    copy.sort((a, b) => {\n      const x = sortKeyValue(a.key)\n      const y = sortKeyValue(b.key)\n      if (x < y) return -1\n      if (x > y) return 1\n      return 0\n    })\n  } else {\n    const fn = state.sortKeys\n    copy.sort((a, b) => fn(sortKeyValue(a.key), sortKeyValue(b.key)))\n  }\n\n  return copy\n}\n\nfunction writeBlockMapping (state: PresenterState, level: number, node: MappingNode, compact: boolean) {\n  let result = ''\n  const items = sortMappingItems(state, node.items)\n\n  for (let index = 0, length = items.length; index < length; index += 1) {\n    let pairBuffer = ''\n\n    if (!compact || result !== '') {\n      pairBuffer += generateNextLine(state, level)\n    }\n\n    const { key, value } = items[index]\n\n    // A block key — a block collection (mapping/sequence) or a block scalar\n    // (literal/folded) — can't sit on a `key:` line, so it's written with block\n    // context and the pair takes the explicit `? key / : value` form. A simple\n    // scalar key stays inline (flow-vs-block is invisible there).\n    const keyIsBlock =\n      ((key.kind === 'mapping' || key.kind === 'sequence') &&\n        !key.style.flow && key.items.length !== 0) ||\n      (key.kind === 'scalar' && (key.style.literal || key.style.folded))\n\n    // The `?`/`:` indicators shift content right like a `-`, so a block key or\n    // value that stays on the indicator line keeps its indentation under\n    // seqNoIndent (`isblockseq`). One that drops to its own line (tag/anchor)\n    // collapses to the parent indent, so leave the flag off there.\n    const keyText = keyIsBlock\n      ? writeNode(state, level + 1, key,\n        { block: true, compact: true, isblockseq: !cannotBeCompact(state, key, level + 1) })\n      : writeNode(state, level + 1, key, { block: true, compact: true, iskey: true })\n\n    // Block key, over-long key, or multiline scalar key forces explicit form.\n    // Multiline isn't a spec requirement — just matches pyyaml's simple-key rule.\n    const keyHasLineBreak = key.kind === 'scalar' && key.value.indexOf('\\n') !== -1\n    const explicitPair = keyIsBlock || keyHasLineBreak || keyText.length > 1024\n\n    if (explicitPair) {\n      if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) {\n        pairBuffer += '?'\n      } else {\n        pairBuffer += '? '\n      }\n    }\n\n    pairBuffer += keyText\n\n    if (explicitPair) {\n      pairBuffer += generateNextLine(state, level)\n    }\n\n    const valueText = writeNode(state, level + 1, value,\n      { block: true, compact: explicitPair, isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1) })\n\n    // Keep a space before the colon when the key text ends in a leading\n    // property rather than scalar content, so the colon can't be read as part\n    // of it. Two cases: an inline alias key (`*b : v`), and an empty scalar key\n    // whose whole text is its anchor/tag (`&a :`, `!!str :`) — without the\n    // space `&a:` reparses as an anchored value, dropping the null key.\n    const keyIsBareProps = key.kind === 'scalar' && key.value === '' &&\n      keyText !== '' &&\n      keyText.charCodeAt(keyText.length - 1) !== CHAR_SINGLE_QUOTE &&\n      keyText.charCodeAt(keyText.length - 1) !== CHAR_DOUBLE_QUOTE\n    const keyColonSep = !explicitPair && (key.kind === 'alias' || keyIsBareProps) ? ' ' : ''\n\n    // No trailing space when the value renders empty (e.g. null → '').\n    if (valueText === '' || CHAR_LINE_FEED === valueText.charCodeAt(0)) {\n      pairBuffer += `${keyColonSep}:`\n    } else {\n      pairBuffer += `${keyColonSep}: `\n    }\n\n    pairBuffer += valueText\n\n    result += pairBuffer\n  }\n\n  return result\n}\n\n// Where a node sits relative to its parent — drives layout/style decisions.\n// All flags default to false (the flow-context, non-key, non-compact case).\ninterface NodeContext {\n  block?: boolean      // block context (vs flow); propagates downward\n  compact?: boolean    // may start on the current line (no leading newline)\n  iskey?: boolean      // node is a mapping key\n  isblockseq?: boolean // content follows an indicator (`-`, or `?`/`:` in an\n                       // explicit pair) that already shifted it right; keeps\n                       // its indentation under seqNoIndent\n}\n\n// A node can't sit compact on its parent's indicator (`-`/`?`/`:`) line when it\n// carries leading props (tag/anchor) that would collide with the indicator, or\n// when the indent step is too narrow for the 2-char indicator. Such a node drops\n// to its own line; a block collection that does so also collapses its seqNoIndent\n// indentation back to the parent.\nfunction cannotBeCompact (state: PresenterState, node: Node, level: number) {\n  return node.style.tagged || node.anchor !== undefined || (state.indent < 2 && level > 0)\n}\n\nfunction writeNode (state: PresenterState, level: number, node: Node, ctx: NodeContext): string {\n  if (node.kind === 'alias') return `*${node.anchor}`\n\n  const { block = false, iskey = false, isblockseq = false } = ctx\n  let compact = ctx.compact ?? false\n\n  const hasAnchor = node.anchor !== undefined\n\n  if (cannotBeCompact(state, node, level)) {\n    compact = false\n  }\n\n  let body: string\n  let shouldPrintTag = node.style.tagged\n  const useBlockCollection = block &&\n    (node.kind === 'mapping' || node.kind === 'sequence') &&\n    !node.style.flow && node.items.length !== 0\n\n  if (node.kind === 'mapping') {\n    if (useBlockCollection) {\n      body = writeBlockMapping(state, level, node, compact)\n    } else {\n      body = writeFlowMapping(state, level, node)\n    }\n  } else if (node.kind === 'sequence') {\n    if (useBlockCollection) {\n      if (state.seqNoIndent && !isblockseq && level > 0) {\n        body = writeBlockSequence(state, level - 1, node, compact)\n      } else {\n        body = writeBlockSequence(state, level, node, compact)\n      }\n    } else {\n      body = writeFlowSequence(state, level, node)\n    }\n  } else {\n    const layout = scalarLayout(state, level)\n    const style = resolveScalarStyle(state, node, layout, iskey, block)\n    body = renderScalarStyle(node.value, style, layout)\n    shouldPrintTag = node.style.tagged || (style !== STYLE_PLAIN && node.tag !== state.defaultScalarTagName)\n  }\n\n  // An indicator plus its mandatory separator occupies 2 columns. For wider\n  // indentation, pad a compact block collection so its first item starts at\n  // the same column as the following items.\n  if (useBlockCollection && compact && level > 0 && state.indent > 2) {\n    body = `${' '.repeat(state.indent - 2)}${body}`\n  }\n\n  if (shouldPrintTag || hasAnchor) {\n    const props: string[] = []\n    const tag = shouldPrintTag ? nodeTagShort(node) : null\n    const anchor = hasAnchor ? `&${node.anchor}` : null\n\n    if (state.tagBeforeAnchor) {\n      if (tag !== null) props.push(tag)\n      if (anchor !== null) props.push(anchor)\n    } else {\n      if (anchor !== null) props.push(anchor)\n      if (tag !== null) props.push(tag)\n    }\n\n    // No separator when the body is empty (e.g. `&anchor` on a null node) or\n    // already starts on its own line.\n    const sep = body === '' || body.charCodeAt(0) === CHAR_LINE_FEED ? '' : ' '\n    body = `${props.join(' ')}${sep}${body}`\n  }\n\n  return body\n}\n\n// A bare (untagged, unanchored) non-empty block collection: writeNode renders it\n// in compact form with its first item on the opening line. That works mid-stream,\n// but right after a `---` the first item must drop to the next line. A tag/anchor\n// already forces the body onto its own line, so those stay on the `---` line.\nfunction rootStartsOwnLine (node: Node) {\n  return (node.kind === 'sequence' || node.kind === 'mapping') &&\n    !node.style.flow &&\n    node.items.length !== 0 &&\n    !node.style.tagged &&\n    node.anchor === undefined\n}\n\n// A document whose serialization ends with a keep-chomped (`+`) block scalar is\n// open-ended: the trailing blank line(s) would otherwise be ambiguous, so it\n// needs a `...` terminator. Mirrors the keep test in `blockHeader`.\nfunction isOpenEnded (node: Node) {\n  // Descend to the last leaf, always taking the last item of a block collection\n  // (a flow collection renders on one line, so it ends the document itself).\n  let leaf = node\n  while ((leaf.kind === 'sequence' || leaf.kind === 'mapping') &&\n    !leaf.style.flow && leaf.items.length !== 0) {\n    leaf = leaf.kind === 'sequence'\n      ? leaf.items[leaf.items.length - 1]\n      : leaf.items[leaf.items.length - 1].value\n  }\n\n  if (leaf.kind !== 'scalar' || !(leaf.style.literal || leaf.style.folded)) return false\n  const { value } = leaf\n  // Keep chomping: ends in a blank line (`\\n\\n`) or is a lone `\\n`.\n  return value.endsWith('\\n\\n') || value === '\\n'\n}\n\nfunction writeDocumentDirectives (doc: Document) {\n  let result = ''\n\n  for (const directive of doc.directives) {\n    if (directive.kind === 'yaml') {\n      result += `%YAML ${directive.version}\\n`\n      continue\n    }\n\n    const { handle, prefix } = directive\n    result += `%TAG ${handle} ${prefix}\\n`\n  }\n\n  return result\n}\n\n// Documents → text, including the trailing newline.\nfunction present (documents: Document[], options: PresenterOptions): string {\n  const state = createPresenterState(options)\n  let result = ''\n  let previousEnded = false\n\n  for (let index = 0; index < documents.length; index += 1) {\n    const doc = documents[index]\n    const directives = writeDocumentDirectives(doc)\n    const hasDirectives = directives !== ''\n    const marker = doc.explicitStart || hasDirectives || (index > 0 && !previousEnded)\n\n    result += directives\n\n    if (doc.contents === null) {\n      if (marker) result += '---\\n'\n    } else if (marker) {\n      const body = writeNode(state, 0, doc.contents, { block: true, compact: true })\n      // Content shares the `---` line, except: an empty render (no separator at\n      // all), a bare block collection (wraps to the next line), or directives\n      // forcing `---` onto its own line.\n      const sep = body === '' ? '' : (hasDirectives || rootStartsOwnLine(doc.contents) ? '\\n' : ' ')\n      result += `---${sep}${body}\\n`\n    } else {\n      result += writeNode(state, 0, doc.contents, { block: true, compact: true }) + '\\n'\n    }\n\n    previousEnded = doc.explicitEnd || (doc.contents !== null && isOpenEnded(doc.contents))\n    if (previousEnded) {\n      result += '...\\n'\n    }\n  }\n\n  return result\n}\n\nexport {\n  DEFAULT_PRESENTER_OPTIONS,\n  present,\n  type PresenterOptions\n}\n","import { YAML11_SCHEMA, type Schema } from './schema.ts'\nimport { jsToAst } from './ast/from_js.ts'\nimport { visit, VISIT_SKIP } from './ast/visit.ts'\nimport { type Document } from './ast/nodes.ts'\nimport {\n  DEFAULT_PRESENTER_OPTIONS,\n  present,\n  type PresenterOptions\n} from './ast/presenter.ts'\nimport { pick } from './common/object.ts'\nimport { NOT_RESOLVED } from './tag.ts'\nimport { intCoreTag } from './tag/scalar/int_core.ts'\nimport { intYaml11Tag } from './tag/scalar/int_yaml11.ts'\nimport { floatCoreTag } from './tag/scalar/float_core.ts'\nimport { floatYaml11Tag } from './tag/scalar/float_yaml11.ts'\n\ninterface DumpOptions extends Omit<PresenterOptions, 'schema'> {\n  schema?: Schema\n  skipInvalid?: boolean\n  noRefs?: boolean\n  flowLevel?: number\n  transform?: (documents: Document[]) => void\n}\n\n// YAML 1.1 misses YAML 1.2 `0o...` ints and exponent-only floats.\n// Combine resolvers so all possible collisions are quoted.\nconst DEFAULT_DUMP_SCHEMA = YAML11_SCHEMA.withTags(\n  {\n    ...intYaml11Tag,\n    resolve: (source, isExplicit, tagName) => {\n      const result = intYaml11Tag.resolve(source, isExplicit, tagName)\n      return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result\n    }\n  },\n  {\n    ...floatYaml11Tag,\n    resolve: (source, isExplicit, tagName) => {\n      const result = floatYaml11Tag.resolve(source, isExplicit, tagName)\n      return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result\n    }\n  }\n)\n\nconst DEFAULT_DUMP_OPTIONS: Required<DumpOptions> = {\n  ...DEFAULT_PRESENTER_OPTIONS,\n  schema: DEFAULT_DUMP_SCHEMA,\n  skipInvalid: false,\n  noRefs: false,\n  flowLevel: -1,\n  transform: () => {}\n}\n\n// Options that need the JS value (tags, format, dedup) go to `jsToAst`; purely\n// presentational ones go to `present`.\nfunction dump (input: any, options: DumpOptions = {}) {\n  const opts = { ...DEFAULT_DUMP_OPTIONS, ...options }\n\n  const documents = jsToAst(input, opts.schema, {\n    noRefs: opts.noRefs,\n    skipInvalid: opts.skipInvalid\n  })\n\n  // flowLevel: every node at this depth switches to flow; the presenter forces\n  // everything below into flow too, so the walk stops there.\n  if (opts.flowLevel >= 0) {\n    visit(documents, (node, ctx) => {\n      if (ctx.depth < opts.flowLevel) return\n      node.style.flow = true\n      return VISIT_SKIP\n    })\n  }\n\n  opts.transform(documents)\n\n  const PRESENTER_OPT_KEYS = Object.keys(DEFAULT_PRESENTER_OPTIONS) as\n    (keyof typeof DEFAULT_PRESENTER_OPTIONS)[]\n\n  return present(documents, { ...pick(opts, PRESENTER_OPT_KEYS), schema: opts.schema })\n}\n\nexport {\n  dump,\n\n  type DumpOptions\n}\n","import { ParserError } from \"../util/errors.js\";\nimport { binaryTag, CORE_SCHEMA, load, loadAll, mergeTag, omapTag, pairsTag, setTag, timestampTag } from \"js-yaml\";\n// Match js-yaml v4's default schema for the fallback parser. In v4, JSON_SCHEMA\n// and CORE_SCHEMA behaved identically; v5's CORE_SCHEMA preserves that behavior,\n// including null values for omitted mapping values and strings for date-like data.\nconst legacyDefaultSchema = CORE_SCHEMA.withTags(timestampTag, mergeTag, binaryTag, omapTag, pairsTag, setTag);\nexport default {\n    /**\n     * The order that this parser will run, in relation to other parsers.\n     */\n    order: 200,\n    /**\n     * Whether to allow \"empty\" files. This includes zero-byte files, as well as empty JSON objects.\n     */\n    allowEmpty: true,\n    /**\n     * Determines whether this parser can parse a given file reference.\n     * Parsers that match will be tried, in order, until one successfully parses the file.\n     * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case\n     * every parser will be tried.\n     */\n    canParse: [\".yaml\", \".yml\", \".json\"], // JSON is valid YAML\n    /**\n     * Parses the given file as YAML\n     *\n     * @param file           - An object containing information about the referenced file\n     * @param file.url       - The full URL of the referenced file\n     * @param file.extension - The lowercased file extension (e.g. \".txt\", \".html\", etc.)\n     * @param file.data      - The file contents. This will be whatever data type was returned by the resolver\n     * @returns\n     */\n    async parse(file) {\n        let data = file.data;\n        if (Buffer.isBuffer(data)) {\n            data = data.toString();\n        }\n        if (typeof data === \"string\") {\n            try {\n                return load(data, { schema: CORE_SCHEMA });\n            }\n            catch {\n                try {\n                    // Fall back to js-yaml v4's extended default schema.\n                    return load(data, { schema: legacyDefaultSchema });\n                }\n                catch (e) {\n                    // js-yaml v5 throws for empty streams, whereas v4 returned undefined.\n                    // Preserve the parser's allowEmpty behavior for blank/comment-only files.\n                    try {\n                        if (loadAll(data, { schema: CORE_SCHEMA }).length === 0) {\n                            return undefined;\n                        }\n                    }\n                    catch {\n                        // Preserve the more useful fallback parser error below.\n                    }\n                    throw new ParserError(e?.message || \"Parser Error\", file.url);\n                }\n            }\n        }\n        else {\n            // data is already a JavaScript value (object, array, number, null, NaN, etc.)\n            return data;\n        }\n    },\n};\n","import { ParserError } from \"../util/errors.js\";\nconst TEXT_REGEXP = /\\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)(?:[?#].*)?$/i;\nexport default {\n    /**\n     * The order that this parser will run, in relation to other parsers.\n     */\n    order: 300,\n    /**\n     * Whether to allow \"empty\" files (zero bytes).\n     */\n    allowEmpty: true,\n    /**\n     * The encoding that the text is expected to be in.\n     */\n    encoding: \"utf8\",\n    /**\n     * Determines whether this parser can parse a given file reference.\n     * Parsers that return true will be tried, in order, until one successfully parses the file.\n     * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case\n     * every parser will be tried.\n     */\n    canParse(file) {\n        // Use this parser if the file is a string or Buffer, and has a known text-based extension\n        return (typeof file.data === \"string\" || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url);\n    },\n    /**\n     * Parses the given file as text\n     */\n    parse(file) {\n        if (typeof file.data === \"string\") {\n            return file.data;\n        }\n        else if (Buffer.isBuffer(file.data)) {\n            return file.data.toString(this.encoding);\n        }\n        else {\n            throw new ParserError(\"data is not text\", file.url);\n        }\n    },\n};\n","const BINARY_REGEXP = /\\.(jpeg|jpg|gif|png|bmp|ico)(?:[?#].*)?$/i;\nexport default {\n    /**\n     * The order that this parser will run, in relation to other parsers.\n     */\n    order: 400,\n    /**\n     * Whether to allow \"empty\" files (zero bytes).\n     */\n    allowEmpty: true,\n    /**\n     * Determines whether this parser can parse a given file reference.\n     * Parsers that return true will be tried, in order, until one successfully parses the file.\n     * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case\n     * every parser will be tried.\n     */\n    canParse(file) {\n        // Use this parser if the file is a Buffer, and has a known binary extension\n        return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url);\n    },\n    /**\n     * Parses the given data as a Buffer (byte array).\n     */\n    parse(file) {\n        if (Buffer.isBuffer(file.data)) {\n            return file.data;\n        }\n        else {\n            // This will reject if data is anything other than a string or typed array\n            return Buffer.from(file.data);\n        }\n    },\n};\n","import * as url from \"../util/url.js\";\nimport { ResolverError } from \"../util/errors.js\";\nexport default {\n    /**\n     * The order that this resolver will run, in relation to other resolvers.\n     */\n    order: 100,\n    /**\n     * Determines whether this resolver can read a given file reference.\n     * Resolvers that return true will be tried, in order, until one successfully resolves the file.\n     * Resolvers that return false will not be given a chance to resolve the file.\n     */\n    canRead(file) {\n        return url.isFileSystemPath(file.url);\n    },\n    /**\n     * Reads the given file and returns its raw contents as a Buffer.\n     */\n    async read(file) {\n        let path;\n        const fs = await import(\"fs\");\n        try {\n            path = url.toFileSystemPath(file.url);\n        }\n        catch (err) {\n            const e = err;\n            e.message = `Malformed URI: ${file.url}: ${e.message}`;\n            throw new ResolverError(e, file.url);\n        }\n        // strip trailing slashes\n        if (path.endsWith(\"/\") || path.endsWith(\"\\\\\")) {\n            path = path.slice(0, -1);\n        }\n        try {\n            return await fs.promises.readFile(path);\n        }\n        catch (err) {\n            const e = err;\n            e.message = `Error opening file ${path}: ${e.message}`;\n            throw new ResolverError(e, path);\n        }\n    },\n};\n","import * as url from \"../util/url.js\";\nimport { ResolverError } from \"../util/errors.js\";\nexport default {\n    /**\n     * The order that this resolver will run, in relation to other resolvers.\n     */\n    order: 200,\n    /**\n     * HTTP headers to send when downloading files.\n     *\n     * @example:\n     * {\n     *   \"User-Agent\": \"JSON Schema $Ref Parser\",\n     *   Accept: \"application/json\"\n     * }\n     */\n    headers: null,\n    /**\n     * HTTP request timeout (in milliseconds).\n     */\n    timeout: 60_000, // 60 seconds\n    /**\n     * The maximum number of HTTP redirects to follow.\n     * To disable automatic following of redirects, set this to zero.\n     */\n    redirects: 5,\n    /**\n     * The `withCredentials` option of XMLHttpRequest.\n     * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication\n     */\n    withCredentials: false,\n    /**\n     * Set this to `false` if you want to allow unsafe URLs (e.g., `127.0.0.1`, localhost, and other internal URLs).\n     */\n    safeUrlResolver: true,\n    /**\n     * Determines whether this resolver can read a given file reference.\n     * Resolvers that return true will be tried in order, until one successfully resolves the file.\n     * Resolvers that return false will not be given a chance to resolve the file.\n     */\n    canRead(file) {\n        return url.isHttp(file.url) && (!this.safeUrlResolver || !url.isUnsafeUrl(file.url));\n    },\n    /**\n     * Reads the given URL and returns its raw contents as a Buffer.\n     */\n    read(file) {\n        const u = url.parse(file.url);\n        if (typeof window !== \"undefined\" && !u.protocol) {\n            // Use the protocol of the current page\n            u.protocol = url.parse(location.href).protocol;\n        }\n        return download(u, this);\n    },\n};\n/**\n * Downloads the given file.\n * @returns\n * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error.\n */\nasync function download(u, httpOptions, _redirects) {\n    u = url.parse(u);\n    const redirects = _redirects || [];\n    redirects.push(u.href);\n    let pendingResponse;\n    try {\n        let resolvedAddresses;\n        if (httpOptions.safeUrlResolver) {\n            const safety = await url.resolveUrlSafety(u.href);\n            if (safety.unsafe) {\n                throw new Error(`Unsafe URL blocked by safeUrlResolver: ${u.href}`);\n            }\n            resolvedAddresses = safety.addresses;\n        }\n        pendingResponse = await get(u, httpOptions, resolvedAddresses);\n        const res = pendingResponse.response;\n        if (res.status >= 400) {\n            const error = new Error(`HTTP ERROR ${res.status}`);\n            error.status = res.status;\n            throw error;\n        }\n        else if (res.status >= 300) {\n            if (!Number.isNaN(httpOptions.redirects) && redirects.length > httpOptions.redirects) {\n                const error = new Error(`Error downloading ${redirects[0]}. \\nToo many redirects: \\n  ${redirects.join(\" \\n  \")}`);\n                error.status = res.status;\n                throw new ResolverError(error);\n            }\n            else {\n                const location = getHeader(res, \"location\");\n                if (!location) {\n                    const error = new Error(`HTTP ${res.status} redirect with no location header`);\n                    error.status = res.status;\n                    throw error;\n                }\n                const redirectTo = url.resolve(u.href, location);\n                const redirectOptions = url.parse(redirectTo).origin === u.origin ? httpOptions : withoutSensitiveHeaders(httpOptions);\n                return download(redirectTo, redirectOptions, redirects);\n            }\n        }\n        else {\n            if (res.body) {\n                const buf = await res.arrayBuffer();\n                return Buffer.from(buf);\n            }\n            return Buffer.alloc(0);\n        }\n    }\n    catch (err) {\n        const cause = err instanceof Error ? err : new Error(String(err));\n        const wrappedError = new Error(`Error downloading ${u.href}: ${cause.message}`, { cause });\n        if (\"code\" in cause) {\n            wrappedError.code = cause.code;\n        }\n        throw new ResolverError(wrappedError, u.href);\n    }\n    finally {\n        pendingResponse?.cancelTimeout();\n    }\n}\n/**\n * Sends an HTTP GET request.\n * The promise resolves with the HTTP Response object and a timeout cleanup\n * function. The caller keeps the timeout active until it has consumed the\n * response body.\n */\nasync function get(u, httpOptions, resolvedAddresses) {\n    const pinnedTransport = resolvedAddresses && resolvedAddresses.length > 0 ? await createPinnedTransport(u, resolvedAddresses) : undefined;\n    const dispatcher = pinnedTransport?.dispatcher;\n    let controller;\n    let timeoutId;\n    if (httpOptions.timeout && typeof AbortController !== \"undefined\") {\n        const abortController = new AbortController();\n        controller = abortController;\n        timeoutId = setTimeout(() => abortController.abort(), httpOptions.timeout);\n    }\n    const cancelTimeout = () => {\n        if (timeoutId !== undefined) {\n            clearTimeout(timeoutId);\n            timeoutId = undefined;\n        }\n        if (dispatcher && !dispatcher.destroyed) {\n            void dispatcher.destroy().catch(() => undefined);\n        }\n    };\n    try {\n        const requestOptions = {\n            method: \"GET\",\n            headers: httpOptions.headers || {},\n            credentials: httpOptions.withCredentials ? \"include\" : \"same-origin\",\n            redirect: \"manual\",\n            signal: controller ? controller.signal : null,\n        };\n        if (dispatcher) {\n            requestOptions.dispatcher = dispatcher;\n        }\n        const response = pinnedTransport\n            ? (await pinnedTransport.fetch(u, requestOptions))\n            : await fetch(u, requestOptions);\n        return { response, cancelTimeout };\n    }\n    catch (error) {\n        cancelTimeout();\n        throw error;\n    }\n}\n/**\n * Creates a per-request dispatcher whose DNS callback can only return addresses\n * from the validation lookup. The URL hostname is still used for the Host\n * header and TLS SNI/certificate verification.\n */\nasync function createPinnedTransport(requestUrl, resolvedAddresses) {\n    // Keep the Node-only implementation out of browser module graphs.\n    const undiciModuleName = \"undici\";\n    const undici = (await import(undiciModuleName));\n    const expectedHostname = normalizeLookupHostname(requestUrl.hostname);\n    const pinnedAddresses = resolvedAddresses.map(({ address, family }) => ({ address, family }));\n    const lookup = (hostname, options, callback) => {\n        const normalizedHostname = normalizeLookupHostname(hostname);\n        const requestedFamily = options.family === \"IPv4\" ? 4 : options.family === \"IPv6\" ? 6 : options.family || 0;\n        const candidates = pinnedAddresses.filter(({ family }) => requestedFamily === 0 || family === requestedFamily);\n        if (normalizedHostname !== expectedHostname || candidates.length === 0) {\n            const error = new Error(`No validated address is available for ${hostname}`);\n            error.code = \"ENOTFOUND\";\n            callback(error, \"\", 0);\n        }\n        else if (options.all) {\n            callback(null, candidates);\n        }\n        else {\n            const selected = candidates[0];\n            callback(null, selected.address, selected.family);\n        }\n    };\n    return {\n        dispatcher: new undici.Agent({\n            connect: { lookup },\n            autoSelectFamily: true,\n        }),\n        fetch: (input, init) => undici.fetch(input, init),\n    };\n}\nfunction normalizeLookupHostname(hostname) {\n    return hostname\n        .replace(/^\\[|\\]$/g, \"\")\n        .replace(/\\.+$/, \"\")\n        .toLowerCase();\n}\nfunction getHeader(response, name) {\n    return response.headers.get(name);\n}\nfunction withoutSensitiveHeaders(httpOptions) {\n    if (!httpOptions.headers) {\n        return httpOptions;\n    }\n    const headers = new Headers(httpOptions.headers);\n    headers.delete(\"authorization\");\n    headers.delete(\"proxy-authorization\");\n    headers.delete(\"cookie\");\n    return { ...httpOptions, headers };\n}\n","import jsonParser from \"./parsers/json.js\";\nimport yamlParser from \"./parsers/yaml.js\";\nimport textParser from \"./parsers/text.js\";\nimport binaryParser from \"./parsers/binary.js\";\nimport fileResolver from \"./resolvers/file.js\";\nimport httpResolver from \"./resolvers/http.js\";\nexport const getJsonSchemaRefParserDefaultOptions = () => {\n    const defaults = {\n        /**\n         * Determines how different types of files will be parsed.\n         *\n         * You can add additional parsers of your own, replace an existing one with\n         * your own implementation, or disable any parser by setting it to false.\n         */\n        parse: {\n            json: { ...jsonParser },\n            yaml: { ...yamlParser },\n            text: { ...textParser },\n            binary: { ...binaryParser },\n        },\n        /**\n         * Determines how JSON References will be resolved.\n         *\n         * You can add additional resolvers of your own, replace an existing one with\n         * your own implementation, or disable any resolver by setting it to false.\n         */\n        resolve: {\n            file: { ...fileResolver },\n            http: { ...httpResolver },\n            /**\n             * Determines whether external $ref pointers will be resolved.\n             * If this option is disabled, then none of above resolvers will be called.\n             * Instead, external $ref pointers will simply be ignored.\n             *\n             * @type {boolean}\n             */\n            external: true,\n        },\n        /**\n         * By default, JSON Schema $Ref Parser throws the first error it encounters. Setting `continueOnError` to `true`\n         * causes it to keep processing as much as possible and then throw a single error that contains all errors\n         * that were encountered.\n         */\n        continueOnError: false,\n        /**\n         * Determines the types of JSON references that are allowed.\n         */\n        bundle: {\n            /**\n             * A function, called for each path, which can return true to stop this path and all\n             * subpaths from being processed further. This is useful in schemas where some\n             * subpaths contain literal $ref keys that should not be changed.\n             *\n             * @type {function}\n             */\n            excludedPathMatcher: () => false,\n        },\n        /**\n         * Determines the types of JSON references that are allowed.\n         */\n        dereference: {\n            /**\n             * Dereference circular (recursive) JSON references?\n             * If false, then a {@link ReferenceError} will be thrown if a circular reference is found.\n             * If \"ignore\", then circular references will not be dereferenced.\n             *\n             * @type {boolean|string}\n             */\n            circular: true,\n            /**\n             * A function, called for each path, which can return true to stop this path and all\n             * subpaths from being dereferenced further. This is useful in schemas where some\n             * subpaths contain literal $ref keys that should not be dereferenced.\n             *\n             * @type {function}\n             */\n            excludedPathMatcher: () => false,\n            referenceResolution: \"relative\",\n            mergeKeys: true,\n        },\n        mutateInputSchema: true,\n    };\n    return defaults;\n};\nexport const getNewOptions = (options) => {\n    const newOptions = getJsonSchemaRefParserDefaultOptions();\n    if (options) {\n        merge(newOptions, options);\n    }\n    return newOptions;\n};\n/**\n * Merges the properties of the source object into the target object.\n *\n * @param target - The object that we're populating\n * @param source - The options that are being merged\n * @returns\n */\nfunction merge(target, source) {\n    if (isMergeable(source)) {\n        // prevent prototype pollution\n        const keys = Object.keys(source).filter((key) => ![\"__proto__\", \"constructor\", \"prototype\"].includes(key));\n        for (let i = 0; i < keys.length; i++) {\n            const key = keys[i];\n            const sourceSetting = source[key];\n            const targetSetting = target[key];\n            if (isMergeable(sourceSetting)) {\n                // It's a nested object, so merge it recursively\n                target[key] = merge(targetSetting || {}, sourceSetting);\n            }\n            else if (sourceSetting !== undefined) {\n                // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.\n                target[key] = sourceSetting;\n            }\n        }\n    }\n    return target;\n}\n/**\n * Determines whether the given value can be merged,\n * or if it is a scalar value that should just override the target value.\n *\n * @param val\n * @returns\n */\nfunction isMergeable(val) {\n    return (val &&\n        typeof val === \"object\" &&\n        !Array.isArray(val) &&\n        !(val instanceof RegExp) &&\n        !(val instanceof Date) &&\n        !(typeof Headers !== \"undefined\" && val instanceof Headers));\n}\n","import { getNewOptions } from \"./options.js\";\n/**\n * Normalizes the given arguments, accounting for optional args.\n */\nexport function normalizeArgs(_args) {\n    let path;\n    let schema;\n    let options;\n    let callback;\n    const args = Array.prototype.slice.call(_args);\n    if (typeof args[args.length - 1] === \"function\") {\n        // The last parameter is a callback function\n        callback = args.pop();\n    }\n    if (typeof args[0] === \"string\") {\n        // The first parameter is the path\n        path = args[0];\n        if (typeof args[2] === \"object\") {\n            // The second parameter is the schema, and the third parameter is the options\n            schema = args[1];\n            options = args[2];\n        }\n        else {\n            // The second parameter is the options\n            schema = undefined;\n            options = args[1];\n        }\n    }\n    else {\n        // The first parameter is the schema\n        path = \"\";\n        schema = args[0];\n        options = args[1];\n    }\n    try {\n        options = getNewOptions(options);\n    }\n    catch (e) {\n        console.error(`JSON Schema Ref Parser: Error normalizing options: ${e}`);\n    }\n    if (!options.mutateInputSchema && typeof schema === \"object\") {\n        // Make a deep clone of the schema, so that we don't alter the original object\n        schema = JSON.parse(JSON.stringify(schema));\n    }\n    return {\n        path,\n        schema,\n        options,\n        callback,\n    };\n}\nexport default normalizeArgs;\n","import $Ref from \"./ref.js\";\nimport Pointer from \"./pointer.js\";\nimport parse from \"./parse.js\";\nimport * as url from \"./util/url.js\";\nimport { isHandledError } from \"./util/errors.js\";\nimport { getSchemaBasePath, getSchemaIdMode } from \"./util/schema-resources.js\";\n/**\n * Crawls the JSON schema, finds all external JSON references, and resolves their values.\n * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.\n *\n * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.\n *\n * @returns\n * The promise resolves once all JSON references in the schema have been resolved,\n * including nested references that are contained in externally-referenced files.\n */\nfunction resolveExternal(parser, options) {\n    if (!options.resolve?.external) {\n        // Nothing to resolve, so exit early\n        return Promise.resolve();\n    }\n    try {\n        const rootScopeBase = parser.$refs._root$Ref.dynamicIdScope\n            ? getSchemaBasePath(parser.$refs._root$Ref.path, parser.schema, parser.$refs._root$Ref.legacyIdScope)\n            : parser.$refs._root$Ref.path;\n        // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);\n        const promises = crawl(parser.schema, parser.$refs._root$Ref.path + \"#\", rootScopeBase, parser.$refs._root$Ref.dynamicIdScope, parser.$refs._root$Ref.legacyIdScope, parser.$refs, options);\n        return Promise.all(promises);\n    }\n    catch (e) {\n        return Promise.reject(e);\n    }\n}\n/**\n * Recursively crawls the given value, and resolves any external JSON references.\n *\n * @param obj - The value to crawl. If it's not an object or array, it will be ignored.\n * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash\n * @param {boolean} external - Whether `obj` was found in an external document.\n * @param $refs\n * @param options\n * @param seen - Internal.\n *\n * @returns\n * Returns an array of promises. There will be one promise for each JSON reference in `obj`.\n * If `obj` does not contain any JSON references, then the array will be empty.\n * If any of the JSON references point to files that contain additional JSON references,\n * then the corresponding promise will internally reference an array of promises.\n */\nfunction crawl(obj, path, scopeBase, dynamicIdScope, legacyIdScope, $refs, options, seen, external) {\n    seen ||= new Set();\n    let promises = [];\n    if (obj && typeof obj === \"object\" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {\n        seen.add(obj); // Track previously seen objects to avoid infinite recursion\n        const currentScopeBase = scopeBase;\n        if ($Ref.isExternal$Ref(obj)) {\n            promises.push(resolve$Ref(obj, path, currentScopeBase, dynamicIdScope, $refs, options));\n        }\n        const keys = Object.keys(obj);\n        for (const key of keys) {\n            const keyPath = Pointer.join(path, key);\n            const value = obj[key];\n            const childLegacyIdScope = getSchemaIdMode(value, legacyIdScope);\n            const childScopeBase = dynamicIdScope && value && typeof value === \"object\" && !ArrayBuffer.isView(value)\n                ? getSchemaBasePath(currentScopeBase, value, childLegacyIdScope)\n                : currentScopeBase;\n            promises = promises.concat(crawl(value, keyPath, childScopeBase, dynamicIdScope, childLegacyIdScope, $refs, options, seen, external));\n        }\n    }\n    return promises;\n}\n/**\n * Resolves the given JSON Reference, and then crawls the resulting value.\n *\n * @param $ref - The JSON Reference to resolve\n * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash\n * @param $refs\n * @param options\n *\n * @returns\n * The promise resolves once all JSON references in the object have been resolved,\n * including nested references that are contained in externally-referenced files.\n */\nasync function resolve$Ref($ref, path, scopeBase, dynamicIdScope, $refs, options) {\n    const shouldResolveOnCwd = options.dereference?.externalReferenceResolution === \"root\";\n    const resolutionBase = shouldResolveOnCwd ? url.cwd() : dynamicIdScope ? scopeBase : path;\n    const resolvedPath = url.resolve(resolutionBase, $ref.$ref);\n    const withoutHash = url.stripHash(resolvedPath);\n    // $ref.$ref = url.relative($refs._root$Ref.path, resolvedPath);\n    // Do we already have this $ref?\n    const ref = $refs._get$Ref(withoutHash);\n    if (ref) {\n        // We've already parsed this $ref, so use the existing value\n        return Promise.resolve(ref.value);\n    }\n    // Parse the $referenced file/url\n    try {\n        const reference = $ref.$ref;\n        const parseTarget = {\n            url: resolvedPath,\n            baseUrl: resolutionBase,\n        };\n        if (typeof reference === \"string\") {\n            parseTarget.reference = reference;\n        }\n        const result = await parse(parseTarget, $refs, options);\n        // Crawl the parsed value\n        // console.log('Resolving $ref pointers in %s', withoutHash);\n        const parsedRef = $refs._get$Ref(withoutHash);\n        const parsedDynamicIdScope = parsedRef?.dynamicIdScope ?? false;\n        const parsedLegacyIdScope = parsedRef?.legacyIdScope ?? false;\n        const parsedScopeBase = parsedDynamicIdScope\n            ? getSchemaBasePath(withoutHash, result, parsedLegacyIdScope)\n            : withoutHash;\n        const promises = crawl(result, withoutHash + \"#\", parsedScopeBase, parsedDynamicIdScope, parsedLegacyIdScope, $refs, options, new Set(), true);\n        return Promise.all(promises);\n    }\n    catch (err) {\n        if (!options?.continueOnError || !isHandledError(err)) {\n            throw err;\n        }\n        if ($refs._$refs[withoutHash]) {\n            err.source = decodeURI(url.stripHash(path));\n            err.path = url.safePointerToPath(url.getHash(path));\n        }\n        return [];\n    }\n}\nexport default resolveExternal;\n","import $Ref from \"./ref.js\";\nimport Pointer from \"./pointer.js\";\nimport * as url from \"./util/url.js\";\nimport { getSchemaBasePath, getSchemaId, getSchemaIdMode } from \"./util/schema-resources.js\";\n/**\n * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that\n * only has *internal* references, not any *external* references.\n * This method mutates the JSON schema object, adding new references and re-mapping existing ones.\n *\n * @param parser\n * @param options\n */\nfunction bundle(parser, options) {\n    // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);\n    const rootScopeBase = parser.$refs._root$Ref.dynamicIdScope\n        ? getSchemaBasePath(parser.$refs._root$Ref.path, parser.schema, parser.$refs._root$Ref.legacyIdScope)\n        : parser.$refs._root$Ref.path;\n    // Build an inventory of all $ref pointers in the JSON Schema\n    const inventory = [];\n    const embeddedResourcePaths = new Set([url.stripHash(parser.$refs._root$Ref.path), url.stripHash(rootScopeBase)]);\n    crawl(parser, \"schema\", parser.$refs._root$Ref.path + \"#\", rootScopeBase, parser.$refs._root$Ref.dynamicIdScope, parser.$refs._root$Ref.legacyIdScope, false, \"#\", 0, inventory, parser.$refs, options, embeddedResourcePaths, new Set());\n    // Get the root schema's $id (if any) for qualifying refs inside sub-schemas with their own $id\n    const rootId = getSchemaId(parser.schema, parser.$refs._root$Ref.legacyIdScope);\n    // Remap all $ref pointers\n    remap(inventory, options, rootId, rootScopeBase);\n    // Fix any $ref paths that traverse through other $refs (which is invalid per JSON Schema spec)\n    const bundleOptions = (options.bundle || {});\n    if (bundleOptions.optimizeInternalRefs !== false) {\n        fixRefsThroughRefs(inventory, parser.schema);\n    }\n}\n/**\n * Recursively crawls the given value, and inventories all JSON references.\n *\n * @param parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored.\n * @param key - The property key of `parent` to be crawled\n * @param path - The full path of the property being crawled, possibly with a JSON Pointer in the hash\n * @param pathFromRoot - The path of the property being crawled, from the schema root\n * @param indirections\n * @param inventory - An array of already-inventoried $ref pointers\n * @param $refs\n * @param options\n */\nfunction crawl(parent, key, path, scopeBase, dynamicIdScope, legacyIdScope, nestedIdScope, pathFromRoot, indirections, inventory, $refs, options, embeddedResourcePaths, seen) {\n    const obj = key === null ? parent : parent[key];\n    const bundleOptions = (options.bundle || {});\n    const isExcludedPath = bundleOptions.excludedPathMatcher || (() => false);\n    if (obj && typeof obj === \"object\" && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot) && !seen.has(obj)) {\n        // Input schemas are normally JSON trees, but callers can pass pre-circular\n        // JavaScript objects. Tracking identities keeps those cycles intact without\n        // recursively walking them until the call stack overflows. It also avoids\n        // repeatedly inventorying shared object instances.\n        seen.add(obj);\n        const currentScopeBase = scopeBase;\n        if ($Ref.isAllowed$Ref(obj, options)) {\n            inventory$Ref(parent, key, path, currentScopeBase, dynamicIdScope, nestedIdScope, pathFromRoot, indirections, inventory, $refs, options, embeddedResourcePaths, seen);\n        }\n        else {\n            // Crawl the object in a specific order that's optimized for bundling.\n            // This is important because it determines how `pathFromRoot` gets built,\n            // which later determines which keys get dereferenced and which ones get remapped\n            const keys = Object.keys(obj).sort((a, b) => {\n                // Most people will expect references to be bundled into the the \"definitions\" property,\n                // so we always crawl that property first, if it exists.\n                if (a === \"definitions\" || a === \"$defs\") {\n                    return -1;\n                }\n                else if (b === \"definitions\" || b === \"$defs\") {\n                    return 1;\n                }\n                else {\n                    // Otherwise, crawl the keys based on their length.\n                    // This produces the shortest possible bundled references\n                    return a.length - b.length;\n                }\n            });\n            for (const key of keys) {\n                const keyPath = Pointer.join(path, key);\n                const keyPathFromRoot = Pointer.join(pathFromRoot, key);\n                const value = obj[key];\n                const childLegacyIdScope = getSchemaIdMode(value, legacyIdScope);\n                const childScopeBase = dynamicIdScope && value && typeof value === \"object\" && !ArrayBuffer.isView(value)\n                    ? getSchemaBasePath(currentScopeBase, value, childLegacyIdScope)\n                    : currentScopeBase;\n                const childHasSchemaIdentifier = dynamicIdScope && hasSchemaIdentifier(value, childLegacyIdScope);\n                const childNestedIdScope = nestedIdScope || childHasSchemaIdentifier;\n                let childEmbeddedResourcePaths = embeddedResourcePaths;\n                if (childHasSchemaIdentifier) {\n                    childEmbeddedResourcePaths = new Set(embeddedResourcePaths);\n                    childEmbeddedResourcePaths.add(url.stripHash(childScopeBase));\n                }\n                if ($Ref.isAllowed$Ref(value, options)) {\n                    inventory$Ref(obj, key, keyPath, childScopeBase, dynamicIdScope, childNestedIdScope, keyPathFromRoot, indirections, inventory, $refs, options, childEmbeddedResourcePaths, seen);\n                }\n                else {\n                    crawl(obj, key, keyPath, childScopeBase, dynamicIdScope, childLegacyIdScope, childNestedIdScope, keyPathFromRoot, indirections, inventory, $refs, options, childEmbeddedResourcePaths, seen);\n                }\n                // We need to ensure that we have an object to work with here because we may be crawling\n                // an `examples` schema and `value` may be nullish.\n                if (value && typeof value === \"object\" && !Array.isArray(value)) {\n                    if (\"$ref\" in value) {\n                        bundleOptions?.onBundle?.(value[\"$ref\"], obj[key], obj, key);\n                    }\n                }\n            }\n        }\n    }\n}\n/**\n * Inventories the given JSON Reference (i.e. records detailed information about it so we can\n * optimize all $refs in the schema), and then crawls the resolved value.\n *\n * @param $refParent - The object that contains a JSON Reference as one of its keys\n * @param $refKey - The key in `$refParent` that is a JSON Reference\n * @param path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash\n * @param indirections - unknown\n * @param pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root\n * @param inventory - An array of already-inventoried $ref pointers\n * @param $refs\n * @param options\n */\nfunction inventory$Ref($refParent, $refKey, path, scopeBase, dynamicIdScope, nestedIdScope, pathFromRoot, indirections, inventory, $refs, options, embeddedResourcePaths, seen) {\n    const $ref = $refKey === null ? $refParent : $refParent[$refKey];\n    const shouldResolveOnCwd = $Ref.isExternal$Ref($ref) && options.dereference?.externalReferenceResolution === \"root\";\n    const resolutionBase = shouldResolveOnCwd ? url.cwd() : dynamicIdScope ? scopeBase : path;\n    const $refPath = url.resolve(resolutionBase, $ref.$ref);\n    const pointer = $refs._resolve($refPath, pathFromRoot, options);\n    if (pointer === null) {\n        return;\n    }\n    const parsed = Pointer.parse(pathFromRoot);\n    const depth = parsed.length;\n    const file = url.stripHash(pointer.path);\n    const hash = url.getHash(pointer.path);\n    const alias = $refs._aliases[file];\n    const aliasIsInRootSchema = Boolean(alias && containsObject($refs._root$Ref.value, pointer.$ref.value));\n    const external = file !== $refs._root$Ref.path && !embeddedResourcePaths.has(file) && !aliasIsInRootSchema;\n    const nestedResource = Boolean(alias) && pointer.$ref.value !== $refs._root$Ref.value;\n    const targetResourceId = getSchemaId(pointer.$ref.value, pointer.$ref.legacyIdScope);\n    const targetResourceBase = alias\n        ? pointer.$ref.path\n        : pointer.$ref.dynamicIdScope\n            ? getSchemaBasePath(pointer.$ref.path, pointer.$ref.value, pointer.$ref.legacyIdScope)\n            : pointer.$ref.path;\n    const extended = $Ref.isExtended$Ref($ref);\n    indirections += pointer.indirections;\n    const existingEntry = findInInventory(inventory, $refParent, $refKey);\n    if (existingEntry) {\n        // This $Ref has already been inventoried, so we don't need to process it again\n        if (depth < existingEntry.depth || indirections < existingEntry.indirections) {\n            removeFromInventory(inventory, existingEntry);\n        }\n        else {\n            return;\n        }\n    }\n    inventory.push({\n        $ref, // The JSON Reference (e.g. {$ref: string})\n        parent: $refParent, // The object that contains this $ref pointer\n        key: $refKey, // The key in `parent` that is the $ref pointer\n        pathFromRoot, // The path to the $ref pointer, from the JSON Schema root\n        depth, // How far from the JSON Schema root is this $ref pointer?\n        file, // The file that the $ref pointer resolves to\n        hash, // The hash within `file` that the $ref pointer resolves to\n        value: pointer.value, // The resolved value of the $ref pointer\n        circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)\n        extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to \"$ref\")\n        external, // Does this $ref pointer point to a file other than the main JSON Schema file?\n        nestedResource, // Does this $ref resolve to an embedded schema resource with its own $id?\n        indirections, // The number of indirect references that were traversed to resolve the value\n        scopeBase, // The active schema-resource base at the location of this $ref\n        dynamicIdScope, // Whether this $ref uses nested JSON Schema $id scopes\n        nestedIdScope, // Whether this $ref will remain inside a non-root $id scope after bundling\n        targetResourceBase, // The canonical URI of the resource containing the target\n        ...(targetResourceId === undefined ? {} : { targetResourceId }),\n    });\n    // Recursively crawl the resolved value\n    if (!existingEntry || external) {\n        const resolvedScopeBase = pointer.$ref.dynamicIdScope ? pointer.scopeBase : pointer.$ref.path;\n        const resolvedNestedIdScope = nestedIdScope || (pointer.$ref.dynamicIdScope && hasSchemaIdentifier(pointer.value, pointer.legacyIdScope));\n        const resolvedEmbeddedResourcePaths = new Set(embeddedResourcePaths);\n        if (pointer.value === pointer.$ref.value && hasSchemaIdentifier(pointer.$ref.value, pointer.$ref.legacyIdScope)) {\n            resolvedEmbeddedResourcePaths.add(url.stripHash(pointer.$ref.path));\n            resolvedEmbeddedResourcePaths.add(url.stripHash(resolvedScopeBase));\n        }\n        crawl(pointer.value, null, pointer.path, resolvedScopeBase, pointer.$ref.dynamicIdScope, pointer.legacyIdScope, resolvedNestedIdScope, pathFromRoot, indirections + 1, inventory, $refs, options, resolvedEmbeddedResourcePaths, seen);\n    }\n}\n/**\n * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema.\n * Each referenced value is dereferenced EXACTLY ONCE.  All subsequent references to the same\n * value are re-mapped to point to the first reference.\n *\n * @example: {\n *    first: { $ref: somefile.json#/some/part },\n *    second: { $ref: somefile.json#/another/part },\n *    third: { $ref: somefile.json },\n *    fourth: { $ref: somefile.json#/some/part/sub/part }\n *  }\n *\n * In this example, there are four references to the same file, but since the third reference points\n * to the ENTIRE file, that's the only one we need to dereference.  The other three can just be\n * remapped to point inside the third one.\n *\n * On the other hand, if the third reference DIDN'T exist, then the first and second would both need\n * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT\n * need to be dereferenced, because it can be remapped to point inside the first one.\n *\n * @param inventory\n */\nfunction remap(inventory, options, rootId, rootScopeBase) {\n    // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them\n    inventory.sort((a, b) => {\n        if (a.file !== b.file) {\n            // Group all the $refs that point to the same file\n            return a.file < b.file ? -1 : +1;\n        }\n        else if (a.hash !== b.hash) {\n            // Group all the $refs that point to the same part of the file\n            return a.hash < b.hash ? -1 : +1;\n        }\n        else if (a.circular !== b.circular) {\n            // If the $ref points to itself, then sort it higher than other $refs that point to this $ref\n            return a.circular ? -1 : +1;\n        }\n        else if (a.extended !== b.extended) {\n            // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value\n            return a.extended ? +1 : -1;\n        }\n        else if (a.indirections !== b.indirections) {\n            // Sort direct references higher than indirect references\n            return a.indirections - b.indirections;\n        }\n        else if (a.depth !== b.depth) {\n            // Sort $refs by how close they are to the JSON Schema root\n            return a.depth - b.depth;\n        }\n        else {\n            // Determine how far each $ref is from the \"definitions\" property.\n            // Most people will expect references to be bundled into the the \"definitions\" property if possible.\n            const aDefinitionsIndex = Math.max(a.pathFromRoot.lastIndexOf(\"/definitions\"), a.pathFromRoot.lastIndexOf(\"/$defs\"));\n            const bDefinitionsIndex = Math.max(b.pathFromRoot.lastIndexOf(\"/definitions\"), b.pathFromRoot.lastIndexOf(\"/$defs\"));\n            if (aDefinitionsIndex !== bDefinitionsIndex) {\n                // Give higher priority to the $ref that's closer to the \"definitions\" property\n                return bDefinitionsIndex - aDefinitionsIndex;\n            }\n            else {\n                // All else is equal, so use the shorter path, which will produce the shortest possible reference\n                return a.pathFromRoot.length - b.pathFromRoot.length;\n            }\n        }\n    });\n    let file, hash, pathFromRoot;\n    for (const entry of inventory) {\n        // console.log('Re-mapping $ref pointer \"%s\" at %s', entry.$ref.$ref, entry.pathFromRoot);\n        const bundleOpts = (options.bundle || {});\n        if (!entry.external) {\n            // This $ref already resolves to the main JSON Schema file.\n            // When optimizeInternalRefs is false, preserve the original internal ref path\n            // instead of rewriting it to the fully resolved hash. References to nested\n            // resources must also retain their resource URI so that \"#\" does not point\n            // at the document root instead.\n            if (bundleOpts.optimizeInternalRefs !== false) {\n                const targetResourceBase = url.stripHash(entry.targetResourceBase);\n                const locationResourceBase = url.stripHash(entry.scopeBase);\n                if (targetResourceBase !== locationResourceBase) {\n                    entry.$ref.$ref = referenceToResource(entry);\n                }\n                else if (!entry.nestedResource) {\n                    entry.$ref.$ref = entry.hash;\n                }\n            }\n        }\n        else if (entry.file === file && entry.hash === hash) {\n            // This $ref points to the same value as the previous $ref, so remap it to the same path\n            entry.$ref.$ref = qualifyPathFromRoot(entry, pathFromRoot, rootId, rootScopeBase);\n        }\n        else if (entry.file === file && entry.hash.indexOf(hash + \"/\") === 0) {\n            // This $ref points to a sub-value of the previous $ref, so remap it beneath that path\n            const subPath = Pointer.join(pathFromRoot, Pointer.parse(entry.hash.replace(hash, \"#\")));\n            entry.$ref.$ref = qualifyPathFromRoot(entry, subPath, rootId, rootScopeBase);\n        }\n        else {\n            // We've moved to a new file or new hash\n            file = entry.file;\n            hash = entry.hash;\n            pathFromRoot = entry.pathFromRoot;\n            // This is the first $ref to point to this value, so dereference the value.\n            // Any other $refs that point to the same value will point to this $ref instead\n            entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value, options);\n            if (entry.circular) {\n                // This $ref points to itself\n                entry.$ref.$ref = entry.pathFromRoot;\n            }\n        }\n    }\n    // we want to ensure that any $refs that point to another $ref are remapped to point to the final value\n    // let hadChange = true;\n    // while (hadChange) {\n    //   hadChange = false;\n    //   for (const entry of inventory) {\n    //     if (entry.$ref && typeof entry.$ref === \"object\" && \"$ref\" in entry.$ref) {\n    //       const resolved = inventory.find((e: InventoryEntry) => e.pathFromRoot === entry.$ref.$ref);\n    //       if (resolved) {\n    //         const resolvedPointsToAnotherRef =\n    //           resolved.$ref && typeof resolved.$ref === \"object\" && \"$ref\" in resolved.$ref;\n    //         if (resolvedPointsToAnotherRef && entry.$ref.$ref !== resolved.$ref.$ref) {\n    //           // console.log('Re-mapping $ref pointer \"%s\" at %s', entry.$ref.$ref, entry.pathFromRoot);\n    //           entry.$ref.$ref = resolved.$ref.$ref;\n    //           hadChange = true;\n    //         }\n    //       }\n    //     }\n    //   }\n    // }\n}\n/**\n * TODO\n */\nfunction findInInventory(inventory, $refParent, $refKey) {\n    for (const existingEntry of inventory) {\n        if (existingEntry && existingEntry.parent === $refParent && existingEntry.key === $refKey) {\n            return existingEntry;\n        }\n    }\n    return undefined;\n}\nfunction removeFromInventory(inventory, entry) {\n    const index = inventory.indexOf(entry);\n    inventory.splice(index, 1);\n}\n/**\n * After remapping, some $ref paths may traverse through other $ref nodes.\n * JSON pointer resolution does not follow $ref indirection, so these paths are invalid.\n * This function detects and fixes such paths by following any intermediate $refs\n * to compute a valid direct path.\n */\nfunction fixRefsThroughRefs(inventory, schema) {\n    for (const entry of inventory) {\n        if (!entry.$ref || typeof entry.$ref !== \"object\" || !(\"$ref\" in entry.$ref)) {\n            continue;\n        }\n        const refValue = entry.$ref.$ref;\n        if (typeof refValue !== \"string\" || !refValue.startsWith(\"#/\")) {\n            continue;\n        }\n        const fixedPath = resolvePathThroughRefs(schema, refValue);\n        if (fixedPath !== refValue) {\n            entry.$ref.$ref = fixedPath;\n        }\n    }\n}\n/**\n * Walks a JSON pointer path through the schema. If any intermediate value\n * is a $ref, follows it and adjusts the path accordingly.\n * Returns the corrected path that doesn't traverse through any $ref.\n */\nfunction resolvePathThroughRefs(schema, refPath) {\n    if (!refPath.startsWith(\"#/\")) {\n        return refPath;\n    }\n    const segments = refPath.slice(2).split(\"/\");\n    let current = schema;\n    const resolvedSegments = [];\n    for (const seg of segments) {\n        if (current === null || current === undefined || typeof current !== \"object\") {\n            // Can't walk further, return original path\n            return refPath;\n        }\n        const decoded = seg.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n        // If the next token is an own sibling of an extended $ref, the pointer\n        // addresses that sibling directly and must not be rewritten through the\n        // $ref target. Only follow the $ref when the literal object has no such key.\n        if (!Object.prototype.hasOwnProperty.call(current, decoded) &&\n            \"$ref\" in current &&\n            typeof current.$ref === \"string\" &&\n            current.$ref.startsWith(\"#/\")) {\n            // Follow the $ref and restart the path from its target\n            const targetSegments = current.$ref.slice(2).split(\"/\");\n            resolvedSegments.length = 0;\n            resolvedSegments.push(...targetSegments);\n            current = walkPath(schema, current.$ref);\n            if (current === null || current === undefined || typeof current !== \"object\") {\n                return refPath;\n            }\n        }\n        const idx = Array.isArray(current) ? parseInt(decoded) : decoded;\n        current = current[idx];\n        resolvedSegments.push(seg);\n    }\n    const result = \"#/\" + resolvedSegments.join(\"/\");\n    return result;\n}\n/**\n * Walks a JSON pointer path through a schema object, returning the value at that path.\n */\nfunction walkPath(schema, path) {\n    if (!path.startsWith(\"#/\")) {\n        return undefined;\n    }\n    const segments = path.slice(2).split(\"/\");\n    let current = schema;\n    for (const seg of segments) {\n        if (current === null || current === undefined || typeof current !== \"object\") {\n            return undefined;\n        }\n        const decoded = seg.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n        const idx = Array.isArray(current) ? parseInt(decoded) : decoded;\n        current = current[idx];\n    }\n    return current;\n}\n/**\n * Qualifies a root-relative JSON Pointer when it is emitted inside a nested schema resource.\n * A fragment-only reference there would resolve against the nested resource rather than the\n * bundled document root.\n */\nfunction qualifyPathFromRoot(entry, pathFromRoot, rootId, rootScopeBase) {\n    if (!entry.dynamicIdScope || !entry.nestedIdScope || !rootScopeBase) {\n        return pathFromRoot;\n    }\n    // A fragment-only reference inside a nested schema resource resolves against\n    // that resource's $id. Point back to the root resource explicitly instead.\n    // Prefer the root's declared $id when it resolves correctly from this scope;\n    // otherwise use the canonical root resource URI.\n    let rootResource = rootScopeBase;\n    if (rootId && url.stripHash(url.resolve(entry.scopeBase, rootId)) === url.stripHash(rootScopeBase)) {\n        rootResource = rootId;\n    }\n    return url.stripHash(rootResource) + pathFromRoot;\n}\nfunction referenceToResource(entry) {\n    let resourceReference = url.stripHash(entry.targetResourceBase);\n    if (typeof entry.$ref.$ref === \"string\" &&\n        url.stripHash(url.resolve(entry.scopeBase, entry.$ref.$ref)) === resourceReference) {\n        return entry.$ref.$ref;\n    }\n    if (entry.targetResourceId &&\n        url.stripHash(url.resolve(entry.scopeBase, entry.targetResourceId)) === resourceReference) {\n        resourceReference = entry.targetResourceId;\n    }\n    return entry.hash === \"#\" ? resourceReference : resourceReference + entry.hash;\n}\nfunction hasSchemaIdentifier(value, legacyIdScope = false) {\n    return getSchemaId(value, legacyIdScope) !== undefined;\n}\nfunction containsObject(root, target) {\n    if (!target || typeof target !== \"object\") {\n        return false;\n    }\n    const seen = new Set();\n    const visit = (value) => {\n        if (value === target) {\n            return true;\n        }\n        if (!value || typeof value !== \"object\" || ArrayBuffer.isView(value) || seen.has(value)) {\n            return false;\n        }\n        seen.add(value);\n        return Object.keys(value).some((key) => visit(value[key]));\n    };\n    return visit(root);\n}\nexport default bundle;\n","import $Ref from \"./ref.js\";\nimport Pointer from \"./pointer.js\";\nimport * as url from \"./util/url.js\";\nimport { getSchemaBasePath, getSchemaIdMode } from \"./util/schema-resources.js\";\nimport { TimeoutError } from \"./util/errors.js\";\nexport default dereference;\n/**\n * Crawls the JSON schema, finds all JSON references, and dereferences them.\n * This method mutates the JSON schema object, replacing JSON references with their resolved value.\n *\n * @param parser\n * @param options\n */\nfunction dereference(parser, options) {\n    const start = Date.now();\n    const rootScopeBase = parser.$refs._root$Ref.dynamicIdScope\n        ? getSchemaBasePath(parser.$refs._root$Ref.path, parser.schema, parser.$refs._root$Ref.legacyIdScope)\n        : parser.$refs._root$Ref.path;\n    // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);\n    const dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, rootScopeBase, parser.$refs._root$Ref.dynamicIdScope, parser.$refs._root$Ref.legacyIdScope, \"#\", new Set(), new Set(), new Map(), parser.$refs, options, start, 0);\n    parser.$refs.circular = dereferenced.circular;\n    parser.schema = dereferenced.value;\n}\n/**\n * Recursively crawls the given value, and dereferences any JSON references.\n *\n * @param obj - The value to crawl. If it's not an object or array, it will be ignored.\n * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash\n * @param pathFromRoot - The path of `obj` from the schema root\n * @param parents - An array of the parent objects that have already been dereferenced\n * @param processedObjects - An array of all the objects that have already been processed\n * @param dereferencedCache - An map of all the dereferenced objects\n * @param $refs\n * @param options\n * @param startTime - The time when the dereferencing started\n * @param depth - The current recursion depth\n * @returns\n */\nfunction crawl(obj, path, scopeBase, dynamicIdScope, legacyIdScope, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, depth) {\n    let dereferenced;\n    const result = {\n        value: obj,\n        circular: false,\n    };\n    checkDereferenceTimeout(startTime, options);\n    const derefOptions = (options.dereference || {});\n    const maxDepth = derefOptions.maxDepth ?? 500;\n    if (depth > maxDepth) {\n        throw new RangeError(`Maximum dereference depth (${maxDepth}) exceeded at ${pathFromRoot}. ` +\n            `This likely indicates an extremely deep or recursive schema. ` +\n            `You can increase this limit with the dereference.maxDepth option.`);\n    }\n    const isExcludedPath = derefOptions.excludedPathMatcher || (() => false);\n    if (derefOptions?.circular === \"ignore\" || !processedObjects.has(obj)) {\n        if (obj && typeof obj === \"object\" && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot)) {\n            parents.add(obj);\n            processedObjects.add(obj);\n            const currentScopeBase = scopeBase;\n            if ($Ref.isAllowed$Ref(obj, options)) {\n                dereferenced = dereference$Ref(obj, path, currentScopeBase, dynamicIdScope, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, depth);\n                result.circular = dereferenced.circular;\n                result.value = dereferenced.value;\n            }\n            else {\n                for (const key of Object.keys(obj)) {\n                    checkDereferenceTimeout(startTime, options);\n                    const keyPath = Pointer.join(path, key);\n                    const keyPathFromRoot = Pointer.join(pathFromRoot, key);\n                    if (isExcludedPath(keyPathFromRoot)) {\n                        continue;\n                    }\n                    const value = obj[key];\n                    const childLegacyIdScope = getSchemaIdMode(value, legacyIdScope);\n                    const childScopeBase = dynamicIdScope && value && typeof value === \"object\" && !ArrayBuffer.isView(value)\n                        ? getSchemaBasePath(currentScopeBase, value, childLegacyIdScope)\n                        : currentScopeBase;\n                    let circular;\n                    if ($Ref.isAllowed$Ref(value, options)) {\n                        dereferenced = dereference$Ref(value, keyPath, childScopeBase, dynamicIdScope, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, depth);\n                        circular = dereferenced.circular;\n                        // Avoid pointless mutations; breaks frozen objects to no profit\n                        if (obj[key] !== dereferenced.value) {\n                            // If we have properties we want to preserve from our dereferenced schema then we need\n                            // to copy them over to our new object.\n                            const preserved = new Map();\n                            if (derefOptions?.preservedProperties) {\n                                if (typeof obj[key] === \"object\" && !Array.isArray(obj[key])) {\n                                    derefOptions?.preservedProperties.forEach((prop) => {\n                                        if (prop in obj[key]) {\n                                            preserved.set(prop, obj[key][prop]);\n                                        }\n                                    });\n                                }\n                            }\n                            // Clone the dereferenced value if cloneReferences is enabled and this is not a\n                            // circular reference. This prevents mutations to one location from affecting others.\n                            let assignedValue = dereferenced.value;\n                            if (derefOptions?.cloneReferences && !circular && assignedValue && typeof assignedValue === \"object\") {\n                                assignedValue = structuredClone(assignedValue);\n                            }\n                            obj[key] = assignedValue;\n                            // If we have data to preserve and our dereferenced object is still an object then\n                            // we need copy back our preserved data into our dereferenced schema.\n                            if (derefOptions?.preservedProperties) {\n                                if (preserved.size && typeof obj[key] === \"object\" && !Array.isArray(obj[key])) {\n                                    preserved.forEach((value, prop) => {\n                                        obj[key][prop] = value;\n                                    });\n                                }\n                            }\n                            derefOptions?.onDereference?.(value.$ref, obj[key], obj, key);\n                        }\n                    }\n                    else {\n                        if (!parents.has(value)) {\n                            dereferenced = crawl(value, keyPath, childScopeBase, dynamicIdScope, childLegacyIdScope, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, depth + 1);\n                            circular = dereferenced.circular;\n                            // Avoid pointless mutations; breaks frozen objects to no profit\n                            if (obj[key] !== dereferenced.value) {\n                                obj[key] = dereferenced.value;\n                            }\n                        }\n                        else {\n                            circular = foundCircularReference(keyPath, $refs, options);\n                        }\n                    }\n                    // Set the \"isCircular\" flag if this or any other property is circular\n                    result.circular = result.circular || circular;\n                }\n            }\n            parents.delete(obj);\n        }\n    }\n    return result;\n}\n/**\n * Dereferences the given JSON Reference, and then crawls the resulting value.\n *\n * @param $ref - The JSON Reference to resolve\n * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash\n * @param pathFromRoot - The path of `$ref` from the schema root\n * @param parents - An array of the parent objects that have already been dereferenced\n * @param processedObjects - An array of all the objects that have already been dereferenced\n * @param dereferencedCache - An map of all the dereferenced objects\n * @param $refs\n * @param options\n * @returns\n */\nfunction dereference$Ref($ref, path, scopeBase, dynamicIdScope, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, depth) {\n    const isExternalRef = $Ref.isExternal$Ref($ref);\n    const shouldResolveOnCwd = isExternalRef && options?.dereference?.externalReferenceResolution === \"root\";\n    const resolutionBase = shouldResolveOnCwd ? url.cwd() : dynamicIdScope ? scopeBase : path;\n    const $refPath = url.resolve(resolutionBase, $ref.$ref);\n    const cache = dereferencedCache.get($refPath);\n    if (cache) {\n        // If the object we found is circular we can immediately return it because it would have been\n        // cached with everything we need already and we don't need to re-process anything inside it.\n        //\n        // If the cached object however is _not_ circular and there are additional keys alongside our\n        // `$ref` pointer here, fall through and process it normally. Extended references create a new\n        // value, so returning the cached target (or merging it ad hoc) would make their result depend on\n        // which reference happened to be visited first.\n        if (!cache.circular) {\n            if (!$Ref.isExtended$Ref($ref)) {\n                return cache;\n            }\n        }\n        else {\n            // If both our cached value and our incoming `$ref` are the same then we can return what we\n            // got out of the cache, otherwise we should re-process this value. We need to do this because\n            // the current dereference caching mechanism doesn't take into account that `$ref` are neither\n            // unique or reference the same file.\n            //\n            // For example if `schema.yaml` references `definitions/child.yaml` and\n            // `definitions/parent.yaml` references `child.yaml` then `$ref: 'child.yaml'` may get cached\n            // for `definitions/child.yaml`, resulting in `schema.yaml` being having an invalid reference\n            // to `child.yaml`.\n            //\n            // This check is not perfect and the design of the dereference caching mechanism needs a total\n            // overhaul.\n            if (typeof cache.value === \"object\" && \"$ref\" in cache.value && \"$ref\" in $ref) {\n                if (cache.value.$ref === $ref.$ref) {\n                    // Fire onCircular for cached circular refs so callers are notified of every occurrence\n                    foundCircularReference(path, $refs, options);\n                    return cache;\n                }\n                else {\n                    // no-op - fall through to re-process (handles external ref edge case)\n                }\n            }\n            else {\n                foundCircularReference(path, $refs, options);\n                return cache;\n            }\n        }\n    }\n    const pointer = $refs._resolve($refPath, path, options);\n    if (pointer === null) {\n        return {\n            circular: false,\n            value: null,\n        };\n    }\n    // Check for circular references\n    const directCircular = pointer.circular;\n    let circular = directCircular || pointer.chainCircular || parents.has(pointer.value);\n    if (circular) {\n        foundCircularReference(path, $refs, options);\n    }\n    // Dereference the JSON reference\n    let dereferencedValue = $Ref.dereference($ref, pointer.value, options);\n    // Crawl the dereferenced value (unless it's circular)\n    if (!circular) {\n        // Pointer resolution has already applied every $id scope along the resolved path. Re-applying\n        // the resolved value's $id here would duplicate relative folder-changing identifiers.\n        const dereferencedScopeBase = pointer.$ref.dynamicIdScope ? pointer.scopeBase : pointer.$ref.path;\n        // Determine if the dereferenced value is circular\n        const dereferenced = crawl(dereferencedValue, pointer.path, dereferencedScopeBase, pointer.$ref.dynamicIdScope, pointer.legacyIdScope, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime, depth + 1);\n        circular = dereferenced.circular;\n        dereferencedValue = dereferenced.value;\n    }\n    if (circular && !directCircular && options.dereference?.circular === \"ignore\") {\n        // The user has chosen to \"ignore\" circular references, so don't change the value\n        dereferencedValue = $ref;\n    }\n    if (directCircular && dereferencedValue !== $ref) {\n        // The pointer is a DIRECT circular reference (i.e. it references itself).\n        // So replace the $ref path with the absolute path from the JSON Schema root\n        dereferencedValue.$ref = pathFromRoot;\n    }\n    const dereferencedObject = {\n        circular,\n        value: dereferencedValue,\n    };\n    // only cache if no extra properties than $ref\n    if (Object.keys($ref).length === 1) {\n        dereferencedCache.set($refPath, dereferencedObject);\n    }\n    return dereferencedObject;\n}\n/**\n * Check if we've run past our allowed timeout and throw an error if we have.\n *\n * @param startTime - The time when the dereferencing started.\n * @param options\n */\nfunction checkDereferenceTimeout(startTime, options) {\n    if (options && options.timeoutMs) {\n        if (Date.now() - startTime > options.timeoutMs) {\n            throw new TimeoutError(options.timeoutMs);\n        }\n    }\n}\n/**\n * Called when a circular reference is found.\n * It sets the {@link $Refs#circular} flag, executes the options.dereference.onCircular callback,\n * and throws an error if options.dereference.circular is false.\n *\n * @param keyPath - The JSON Reference path of the circular reference\n * @param $refs\n * @param options\n * @returns - always returns true, to indicate that a circular reference was found\n */\nfunction foundCircularReference(keyPath, $refs, options) {\n    $refs.circular = true;\n    options?.dereference?.onCircular?.(keyPath);\n    if (!options.dereference.circular) {\n        const error = new ReferenceError(`Circular $ref pointer found at ${keyPath}`);\n        throw error;\n    }\n    return true;\n}\n","function makeNext() {\n    if (typeof process === \"object\" && typeof process.nextTick === \"function\") {\n        return process.nextTick;\n    }\n    else if (typeof setImmediate === \"function\") {\n        return setImmediate;\n    }\n    else {\n        return function next(f) {\n            setTimeout(f, 0);\n        };\n    }\n}\nexport default makeNext();\n","import next from \"./next.js\";\nexport default function maybe(cb, promise) {\n    if (cb) {\n        promise.then(function (result) {\n            next(function () {\n                cb(null, result);\n            });\n        }, function (err) {\n            next(function () {\n                cb(err);\n            });\n        });\n        return undefined;\n    }\n    else {\n        return promise;\n    }\n}\n","import $Refs from \"./refs.js\";\nimport _parse from \"./parse.js\";\nimport normalizeArgs from \"./normalize-args.js\";\nimport resolveExternal from \"./resolve-external.js\";\nimport _bundle from \"./bundle.js\";\nimport _dereference from \"./dereference.js\";\nimport * as url from \"./util/url.js\";\nimport FileResolver from \"./resolvers/file.js\";\nimport HTTPResolver from \"./resolvers/http.js\";\nimport { JSONParserError, InvalidPointerError, MissingPointerError, ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError, JSONParserErrorGroup, } from \"./util/errors.js\";\nimport maybe from \"./util/maybe.js\";\nimport { getSchemaIdMode, registerSchemaResources, usesDynamicIdScope } from \"./util/schema-resources.js\";\nimport { getJsonSchemaRefParserDefaultOptions } from \"./options.js\";\nimport { isUnsafeUrl } from \"./util/url.js\";\n/**\n * This class parses a JSON schema, builds a map of its JSON references and their resolved values,\n * and provides methods for traversing, manipulating, and dereferencing those references.\n *\n * @class\n */\nexport class $RefParser {\n    /**\n     * The parsed (and possibly dereferenced) JSON schema object\n     *\n     * @type {object}\n     * @readonly\n     */\n    schema = null;\n    /**\n     * The resolved JSON references\n     *\n     * @type {$Refs}\n     * @readonly\n     */\n    $refs = new $Refs();\n    async parse() {\n        const args = normalizeArgs(arguments);\n        let promise;\n        const hasSchema = args.schema !== undefined && args.schema !== null;\n        if (!args.path && !hasSchema) {\n            const err = new Error(`Expected a file path, URL, or object. Got ${args.path || args.schema}`);\n            return maybe(args.callback, Promise.reject(err));\n        }\n        // Reset everything\n        this.schema = null;\n        this.$refs = new $Refs();\n        // If the path is a filesystem path, then convert it to a URL.\n        // NOTE: According to the JSON Reference spec, these should already be URLs,\n        // but, in practice, many people use local filesystem paths instead.\n        // So we're being generous here and doing the conversion automatically.\n        // This is not intended to be a 100% bulletproof solution.\n        // If it doesn't work for your use-case, then use a URL instead.\n        let pathType = \"http\";\n        if (url.isFileSystemPath(args.path)) {\n            args.path = url.fromFileSystemPath(args.path);\n            pathType = \"file\";\n        }\n        // Resolve the absolute path of the schema\n        args.path = url.resolve(url.cwd(), args.path);\n        if (hasSchema && (typeof args.schema === \"object\" || typeof args.schema === \"boolean\")) {\n            // A schema object was passed-in.\n            // So immediately add a new $Ref with the schema object as its value\n            const $ref = this.$refs._add(args.path);\n            $ref.value = args.schema;\n            $ref.pathType = pathType;\n            $ref.dynamicIdScope = usesDynamicIdScope($ref.value);\n            $ref.legacyIdScope = getSchemaIdMode($ref.value);\n            registerSchemaResources(this.$refs, $ref.path, $ref.value, $ref.pathType, $ref.dynamicIdScope);\n            promise = Promise.resolve(args.schema);\n        }\n        else {\n            // Parse the schema file/url\n            promise = _parse(args.path, this.$refs, args.options);\n        }\n        try {\n            const result = await promise;\n            if (typeof result === \"boolean\" || (result !== null && typeof result === \"object\" && !Buffer.isBuffer(result))) {\n                this.schema = result;\n                return maybe(args.callback, Promise.resolve(this.schema));\n            }\n            else if (args.options.continueOnError) {\n                this.schema = null; // it's already set to null at line 79, but let's set it again for the sake of readability\n                return maybe(args.callback, Promise.resolve(this.schema));\n            }\n            else {\n                throw new SyntaxError(`\"${this.$refs._root$Ref.path || result}\" is not a valid JSON Schema`);\n            }\n        }\n        catch (err) {\n            if (!args.options.continueOnError || !isHandledError(err)) {\n                return maybe(args.callback, Promise.reject(err));\n            }\n            if (this.$refs._$refs[url.stripHash(args.path)]) {\n                this.$refs._$refs[url.stripHash(args.path)].addError(err);\n            }\n            return maybe(args.callback, Promise.resolve(null));\n        }\n    }\n    static parse() {\n        const parser = new $RefParser();\n        return parser.parse.apply(parser, arguments);\n    }\n    async resolve() {\n        const args = normalizeArgs(arguments);\n        try {\n            await this.parse(args.path, args.schema, args.options);\n            await resolveExternal(this, args.options);\n            finalize(this);\n            return maybe(args.callback, Promise.resolve(this.$refs));\n        }\n        catch (err) {\n            return maybe(args.callback, Promise.reject(err));\n        }\n    }\n    static resolve() {\n        const instance = new $RefParser();\n        return instance.resolve.apply(instance, arguments);\n    }\n    static bundle() {\n        const instance = new $RefParser();\n        return instance.bundle.apply(instance, arguments);\n    }\n    async bundle() {\n        const args = normalizeArgs(arguments);\n        try {\n            await this.resolve(args.path, args.schema, args.options);\n            _bundle(this, args.options);\n            finalize(this);\n            return maybe(args.callback, Promise.resolve(this.schema));\n        }\n        catch (err) {\n            return maybe(args.callback, Promise.reject(err));\n        }\n    }\n    static dereference() {\n        const instance = new $RefParser();\n        return instance.dereference.apply(instance, arguments);\n    }\n    async dereference() {\n        const args = normalizeArgs(arguments);\n        try {\n            await this.resolve(args.path, args.schema, args.options);\n            _dereference(this, args.options);\n            finalize(this);\n            return maybe(args.callback, Promise.resolve(this.schema));\n        }\n        catch (err) {\n            return maybe(args.callback, Promise.reject(err));\n        }\n    }\n}\nexport default $RefParser;\nfunction finalize(parser) {\n    const errors = JSONParserErrorGroup.getParserErrors(parser);\n    if (errors.length > 0) {\n        throw new JSONParserErrorGroup(parser);\n    }\n}\nexport const parse = $RefParser.parse;\nexport const resolve = $RefParser.resolve;\nexport const bundle = $RefParser.bundle;\nexport const dereference = $RefParser.dereference;\nexport { UnmatchedResolverError, JSONParserError, InvalidPointerError, MissingPointerError, ResolverError, ParserError, UnmatchedParserError, isHandledError, JSONParserErrorGroup, _dereference as dereferenceInternal, normalizeArgs as jsonSchemaParserNormalizeArgs, getJsonSchemaRefParserDefaultOptions, $Refs, isUnsafeUrl, FileResolver, HTTPResolver, };\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\nimport { isSwagger } from './assertions.js';\n\n/**\n * Regular expression that matches path parameter templating.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-templating}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#path-templating}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-templating}\n */\nexport const pathParameterTemplateRegExp: RegExp = /\\{([^/}]+)}/g;\n\n/**\n * List of HTTP verbs used for OperationItem as per the OpenAPI and Swagger specifications\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#path-item-object}\n */\nexport const supportedHTTPMethods = ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'trace'] as const;\nexport const swaggerHTTPMethods = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch'] as const;\n\n/**\n * Determine the proper name for the API specification schema used by a given schema.\n *\n */\nexport function getSpecificationName(\n  api: OpenAPIV2.Document | OpenAPIV3_1.Document | OpenAPIV3.Document,\n): 'OpenAPI' | 'Swagger' {\n  return isSwagger(api) ? 'Swagger' : 'OpenAPI';\n}\n","import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\nimport { isOpenAPI } from './lib/assertions.js';\nimport { supportedHTTPMethods } from './lib/index.js';\n\n/** Keywords whose values are literal data, not subschemas — a `$id` inside them is user data. */\nconst DATA_KEYWORDS = new Set(['example', 'examples', 'default', 'const', 'enum']);\n\n/** Collect every `$ref` string in the definition, so we can tell which `$id`s are referenced. */\nfunction collectRefs(node: unknown, refs: Set<string>): void {\n  if (Array.isArray(node)) {\n    node.forEach(item => collectRefs(item, refs));\n  } else if (node !== null && typeof node === 'object') {\n    for (const [key, value] of Object.entries(node)) {\n      if (key === '$ref' && typeof value === 'string') {\n        refs.add(value);\n      } else if (!DATA_KEYWORDS.has(key)) {\n        collectRefs(value, refs);\n      }\n    }\n  }\n}\n\nfunction isRelativeRef(ref: string): boolean {\n  return !ref.startsWith('#') && !/^[a-z][a-z0-9+.-]*:/i.test(ref);\n}\n\nfunction decodeURIRef(ref: string): string {\n  try {\n    return decodeURIComponent(ref);\n  } catch {\n    // Malformed percent-encoding; treat the reference literally.\n    return ref;\n  }\n}\n\nfunction decodePointerSegment(segment: string): string {\n  // `$ref` fragments are URI-encoded, so `%20` must become a space before we compare keys.\n  return decodeURIRef(segment).replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\n/**\n * Whether `ref` is a same-document JSON Pointer (`#`, `#/…`), including when the leading slash is\n * percent-encoded (`#%2Fcomponents/…`). Those never target a `$id` URI.\n */\nfunction isDocumentRootPointer(ref: string): boolean {\n  const decoded = decodeURIRef(ref);\n  return decoded === '#' || decoded.startsWith('#/');\n}\n\n/**\n * Whether `ref` is a JSON Pointer that exists on `root`. `#` and `#/` are the resource root.\n */\nfunction jsonPointerExists(root: unknown, ref: string): boolean {\n  const decoded = decodeURIRef(ref);\n  if (decoded === '#' || decoded === '#/') {\n    return root !== undefined;\n  }\n\n  if (!decoded.startsWith('#/')) {\n    return false;\n  }\n\n  const segments = decoded.slice(2).split('/').map(decodePointerSegment);\n  let current: unknown = root;\n  for (const segment of segments) {\n    if (current === null || current === undefined || typeof current !== 'object') {\n      return false;\n    }\n\n    if (!Object.prototype.hasOwnProperty.call(current, segment)) {\n      return false;\n    }\n\n    current = (current as Record<string, unknown>)[segment];\n  }\n\n  return true;\n}\n\n/**\n * Whether anything in `scope` depends on `scope`'s `$id` as its base URI.\n *\n * That includes a relative `$ref`, a nested relative `$id` (which also resolves against the\n * enclosing base), a recursive `$ref: \"#\"` (the current resource), or a fragment pointer that\n * resolves inside `scope` (`#/$defs/…`). Document-root leftovers (`#/paths/…`, `#/components/…`)\n * do not pin it. We stop at nested `$id` boundaries (they open their own scope), except a\n * *relative* nested `$id` still pins `scope`.\n */\nfunction scopeDependsOnId(scope: Record<string, unknown>): boolean {\n  const search = (node: unknown, isScopeRoot: boolean): boolean => {\n    if (Array.isArray(node)) {\n      return node.some(item => search(item, false));\n    }\n\n    if (node === null || typeof node !== 'object') {\n      return false;\n    }\n\n    const obj = node as Record<string, unknown>;\n    if (!isScopeRoot && typeof obj.$id === 'string') {\n      return isRelativeRef(obj.$id);\n    }\n\n    return Object.entries(obj).some(([key, value]) => {\n      if (key === '$ref' && typeof value === 'string') {\n        if (isRelativeRef(value)) {\n          return true;\n        }\n\n        // `$ref: \"#\"` is the current `$id` resource. Stripping `$id` re-aims it at the document.\n        // Keep `$id` when the pointer is local to this resource (`#/$defs/…`, including\n        // percent-encoded `#%2F$defs/…`). Bundled leftovers that only exist at the document root\n        // (`#/paths/…`, `#/components/…`) must not pin it.\n        if (isDocumentRootPointer(value)) {\n          return jsonPointerExists(scope, value);\n        }\n\n        return false;\n      }\n\n      return !DATA_KEYWORDS.has(key) && search(value, false);\n    });\n  };\n\n  return search(scope, true);\n}\n\n/**\n * Remove orphaned `$id` keywords from an API definition.\n *\n * In OpenAPI 3.1, `$id` sets a new base URI for `$ref` resolution within its subschema. Bundling can\n * leave a `$id` on an inlined schema whose own refs were rewritten to internal `#/…` pointers; that\n * leftover `$id` then re-scopes those pointers away from the definition root, so resolution throws a\n * spurious \"Missing $ref pointer\" error. Tooling historically ignored `$id`, so such definitions\n * were long accepted.\n *\n * We strip a `$id` only when nothing depends on it — it's not a `$ref` target, not a base URI for a\n * relative `$ref` or local fragment (`#`, `#/$defs/…`) beneath it, and not the root `$id`. These are\n * conservative string-level checks, not full RFC 3986 resolution: they always err towards *keeping*\n * a `$id`, so we never break a working definition (a `$id` used as an in-document anchor is\n * preserved). The cost is that a rare construct a string compare can't disambiguate (e.g. the same\n * relative id reused across scopes) is left as-is — unimproved, but never broken.\n */\nexport function stripOrphanedIds(schema: unknown): void {\n  const refs = new Set<string>();\n  collectRefs(schema, refs);\n\n  const isReferenced = (id: string): boolean => {\n    for (const ref of refs) {\n      // Document-root JSON Pointers (`#/components/…`, `#/paths/…`, `#%2Fcomponents/…`) never\n      // target a `$id` URI. Matching them as substrings (`$id: \"Pet\"` vs `#/components/schemas/Pet`,\n      // or `$id: \"schema\"` vs `#/…/schema`) prevents stripping orphaned `$id`s that then re-scope\n      // those same pointers and break bundle/dereference/validate.\n      if (isDocumentRootPointer(ref)) {\n        continue;\n      }\n\n      // Substring, not exact match: a `$ref` resolving to a relative `$id` contains it without\n      // equalling it (e.g. `$ref: \"schemas/inner.json\"` targets `$id: \"inner.json\"`). Matching\n      // broadly means we never strip a live target; the cost is a safe over-keep when a `$id` value\n      // merely appears in an unrelated non-pointer ref.\n      if (ref.includes(id)) return true;\n    }\n    return false;\n  };\n\n  const visit = (node: unknown, isRoot: boolean): void => {\n    if (Array.isArray(node)) {\n      node.forEach(item => visit(item, false));\n    } else if (node !== null && typeof node === 'object') {\n      const obj = node as Record<string, unknown>;\n\n      // Post-order: decide nested `$id`s first, since removing an inner one can free the outer.\n      for (const [key, value] of Object.entries(obj)) {\n        if (!DATA_KEYWORDS.has(key)) {\n          visit(value, false);\n        }\n      }\n\n      if (!isRoot && typeof obj.$id === 'string' && !isReferenced(obj.$id) && !scopeDependsOnId(obj)) {\n        delete obj.$id;\n      }\n    }\n  };\n\n  // `isRoot` is `true` here so we never strip the document's own top-level `$id`.\n  visit(schema, true);\n}\n\n/**\n * This function takes in a `ServerObject`, checks if it has relative path and then fixes it as per\n * the path URL.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#server-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object}\n *\n * @param server - The server object to be fixed.\n * @param path - The path (an HTTP(S) url) from where the file was downloaded.\n * @returns The fixed server object\n */\nfunction fixServers(\n  server: OpenAPIV3_1.ReferenceObject | OpenAPIV3.ParameterObject | OpenAPIV3.ServerObject,\n  path: string,\n) {\n  // A server URL starting with \"/\" tells that it is not an HTTP(s) URL.\n  if (server && 'url' in server && server.url && server.url.startsWith('/')) {\n    try {\n      const inUrl = new URL(path);\n\n      // `host` keeps a non-default port; `hostname` would drop it and rewrite\n      // `https://api.example.com:8443` + `/hooks` to `https://api.example.com/hooks`.\n      server.url = `${inUrl.protocol}//${inUrl.host}${server.url}`;\n    } catch {\n      // The server path isn't valid but we shouldn't crash out.\n    }\n  }\n}\n\n/**\n * This function helps fix the relative servers in the API definition file be at root, path or\n * operation's level.\n *\n * From the OpenAPI v3 specification for the `ServerObject` `url` property:\n *\n *    REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative,\n *    to indicate that the host location is relative to the location where the OpenAPI document is\n *    being served. Variable substitutions will be made when a variable is named in `{brackets}`.\n *\n * Further the spec says that `servers` property can show up at root level, in `PathItemObject` or\n * in `OperationObject`. However interpretation of the spec says that relative paths for servers\n * should take into account the hostname that serves the OpenAPI file.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#server-object}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object}\n */\nexport function fixOasRelativeServers(schema: OpenAPI.Document, filePath?: string): void {\n  if (!schema || !isOpenAPI(schema) || !filePath || (!filePath.startsWith('http:') && !filePath.startsWith('https:'))) {\n    return;\n  }\n\n  if (schema.servers) {\n    schema.servers.map(server => fixServers(server, filePath)); // Root level servers array's fixup\n  }\n\n  (['paths', 'webhooks'] as const).forEach(component => {\n    if (component in schema) {\n      // Webhooks use the same Path Item shape as `paths`. Cast so the loop below keeps the\n      // original `paths` typings — `schema[component]` is a `paths | webhooks` union.\n      const schemaElement = ((schema as OpenAPIV3_1.Document)[component] || {}) as NonNullable<typeof schema.paths>;\n      Object.keys(schemaElement).forEach(path => {\n        const pathItem = schemaElement[path] || {};\n        Object.keys(pathItem).forEach((opItem: keyof typeof pathItem) => {\n          const pathItemElement = pathItem[opItem];\n          if (!pathItemElement) {\n            return;\n          }\n\n          /**\n           * Servers are at the `PathItemObject` level.\n           *\n           * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#path-item-object}\n           * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object}\n           */\n          if (opItem === 'servers' && Array.isArray(pathItemElement)) {\n            pathItemElement.forEach(server => {\n              fixServers(server, filePath);\n            });\n            return;\n          }\n\n          /**\n           * Servers are at the `OperationObject` level.\n           *\n           * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#operation-object}\n           * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object}\n           */\n          if (\n            supportedHTTPMethods.includes(opItem as unknown as (typeof supportedHTTPMethods)[number]) &&\n            typeof pathItemElement === 'object' &&\n            'servers' in pathItemElement &&\n            Array.isArray(pathItemElement.servers)\n          ) {\n            pathItemElement.servers.forEach(server => {\n              fixServers(server, filePath);\n            });\n          }\n        });\n      });\n    }\n  });\n}\n","import type { APIDocument, ParserOptions } from './types.js';\nimport type { ParserOptions as $RefParserOptions, ResolverOptions } from '@apidevtools/json-schema-ref-parser';\n\nimport { getJsonSchemaRefParserDefaultOptions } from '@apidevtools/json-schema-ref-parser';\n\nimport { isOpenAPI } from './lib/assertions.js';\nimport { fixOasRelativeServers } from './repair.js';\n\ntype FileResolverOption = boolean | Partial<ResolverOptions> | undefined;\n\n/**\n * If necessary, repair the schema of any anomalies and quirks.\n *\n */\nexport function repairSchema<S extends APIDocument = APIDocument>(schema: S, filePath?: string): void {\n  if (isOpenAPI(schema)) {\n    // This is an OpenAPI v3 schema, check if the configured `servers` have any relative paths and\n    // fix them if the content was pulled from a web resource.\n    fixOasRelativeServers(schema, filePath);\n  }\n}\n\n/**\n * Normalize our library variable arguments into a standard format to be used within\n * `json-schema-ref-parser`.\n *\n */\nexport function normalizeArguments<S extends APIDocument = APIDocument>(\n  api: S | string,\n): { path: string; schema: S | undefined } {\n  return {\n    path: typeof api === 'string' ? api : '',\n    schema: typeof api === 'object' ? (api as S) : undefined,\n  };\n}\n\n/**\n * Convert our `resolve.file` option into something `@apidevtools/json-schema-ref-parser`\n * understands.\n *\n */\nfunction convertFileResolverOption(\n  options: ParserOptions | undefined,\n  defaultFileResolver: FileResolverOption,\n): FileResolverOption {\n  if (!options?.resolve || !('file' in options.resolve)) {\n    return false;\n  }\n\n  if (options.resolve.file === true) {\n    return defaultFileResolver;\n  }\n\n  if (options.resolve.file === false) {\n    return false;\n  }\n\n  // Caller supplied a custom resolver object.\n  return options.resolve.file as FileResolverOption;\n}\n\n/**\n * Convert our option set to be used within `json-schema-ref-parser`.\n *\n */\nexport function convertOptionsForParser(\n  options: ParserOptions | undefined,\n  opts: {\n    /**\n     * When the caller passed a filesystem path as the API source, enable the file resolver unless\n     * they explicitly set `resolve.file`. This keeps local path loading working without re-opening\n     * `file://` LFI for object/URL sources\n     */\n    allowFileResolution?: boolean;\n  } = {},\n): Partial<$RefParserOptions> {\n  const parserOptions = getJsonSchemaRefParserDefaultOptions();\n\n  const fileOption =\n    opts.allowFileResolution && !(options?.resolve && 'file' in options.resolve)\n      ? parserOptions.resolve.file\n      : convertFileResolverOption(options, parserOptions.resolve.file);\n\n  return {\n    ...parserOptions,\n    dereference: {\n      ...parserOptions.dereference,\n\n      circular:\n        options?.dereference && 'circular' in options.dereference\n          ? options.dereference.circular\n          : parserOptions.dereference.circular,\n      onCircular: options?.dereference?.onCircular || parserOptions.dereference.onCircular,\n      onDereference: options?.dereference?.onDereference || parserOptions.dereference.onDereference,\n\n      // OpenAPI 3.1 allows for `summary` and `description` properties at the same level as a `$ref`\n      // pointer to be preserved when that `$ref` pointer is dereferenced. The default behavior of\n      // `json-schema-ref-parser` is to discard these properties but this option allows us to\n      // override that behavior.\n      preservedProperties: ['summary', 'description'],\n    },\n\n    resolve: {\n      ...parserOptions.resolve,\n\n      external:\n        options?.resolve && 'external' in options.resolve ? options.resolve.external : parserOptions.resolve.external,\n\n      file: fileOption,\n\n      http: {\n        ...(typeof parserOptions.resolve.http === 'object' ? parserOptions.resolve.http : {}),\n        ...(typeof options?.resolve?.http === 'object' ? options.resolve.http : {}),\n        timeout: options?.resolve?.http && 'timeout' in options.resolve.http ? options.resolve.http.timeout : 5000,\n        safeUrlResolver: true,\n      },\n    },\n\n    timeoutMs: options?.timeoutMs,\n  };\n}\n","import type { ErrorDetails, ParserOptions, ValidationResult } from '../types.js';\nimport type { ErrorObject } from 'ajv';\nimport type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\nimport betterAjvErrors from '@readme/better-ajv-errors';\nimport { openapi } from '@readme/openapi-schemas';\nimport AjvDraft4 from 'ajv-draft-04';\nimport Ajv from 'ajv/dist/2020.js';\n\nimport { isOpenAPI31, isOpenAPI32, isSwagger } from '../lib/assertions.js';\nimport { hasInvalidPaths } from '../lib/hasInvalidPaths.js';\nimport { getSpecificationName } from '../lib/index.js';\nimport { reduceAjvErrors } from '../lib/reduceAjvErrors.js';\n\n/**\n * Schema errors are formatted with `better-ajv-errors`, which renders a code frame for every error.\n * To do that it pretty-prints the **whole** (dereferenced) API definition and parses that string\n * into a full JSON AST, which needs many times the size of the definition in memory. For large\n * definitions this exhausts the heap and crashes the process; once the pretty-printed string\n * exceeds the maximum string length of the JavaScript engine it instead fails with an\n * `Invalid string length` error that hides every real validation error.\n *\n * So if a spec's **stringified** length reaches `LARGE_SPEC_SIZE_CAP` we skip code frames and\n * report plain messages instead, and if it also has more than `LARGE_SPEC_ERROR_CAP` errors we\n * only return the first `LARGE_SPEC_ERROR_CAP` errors.\n *\n * Ideally we'd be looking at the byte size of the spec instead of looking at its stringified\n * length value but the Blob API, which we'd use to get its size with `new Blob([str]).size;`, was\n * only recently introduced in Node 15.\n *\n * w/r/t the 5,000,000 limit here: The spec we found causing these memory leaks had a size of\n * 13,934,323 so 5mil seems like a decent cap to start with.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}\n */\nconst LARGE_SPEC_ERROR_CAP = 20;\nconst LARGE_SPEC_SIZE_CAP = 5000000;\n\n/**\n * Determines if an API definition is too large for `better-ajv-errors` code frames. A definition\n * that cannot even be stringified (because it exceeds the maximum string length) is large too.\n */\nfunction isLargeAPIDefinition(api: object): boolean {\n  try {\n    return JSON.stringify(api).length >= LARGE_SPEC_SIZE_CAP;\n  } catch {\n    return true;\n  }\n}\n\n/**\n * Formats an Ajv error without a code frame: its JSON pointer, message, and the offending property\n * for errors where Ajv's message doesn't name it (eg. `must NOT have additional properties`).\n */\nfunction toPlainError(err: ErrorObject): ErrorDetails {\n  const property = err.params?.additionalProperty ?? err.params?.unevaluatedProperty;\n  // An empty property name is valid JSON, so check for presence and make it visible.\n  const suffix = property === undefined ? '' : ` (${property === '' ? '\"\"' : property})`;\n\n  return { message: `${err.instancePath || '/'} ${err.message}${suffix}` };\n}\n\n/**\n * Determines which version of Ajv to load and prepares it for use.\n *\n */\nfunction initializeAjv(draft04: boolean = true) {\n  const opts = {\n    allErrors: true,\n    strict: false,\n    validateFormats: false,\n  };\n\n  if (draft04) {\n    return new AjvDraft4(opts);\n  }\n\n  return new Ajv(opts);\n}\n\n/**\n * Validates the given Swagger API against the Swagger 2.0 or OpenAPI 3.0 and 3.1 schemas.\n *\n */\nexport function validateSchema(\n  api: OpenAPIV2.Document | OpenAPIV3_1.Document | OpenAPIV3.Document,\n  options: ParserOptions = {},\n  suppressedInstancePaths: string[] = [],\n): ValidationResult {\n  // Pre-validation check for missing leading slashes in paths\n  if (hasInvalidPaths(api)) {\n    return {\n      valid: false,\n      errors: [\n        {\n          message:\n            getSpecificationName(api) === 'Swagger'\n              ? 'Entries in the Swagger `paths` object must begin with a leading slash.'\n              : 'Entries in the OpenAPI `paths` object must begin with a leading slash.',\n        },\n      ],\n      warnings: [],\n      additionalErrors: 0,\n      specification: getSpecificationName(api),\n    };\n  }\n\n  let ajv: AjvDraft4 | Ajv;\n\n  // Choose the appropriate schema (Swagger or OpenAPI)\n  let schema: typeof openapi.v2 | typeof openapi.v3 | typeof openapi.v31legacy;\n  const specificationName = getSpecificationName(api);\n\n  if (isSwagger(api)) {\n    schema = openapi.v2;\n    ajv = initializeAjv();\n  } else if (isOpenAPI32(api)) {\n    throw new TypeError('OpenAPI 3.2 is currently unsupported.');\n  } else if (isOpenAPI31(api)) {\n    schema = openapi.v31legacy;\n\n    /**\n     * There's a bug with Ajv in how it handles `$dynamicRef` in the way that it's used within the\n     * 3.1 schema so we need to do some adhoc workarounds.\n     *\n     * @see {@link https://github.com/OAI/OpenAPI-Specification/issues/2689}\n     * @see {@link https://github.com/ajv-validator/ajv/issues/1573}\n     */\n    const schemaDynamicRef = schema.$defs.schema;\n    if (typeof schemaDynamicRef === 'object' && '$dynamicAnchor' in schemaDynamicRef) {\n      delete schemaDynamicRef.$dynamicAnchor;\n    }\n\n    // @ts-expect-error Intentionally setting up this funky schema for an AJV bug.\n    schema.$defs.components.properties.schemas.additionalProperties = schemaDynamicRef;\n    // @ts-expect-error -- see above\n    schema.$defs.header.dependentSchemas.schema.properties.schema = schemaDynamicRef;\n    // @ts-expect-error -- see above\n    schema.$defs['media-type'].properties.schema = schemaDynamicRef;\n    // @ts-expect-error -- see above\n    schema.$defs.parameter.properties.schema = schemaDynamicRef;\n\n    ajv = initializeAjv(false);\n  } else {\n    schema = openapi.v3;\n    ajv = initializeAjv();\n  }\n\n  // Validate against the schema\n  const isValid = ajv.validate(schema, api);\n  if (isValid) {\n    // We don't support warnings in our schema validation, only the **spec** validator.\n    return { valid: true, warnings: [], specification: specificationName };\n  }\n\n  let additionalErrors = 0;\n  let reducedErrors = reduceAjvErrors(ajv.errors).filter(err => {\n    return !suppressedInstancePaths.some(path => err.instancePath === path || err.instancePath.startsWith(`${path}/`));\n  });\n\n  // If filtering removed every error, the spec is effectively valid from AJV's perspective.\n  if (!reducedErrors.length) {\n    return { valid: true, warnings: [], specification: specificationName };\n  }\n  const isLargeSpec = isLargeAPIDefinition(api);\n  if (isLargeSpec && reducedErrors.length >= LARGE_SPEC_ERROR_CAP) {\n    additionalErrors = reducedErrors.length - LARGE_SPEC_ERROR_CAP;\n    reducedErrors = reducedErrors.slice(0, LARGE_SPEC_ERROR_CAP);\n  }\n\n  if (isLargeSpec || options?.validate?.errors?.codeFrames === false) {\n    return {\n      valid: false,\n      errors: reducedErrors.map(toPlainError),\n      warnings: [],\n      additionalErrors,\n      specification: specificationName,\n    };\n  }\n\n  try {\n    // @ts-expect-error typing on the `ErrorObject` that we use here doesn't match what `better-ajv-errors` uses\n    const errors = betterAjvErrors(schema, api, reducedErrors, {\n      format: 'cli-array',\n      colorize: options?.validate?.errors?.colorize || false,\n      indent: 2,\n    });\n\n    return {\n      valid: false,\n      errors,\n      warnings: [],\n      additionalErrors,\n      specification: specificationName,\n    };\n  } catch (err) {\n    // If `better-ajv-errors` fails for whatever reason we should capture and return it. We'll\n    // obviously not show the user all of their validation errors but it's better than nothing.\n    return {\n      valid: false,\n      errors: [{ message: err.message }],\n      warnings: [],\n      additionalErrors,\n      specification: specificationName,\n    };\n  }\n}\n","import type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\n/**\n * Detects paths in the API definition that are missing leading slashes.\n * This is a common issue that causes \"ADDITIONAL PROPERTY\" validation errors.\n *\n * @param api - The API definition to check\n * @returns Array of paths that are missing leading slashes\n */\nexport function hasInvalidPaths(api: OpenAPIV2.Document | OpenAPIV3_1.Document | OpenAPIV3.Document): boolean {\n  if (!api.paths || typeof api.paths !== 'object' || Array.isArray(api.paths)) {\n    return false;\n  }\n\n  // Return paths that do not start with a leading slash\n  return Object.keys(api.paths).some(path => !path.startsWith('/'));\n}\n","import type { ErrorObject } from 'ajv';\n\n/**\n * Because of the way that Ajv works, if a validation error occurs deep within a schema there's a\n * chance that errors will also be thrown for its immediate parents, leading to a case where we'll\n * eventually show the error indecipherable errors like \"$ref is missing here!\" instance of what's\n * _actually_ going on where they may have mistyped `enum` as `enumm`.\n *\n * To alleviate this confusing noise, we're compressing Ajv errors down to only surface the deepest\n * point for each lineage, so that if a user typos `enum` as `enumm` we'll surface just that error\n * for them (because really that's **the** error).\n *\n * Ajv reports the deepest error of a lineage first, so an error is dropped when an error was\n * already recorded for the same `instancePath` or for one of its descendants. Every recorded\n * `instancePath` marks itself and its ancestors as covered, which keeps this linear in the number\n * of errors (large API definitions can produce hundreds of thousands of them).\n *\n */\nexport function reduceAjvErrors(errors: ErrorObject[]): ErrorObject[] {\n  const flattened = new Map<string, ErrorObject>();\n  const covered = new Set<string>();\n\n  errors.forEach(err => {\n    // These two errors appear when a child schema of them has a problem and instead of polluting\n    // the user with indecipherable noise we should instead relay the more specific error to them.\n    // If this is all that's present in the stack then as a safety net before we wrap up we'll just\n    // return the original `errors` stack.\n    if ([\"must have required property '$ref'\", 'must match exactly one schema in oneOf'].includes(err.message)) {\n      return;\n    }\n\n    // If we already have an error recorded for this `instancePath`, or for one of its descendants,\n    // we can ignore it because we (likely) already have recorded the more specific error.\n    if (covered.has(err.instancePath)) {\n      return;\n    }\n\n    flattened.set(err.instancePath, err);\n\n    let instancePath = err.instancePath;\n    covered.add(instancePath);\n    while (instancePath) {\n      instancePath = instancePath.slice(0, instancePath.lastIndexOf('/'));\n      covered.add(instancePath);\n    }\n  });\n\n  // If we weren't able to fold errors down for whatever reason just return the original stack.\n  if (!flattened.size) {\n    return errors;\n  }\n\n  return [...flattened.values()];\n}\n","import type { ErrorDetails, WarningDetails } from '../../types.js';\n\nexport abstract class SpecificationValidator {\n  errors: ErrorDetails[] = [];\n\n  warnings: WarningDetails[] = [];\n\n  /**\n   * Instance paths flagged by `runPreSchemaChecks()`. Used to suppress AJV `oneOf` noise that\n   * the pre-schema validator has already produced a clearer error or warning for.\n   */\n  flaggedInstancePaths: string[] = [];\n\n  protected reportError(message: string): void {\n    this.errors.push({ message });\n  }\n\n  protected reportWarning(message: string): void {\n    this.warnings.push({ message });\n  }\n\n  protected flagInstancePath(path: string): void {\n    if (!this.flaggedInstancePaths.includes(path)) {\n      this.flaggedInstancePaths.push(path);\n    }\n  }\n\n  abstract run(): void;\n\n  abstract runPreSchemaChecks(): void;\n}\n","import type { ParserRulesOpenAPI } from '../../types.js';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\nimport { isOpenAPI30, isOpenAPI31 } from '../../lib/assertions.js';\nimport { pathParameterTemplateRegExp, supportedHTTPMethods } from '../../lib/index.js';\n\nimport { SpecificationValidator } from './index.js';\n\ntype ParameterObject =\n  | (OpenAPIV3_1.ParameterObject | OpenAPIV3_1.ReferenceObject)\n  | (OpenAPIV3.ParameterObject | OpenAPIV3.ReferenceObject);\n\n/**\n * Validates parts of the OpenAPI 3.0 and 3.1 specification that aren't covered by their JSON\n * Schema definitions.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md}\n */\nexport class OpenAPISpecificationValidator extends SpecificationValidator {\n  api: OpenAPIV3_1.Document | OpenAPIV3.Document;\n\n  rules: ParserRulesOpenAPI;\n\n  constructor(api: OpenAPIV3_1.Document | OpenAPIV3.Document, rules: ParserRulesOpenAPI) {\n    super();\n\n    this.api = api;\n    this.rules = rules;\n  }\n\n  runPreSchemaChecks(): void {\n    this.checkSecuritySchemes();\n  }\n\n  run(): void {\n    const operationIds: string[] = [];\n    Object.keys(this.api.paths || {}).forEach(pathName => {\n      const path = this.api.paths[pathName];\n      const pathId = `/paths${pathName}`;\n\n      if (path && pathName.startsWith('/')) {\n        this.validatePath(path, pathId, operationIds);\n      }\n    });\n\n    /**\n     * There's a problem with how the 3.0 schema uses `patternProperties` for defining the format of\n     * scheme names that it ignores anything that doesn't match, so if you for example have a space\n     * in a schema name it'll be seen as valid when it should instead trigger a validation error.\n     *\n     * @see {@link https://github.com/APIDevTools/swagger-parser/issues/184}\n     */\n    if (isOpenAPI30(this.api)) {\n      if (this.api.components) {\n        Object.keys(this.api.components).forEach((componentType: keyof typeof this.api.components) => {\n          Object.keys(this.api.components[componentType]).forEach(componentName => {\n            if (!/^[a-zA-Z0-9.\\-_]+$/.test(componentName)) {\n              const componentId = `/components/${componentType}/${componentName}`;\n\n              this.reportError(\n                `\\`${componentId}\\` has an invalid name. Component names should match against: /^[a-zA-Z0-9.-_]+$/`,\n              );\n            }\n          });\n        });\n      }\n    }\n\n    /**\n     * OpenAPI 3.1 brought the addition of `webhooks` and made `paths` optional in the process. The\n     * specification now requires that either `components`, `webhooks`, or `paths` be present and\n     * not empty. Unfortunately the JSON Schema for the specification is unable to specify this.\n     *\n     * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-document}\n     */\n    if (isOpenAPI31(this.api)) {\n      if (\n        !Object.keys(this.api.paths || {}).length &&\n        !Object.keys(this.api.webhooks || {}).length &&\n        !Object.keys(this.api.components || {}).length\n      ) {\n        this.reportError(\n          'OpenAPI 3.1 definitions must contain at least one entry in either `paths`, `webhooks`, or `components`.',\n        );\n      }\n    }\n  }\n\n  /**\n   * Validates the given path.\n   *\n   */\n  private validatePath(\n    path: OpenAPIV3_1.PathItemObject | OpenAPIV3.PathItemObject,\n    pathId: string,\n    operationIds: string[],\n  ) {\n    supportedHTTPMethods.forEach(operationName => {\n      const operation = path[operationName];\n      const operationId = `${pathId}/${operationName}`;\n\n      if (operation) {\n        const declaredOperationId = operation.operationId;\n        if (declaredOperationId) {\n          if (!operationIds.includes(declaredOperationId)) {\n            operationIds.push(declaredOperationId);\n          } else if (this.rules['duplicate-operation-id'] === 'warning') {\n            this.reportWarning(`The operationId \\`${declaredOperationId}\\` is duplicated and should be made unique.`);\n          } else {\n            this.reportError(`The operationId \\`${declaredOperationId}\\` is duplicated and must be made unique.`);\n          }\n        }\n\n        this.validateParameters(path, pathId, operation, operationId);\n\n        Object.keys(operation.responses || {}).forEach(responseCode => {\n          const response = operation.responses[responseCode];\n          const responseId = `${operationId}/responses/${responseCode}`;\n          if (response && !('$ref' in response)) {\n            this.validateResponse(response, responseId);\n          }\n        });\n      }\n    });\n  }\n\n  /**\n   * Validates the parameters for the given operation.\n   *\n   */\n  private validateParameters(\n    path: OpenAPIV3_1.PathItemObject | OpenAPIV3.PathItemObject,\n    pathId: string,\n    operation: OpenAPIV3_1.OperationObject | OpenAPIV3.OperationObject,\n    operationId: string,\n  ) {\n    const pathParams = path.parameters || [];\n    const operationParams = operation.parameters || [];\n\n    // Check for duplicate path parameters.\n    this.checkForDuplicates(pathParams, pathId);\n\n    // Check for duplicate operation parameters.\n    this.checkForDuplicates(operationParams, operationId);\n\n    // Combine the path and operation parameters, with the operation params taking precedence over\n    // the path params.\n    const params = pathParams.reduce((combinedParams, value) => {\n      const duplicate = combinedParams.some(param => {\n        if ('$ref' in param || '$ref' in value) {\n          return false;\n        }\n\n        return param.in === value.in && param.name === value.name;\n      });\n\n      if (!duplicate) {\n        combinedParams.push(value);\n      }\n\n      return combinedParams;\n    }, operationParams.slice());\n\n    this.validatePathParameters(params, pathId, operationId);\n    this.validateParameterTypes(params, operationId);\n  }\n\n  /**\n   * Validates path parameters for the given path.\n   *\n   */\n  private validatePathParameters(params: ParameterObject[], pathId: string, operationId: string) {\n    // Find all `{placeholders}` in the path string. And because paths can have path parameters duped\n    // we need to convert this to a unique array so we can eliminate false positives of placeholders\n    // that might be duplicated.\n    const placeholders = [...new Set(pathId.match(pathParameterTemplateRegExp) || [])];\n\n    params\n      .filter(param => 'in' in param)\n      .filter(param => param.in === 'path')\n      .forEach(param => {\n        if (param.required !== true) {\n          if (this.rules['non-optional-path-parameters'] === 'warning') {\n            this.reportWarning(\n              `Path parameters should not be optional. Set \\`required=true\\` for the \\`${param.name}\\` parameter at \\`${operationId}\\`.`,\n            );\n          } else {\n            this.reportError(\n              `Path parameters cannot be optional. Set \\`required=true\\` for the \\`${param.name}\\` parameter at \\`${operationId}\\`.`,\n            );\n          }\n        }\n\n        const match = placeholders.indexOf(`{${param.name}}`);\n        if (match === -1) {\n          const error = `\\`${operationId}\\` has a path parameter named \\`${param.name}\\`, but there is no corresponding \\`{${param.name}}\\` in the path string.`;\n\n          if (this.rules['path-parameters-not-in-path'] === 'warning') {\n            this.reportWarning(error);\n          } else {\n            this.reportError(error);\n          }\n        }\n\n        placeholders.splice(match, 1);\n      });\n\n    if (placeholders.length > 0) {\n      const list = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(\n        placeholders.map(placeholder => `\\`${placeholder}\\``),\n      );\n\n      const error = `\\`${operationId}\\` is missing path parameter(s) for ${list}.`;\n      if (this.rules['path-parameters-not-in-parameters'] === 'warning') {\n        this.reportWarning(error);\n      } else {\n        this.reportError(error);\n      }\n    }\n  }\n\n  /**\n   * Validates data types of parameters for the given operation.\n   *\n   */\n  private validateParameterTypes(params: ParameterObject[], operationId: string) {\n    params.forEach(param => {\n      if ('$ref' in param) {\n        return;\n      }\n\n      const parameterId = `${operationId}/parameters/${param.name}`;\n\n      /**\n       * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#fixed-fields-10}\n       * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-10}\n       */\n      if (!param.schema && param.content) {\n        this.validateParameterContent(param.content, parameterId);\n        return;\n      } else if ('$ref' in param.schema) {\n        return;\n      }\n\n      this.validateSchema(param.schema, parameterId);\n    });\n  }\n\n  /**\n   * Validates parameter content object.\n   * Note: The requirement for exactly one media type is already enforced by the OpenAPI JSON schema.\n   */\n  private validateParameterContent(\n    content: OpenAPIV3_1.ParameterObject['content'] | OpenAPIV3.ParameterObject['content'],\n    parameterId: string,\n  ) {\n    const mediaTypes = Object.keys(content);\n    if (mediaTypes.length !== 1) {\n      this.reportError(\n        `\\`${parameterId}\\` must have exactly one media type in \\`content\\`, but found ${mediaTypes.length}.`,\n      );\n      return;\n    }\n\n    const mediaType = mediaTypes[0];\n    const contentSchema = content[mediaType].schema;\n    if (contentSchema) {\n      if ('$ref' in contentSchema) {\n        return;\n      }\n      this.validateSchema(contentSchema, `${parameterId}/content/${mediaType}/schema`);\n    }\n  }\n\n  /**\n   * Validates the given response object.\n   *\n   */\n  private validateResponse(response: OpenAPIV3_1.ResponseObject | OpenAPIV3.ResponseObject, responseId: string) {\n    Object.keys(response.headers || {}).forEach(headerName => {\n      const header = response.headers[headerName];\n      const headerId = `${responseId}/headers/${headerName}`;\n      if ('$ref' in header) {\n        return;\n      }\n\n      if (header.schema) {\n        if (!('$ref' in header.schema)) {\n          this.validateSchema(header.schema, headerId);\n        }\n      } else if (header.content) {\n        Object.keys(header.content).forEach(mediaType => {\n          if (header.content[mediaType].schema) {\n            if (!('$ref' in header.content[mediaType].schema)) {\n              this.validateSchema(header.content[mediaType].schema || {}, `${headerId}/content/${mediaType}/schema`);\n            }\n          }\n        });\n      }\n    });\n\n    if (response.content) {\n      Object.keys(response.content).forEach(mediaType => {\n        if (response.content[mediaType].schema) {\n          if (!('$ref' in response.content[mediaType].schema)) {\n            this.validateSchema(response.content[mediaType].schema || {}, `${responseId}/content/${mediaType}/schema`);\n          }\n        }\n      });\n    }\n  }\n\n  /**\n   * Validates the given Swagger schema object.\n   *\n   */\n  private validateSchema(schema: OpenAPIV3_1.SchemaObject | OpenAPIV3.SchemaObject, schemaId: string) {\n    if (schema.type === 'array' && !schema.items) {\n      if (this.rules['array-without-items'] === 'warning') {\n        this.reportWarning(`\\`${schemaId}\\` is an array, so it should include an \\`items\\` schema.`);\n      } else {\n        this.reportError(`\\`${schemaId}\\` is an array, so it must include an \\`items\\` schema.`);\n      }\n    }\n  }\n\n  /**\n   * Validates security schemes in `components.securitySchemes` against their declared `type`.\n   *\n   * AJV uses a `oneOf` schema to validate security schemes, so when a scheme is malformed AJV\n   * fails every branch and produces overwhelming, unhelpful errors. This pre-AJV pass surfaces\n   * a single targeted error per problem.\n   *\n   * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-scheme-object}\n   */\n  private checkSecuritySchemes() {\n    const securitySchemes = this.api.components?.securitySchemes;\n    if (!securitySchemes) {\n      return;\n    }\n\n    const schemeTypeProps: Record<string, { foreign: Record<string, string>; required: string[] }> = {\n      apiKey: {\n        required: ['name', 'in'],\n        foreign: { scheme: 'http', bearerFormat: 'http', flows: 'oauth2', openIdConnectUrl: 'openIdConnect' },\n      },\n      http: {\n        required: ['scheme'],\n        foreign: { name: 'apiKey', in: 'apiKey', flows: 'oauth2', openIdConnectUrl: 'openIdConnect' },\n      },\n      oauth2: {\n        required: ['flows'],\n        foreign: {\n          name: 'apiKey',\n          in: 'apiKey',\n          scheme: 'http',\n          bearerFormat: 'http',\n          openIdConnectUrl: 'openIdConnect',\n        },\n      },\n      openIdConnect: {\n        required: ['openIdConnectUrl'],\n        foreign: { name: 'apiKey', in: 'apiKey', scheme: 'http', bearerFormat: 'http', flows: 'oauth2' },\n      },\n      mutualTLS: {\n        required: [],\n        foreign: {\n          name: 'apiKey',\n          in: 'apiKey',\n          scheme: 'http',\n          bearerFormat: 'http',\n          flows: 'oauth2',\n          openIdConnectUrl: 'openIdConnect',\n        },\n      },\n    };\n\n    Object.keys(securitySchemes).forEach(name => {\n      const scheme = securitySchemes[name] as Record<string, unknown>;\n      if ('$ref' in scheme) {\n        return;\n      }\n\n      const schemeId = `/components/securitySchemes/${name}`;\n      const reportIssue = (message: string) => this.reportSecuritySchemeIssue(message, schemeId);\n\n      // Rule: every scheme must declare a `type`. Without it we can't run any other check.\n      if (!('type' in scheme) || !scheme.type) {\n        reportIssue(\n          `\\`${schemeId}\\` is missing required property \\`type\\`. Must be one of: \\`apiKey\\`, \\`http\\`, \\`oauth2\\`, \\`openIdConnect\\`, \\`mutualTLS\\`.`,\n        );\n        return;\n      }\n\n      const type = scheme.type as string;\n\n      // Rule: `type: basic` is Swagger 2.0 syntax, produce a migration hint instead of a\n      // generic \"invalid type\" so users porting from 2.0 know what to change.\n      if (type === 'basic') {\n        reportIssue(\n          `\\`${schemeId}\\` uses \\`type: basic\\`, which is a Swagger 2.0 value. In OpenAPI 3.x use \\`type: http\\` with \\`scheme: basic\\` instead.`,\n        );\n        return;\n      }\n\n      // Rule: `type` must be one of the recognized OAS 3.x scheme types.\n      if (!(type in schemeTypeProps)) {\n        reportIssue(\n          `\\`${schemeId}\\` has an invalid \\`type\\`: \\`${type}\\`. Must be one of: \\`apiKey\\`, \\`http\\`, \\`oauth2\\`, \\`openIdConnect\\`, \\`mutualTLS\\`.`,\n        );\n        return;\n      }\n\n      const config = schemeTypeProps[type];\n\n      // Rule: each `type` has properties it must declare (apiKey needs name+in, http needs\n      // scheme, oauth2 needs flows, etc.). Report each missing required property separately.\n      config.required.forEach(prop => {\n        if (!(prop in scheme)) {\n          reportIssue(`\\`${schemeId}\\` (\\`type: ${type}\\`) is missing required property \\`${prop}\\`.`);\n        }\n      });\n\n      // Rule: cross-type contamination, e.g. an `http` scheme with a `name` field (which\n      // belongs to `apiKey`). The error names the type that *does* own the property to nudge\n      // the user toward the fix.\n      Object.entries(config.foreign).forEach(([prop, ownerType]) => {\n        if (prop in scheme) {\n          reportIssue(\n            `\\`${schemeId}\\` (\\`type: ${type}\\`) includes \\`${prop}\\`, which is only valid for \\`type: ${ownerType}\\` schemes.`,\n          );\n        }\n      });\n\n      // Rule: `apiKey.in` must be one of `query`, `header`, `cookie` (per OAS 3.0+).\n      if (type === 'apiKey' && typeof scheme.in === 'string') {\n        const validIn = ['query', 'header', 'cookie'];\n        if (!validIn.includes(scheme.in)) {\n          reportIssue(\n            `\\`${schemeId}\\` has an invalid \\`in\\` value: \\`${scheme.in}\\`. Must be one of: \\`query\\`, \\`header\\`, \\`cookie\\`.`,\n          );\n        }\n      }\n\n      // Rule: `oauth2.flows` is structurally present but empty (`flows: {}`), the `required`\n      // check passes, but the spec demands at least one grant type inside.\n      if (type === 'oauth2' && scheme.flows && typeof scheme.flows === 'object') {\n        if (Object.keys(scheme.flows as object).length === 0) {\n          reportIssue(\n            `\\`${schemeId}\\` has empty \\`flows\\`. At least one grant type is required: \\`implicit\\`, \\`password\\`, \\`clientCredentials\\`, or \\`authorizationCode\\`.`,\n          );\n        }\n      }\n    });\n  }\n\n  private reportSecuritySchemeIssue(message: string, schemeId: string) {\n    this.flagInstancePath(schemeId);\n    if (this.rules['invalid-security-scheme-properties'] === 'warning') {\n      this.reportWarning(message);\n    } else {\n      this.reportError(message);\n    }\n  }\n\n  /**\n   * Checks the given parameter list for duplicates.\n   *\n   */\n  private checkForDuplicates(params: ParameterObject[], schemaId: string) {\n    for (let i = 0; i < params.length - 1; i++) {\n      const outer = params[i];\n      for (let j = i + 1; j < params.length; j++) {\n        const inner = params[j];\n        if ('$ref' in outer || '$ref' in inner) {\n          continue;\n        }\n\n        if (outer.name === inner.name && outer.in === inner.in) {\n          const error = `Found multiple \\`${outer.in}\\` parameters named \\`${outer.name}\\` in \\`${schemaId}\\`.`;\n\n          if (this.rules['duplicate-non-request-body-parameters'] === 'warning') {\n            this.reportWarning(error);\n          } else {\n            this.reportError(error);\n          }\n        }\n      }\n    }\n  }\n}\n","import type { ParserRulesSwagger } from '../../types.js';\nimport type { IJsonSchema, OpenAPIV2 } from 'openapi-types';\n\nimport { pathParameterTemplateRegExp, swaggerHTTPMethods } from '../../lib/index.js';\n\nimport { SpecificationValidator } from './index.js';\n\n/**\n * Validates parts of the Swagger 2.0 specification that aren't covered by its JSON Schema\n * definitions.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md}\n */\nexport class SwaggerSpecificationValidator extends SpecificationValidator {\n  api: OpenAPIV2.Document;\n\n  rules: ParserRulesSwagger;\n\n  constructor(api: OpenAPIV2.Document, rules: ParserRulesSwagger) {\n    super();\n\n    this.api = api;\n    this.rules = rules;\n  }\n\n  runPreSchemaChecks(): void {\n    this.checkSecurityDefinitions();\n  }\n\n  run(): void {\n    const operationIds: string[] = [];\n    Object.keys(this.api.paths || {}).forEach(pathName => {\n      const path = this.api.paths[pathName];\n      const pathId = `/paths${pathName}`;\n\n      if (path && pathName.startsWith('/')) {\n        this.validatePath(path, pathId, operationIds);\n      }\n    });\n\n    Object.keys(this.api.definitions || {}).forEach(definitionName => {\n      const definition = this.api.definitions[definitionName];\n      const definitionId = `/definitions/${definitionName}`;\n\n      if (!/^[a-zA-Z0-9.\\-_]+$/.test(definitionName)) {\n        this.reportError(\n          `\\`${definitionId}\\` has an invalid name. Definition names should match against: /^[a-zA-Z0-9.-_]+$/`,\n        );\n      }\n\n      this.validateRequiredPropertiesExist(definition, definitionId);\n    });\n  }\n\n  /**\n   * Validates the given path.\n   *\n   */\n  private validatePath(path: OpenAPIV2.PathItemObject, pathId: string, operationIds: string[]) {\n    swaggerHTTPMethods.forEach(operationName => {\n      const operation = path[operationName];\n      const operationId = `${pathId}/${operationName}`;\n\n      if (operation) {\n        const declaredOperationId = operation.operationId;\n        if (declaredOperationId) {\n          if (!operationIds.includes(declaredOperationId)) {\n            operationIds.push(declaredOperationId);\n          } else if (this.rules['duplicate-operation-id'] === 'warning') {\n            this.reportWarning(`The operationId \\`${declaredOperationId}\\` is duplicated and should be made unique.`);\n          } else {\n            this.reportError(`The operationId \\`${declaredOperationId}\\` is duplicated and must be made unique.`);\n          }\n        }\n\n        this.validateParameters(path, pathId, operation, operationId);\n\n        Object.keys(operation.responses || {}).forEach(responseName => {\n          const response = operation.responses[responseName];\n          if ('$ref' in response || !response) {\n            return;\n          }\n\n          const responseId = `${operationId}/responses/${responseName}`;\n          this.validateResponse(responseName, response, responseId);\n        });\n      }\n    });\n  }\n\n  /**\n   * Validates the parameters for the given operation.\n   *\n   */\n  private validateParameters(\n    path: OpenAPIV2.PathItemObject,\n    pathId: string,\n    operation: OpenAPIV2.OperationObject,\n    operationId: string,\n  ) {\n    const pathParams = (path.parameters || []).filter(param => !('$ref' in param)) as OpenAPIV2.ParameterObject[];\n    const operationParams = (operation.parameters || []).filter(\n      param => !('$ref' in param),\n    ) as OpenAPIV2.ParameterObject[];\n\n    // Check for duplicate path parameters\n    this.checkForDuplicates(pathParams, pathId);\n\n    // Check for duplicate operation parameters\n    this.checkForDuplicates(operationParams, operationId);\n\n    // Combine the path and operation parameters,\n    // with the operation params taking precedence over the path params\n    const params = pathParams.reduce((combinedParams, value) => {\n      const duplicate = combinedParams.some(param => {\n        if ('$ref' in param || '$ref' in value) {\n          return false;\n        }\n        return param.in === value.in && param.name === value.name;\n      });\n      if (!duplicate) {\n        combinedParams.push(value);\n      }\n      return combinedParams;\n    }, operationParams.slice());\n\n    this.validateBodyParameters(params, operationId);\n    this.validatePathParameters(params, pathId, operationId);\n    this.validateParameterTypes(params, operation, operationId);\n  }\n\n  /**\n   * Validates body and formData parameters for the given operation.\n   *\n   */\n  private validateBodyParameters(params: OpenAPIV2.ParameterObject[], operationId: string) {\n    const bodyParams = params.filter(param => param.in === 'body');\n    const formParams = params.filter(param => param.in === 'formData');\n\n    // There can only be one \"body\" parameter\n    if (bodyParams.length > 1) {\n      this.reportError(`\\`${operationId}\\` has ${bodyParams.length} body parameters. Only one is allowed.`);\n    } else if (bodyParams.length > 0 && formParams.length > 0) {\n      // \"body\" params and \"formData\" params are mutually exclusive\n      this.reportError(\n        `\\`${operationId}\\` has \\`body\\` and \\`formData\\` parameters. Only one or the other is allowed.`,\n      );\n    }\n  }\n\n  /**\n   * Validates path parameters for the given path.\n   *\n   */\n  private validatePathParameters(params: OpenAPIV2.ParameterObject[], pathId: string, operationId: string) {\n    // Find all {placeholders} in the path string\n    const placeholders: string[] = pathId.match(pathParameterTemplateRegExp) || [];\n\n    // Check for duplicates\n    for (let i = 0; i < placeholders.length; i++) {\n      for (let j = i + 1; j < placeholders.length; j++) {\n        if (placeholders[i] === placeholders[j]) {\n          this.reportError(`\\`${operationId}\\` has multiple path placeholders named \\`${placeholders[i]}\\`.`);\n        }\n      }\n    }\n\n    params\n      .filter(param => param.in === 'path')\n      .forEach(param => {\n        if (param.required !== true) {\n          if (this.rules['non-optional-path-parameters'] === 'warning') {\n            this.reportWarning(\n              `Path parameters should not be optional. Set \\`required=true\\` for the \\`${param.name}\\` parameter at \\`${operationId}\\`.`,\n            );\n          } else {\n            this.reportError(\n              `Path parameters cannot be optional. Set \\`required=true\\` for the \\`${param.name}\\` parameter at \\`${operationId}\\`.`,\n            );\n          }\n        }\n\n        const match = placeholders.indexOf(`{${param.name}}`);\n        if (match === -1) {\n          const error = `\\`${operationId}\\` has a path parameter named \\`${param.name}\\`, but there is no corresponding \\`{${param.name}}\\` in the path string.`;\n\n          if (this.rules['path-parameters-not-in-path'] === 'warning') {\n            this.reportWarning(error);\n          } else {\n            this.reportError(error);\n          }\n        }\n\n        placeholders.splice(match, 1);\n      });\n\n    if (placeholders.length > 0) {\n      const list = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(\n        placeholders.map(placeholder => `\\`${placeholder}\\``),\n      );\n\n      const error = `\\`${operationId}\\` is missing path parameter(s) for ${list}.`;\n      if (this.rules['path-parameters-not-in-parameters'] === 'warning') {\n        this.reportWarning(error);\n      } else {\n        this.reportError(error);\n      }\n    }\n  }\n\n  /**\n   * Validates data types of parameters for the given operation.\n   *\n   */\n  private validateParameterTypes(\n    params: OpenAPIV2.ParameterObject[],\n    operation: OpenAPIV2.OperationObject,\n    operationId: string,\n  ) {\n    params.forEach(param => {\n      const parameterId = `${operationId}/parameters/${param.name}`;\n      let schema: any;\n\n      switch (param.in) {\n        case 'body':\n          schema = param.schema;\n          break;\n        case 'formData':\n          schema = param;\n          break;\n        default:\n          schema = param;\n      }\n\n      this.validateSchema(schema, parameterId);\n      this.validateRequiredPropertiesExist(schema, parameterId);\n\n      if (schema.type === 'file') {\n        // \"file\" params must consume at least one of these MIME types\n        const formData = /multipart\\/(.*\\+)?form-data/;\n        const urlEncoded = /application\\/(.*\\+)?x-www-form-urlencoded/;\n\n        const consumes = operation.consumes || this.api.consumes || [];\n\n        const hasValidMimeType = consumes.some(consume => {\n          return formData.test(consume) || urlEncoded.test(consume);\n        });\n\n        if (!hasValidMimeType) {\n          this.reportError(\n            `\\`${operationId}\\` has a file parameter, so it must consume \\`multipart/form-data\\` or \\`application/x-www-form-urlencoded\\`.`,\n          );\n        }\n      }\n    });\n  }\n\n  /**\n   * Validates the given response object.\n   *\n   */\n  private validateResponse(code: number | string, response: OpenAPIV2.ResponseObject, responseId: string) {\n    /**\n     * The Swagger JSON Schema allows for any HTTP code between `000` and `999`, where as the OpenAPI\n     * JSON Schema fixed this to require it to be a _known_ code between 100 and 599.\n     *\n     * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/f9a2302ee6707cb65f4aaf180fdce9b0a906701e/schemas/v2.0/schema.json#L350}\n     */\n    if (code !== 'default') {\n      if (\n        (typeof code === 'number' && (code < 100 || code > 599)) ||\n        (typeof code === 'string' && (Number(code) < 100 || Number(code) > 599))\n      ) {\n        this.reportError(`\\`${responseId}\\` has an invalid response code: ${code}`);\n      }\n    }\n\n    Object.keys(response.headers || {}).forEach(headerName => {\n      const header = response.headers[headerName];\n      const headerId = `${responseId}/headers/${headerName}`;\n      this.validateSchema(header, headerId);\n    });\n\n    if (response.schema) {\n      if ('$ref' in response.schema) {\n        return;\n      }\n\n      this.validateSchema(response.schema, `${responseId}/schema`);\n    }\n  }\n\n  /**\n   * Validates the given Swagger schema object.\n   *\n   */\n  private validateSchema(schema: OpenAPIV2.SchemaObject, schemaId: string) {\n    if (schema.type === 'array' && !schema.items) {\n      if (this.rules['array-without-items'] === 'warning') {\n        this.reportWarning(`\\`${schemaId}\\` is an array, so it should include an \\`items\\` schema.`);\n      } else {\n        this.reportError(`\\`${schemaId}\\` is an array, so it must include an \\`items\\` schema.`);\n      }\n    }\n  }\n\n  /**\n   * Validates that the declared properties of the given Swagger schema object actually exist.\n   *\n   */\n  private validateRequiredPropertiesExist(schema: IJsonSchema, schemaId: string) {\n    if (schema.required && Array.isArray(schema.required)) {\n      const props: Record<string, IJsonSchema> = {};\n      this.collectProperties(schema, props);\n      schema.required.forEach(requiredProperty => {\n        if (!props[requiredProperty]) {\n          const error = `Property \\`${requiredProperty}\\` is listed as required but does not exist in \\`${schemaId}\\`.`;\n          if (this.rules['unknown-required-schema-property'] === 'warning') {\n            this.reportWarning(error);\n          } else {\n            this.reportError(error);\n          }\n        }\n      });\n    }\n  }\n\n  /**\n   * Recursively collects all properties of a schema and its ancestors. They are added to the\n   * supplied `props` object.\n   *\n   */\n  private collectProperties(schemaObj: IJsonSchema, props: Record<string, IJsonSchema>) {\n    if (schemaObj.properties) {\n      Object.keys(schemaObj.properties).forEach(property => {\n        // oxlint-disable-next-line no-prototype-builtins -- Intentional\n        if (schemaObj.properties.hasOwnProperty(property)) {\n          props[property] = schemaObj.properties[property];\n        }\n      });\n    }\n\n    if (schemaObj.allOf) {\n      schemaObj.allOf.forEach(parent => {\n        this.collectProperties(parent, props);\n      });\n    }\n  }\n\n  /**\n   * Validates security definitions against their declared `type`.\n   *\n   * AJV uses `oneOf` to validate `securityDefinitions`, so when a definition is malformed AJV\n   * fails every branch and produces overwhelming, unhelpful errors. This pre-AJV pass surfaces\n   * a single targeted error per problem.\n   *\n   * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#security-scheme-object}\n   */\n  private checkSecurityDefinitions() {\n    const securityDefinitions = this.api.securityDefinitions;\n    if (!securityDefinitions) {\n      return;\n    }\n\n    const validApiKeyIn = ['query', 'header'];\n\n    Object.keys(securityDefinitions).forEach(name => {\n      const definition = securityDefinitions[name] as unknown as Record<string, unknown>;\n      const definitionId = `/securityDefinitions/${name}`;\n      const reportIssue = (message: string) => this.reportSecuritySchemeIssue(message, definitionId);\n\n      const type = definition.type as string | undefined;\n\n      // Rule: `type: http` is OpenAPI 3.x syntax, produce a migration hint instead of a\n      // generic \"invalid type\" so users porting from 3.x know to use `type: basic` instead.\n      if (type === 'http') {\n        reportIssue(\n          `\\`${definitionId}\\` uses \\`type: http\\`, which is an OpenAPI 3.x value. In Swagger 2.0 use \\`type: basic\\` for HTTP Basic auth.`,\n        );\n        return;\n      }\n\n      // Rule: Swagger 2.0 `apiKey.in` only allows `query` or `header`. `cookie` was added in\n      // OAS 3.0+, so users carrying it back into a 2.0 spec is the typical mistake.\n      if (type === 'apiKey' && typeof definition.in === 'string' && !validApiKeyIn.includes(definition.in)) {\n        reportIssue(\n          `\\`${definitionId}\\` has an invalid \\`in\\` value: \\`${definition.in}\\`. Swagger 2.0 only supports \\`query\\` or \\`header\\`.`,\n        );\n      }\n    });\n  }\n\n  private reportSecuritySchemeIssue(message: string, definitionId: string) {\n    this.flagInstancePath(definitionId);\n    if (this.rules['invalid-security-scheme-properties'] === 'warning') {\n      this.reportWarning(message);\n    } else {\n      this.reportError(message);\n    }\n  }\n\n  /**\n   * Checks the given parameter list for duplicates.\n   *\n   */\n  private checkForDuplicates(params: OpenAPIV2.ParameterObject[], schemaId: string) {\n    for (let i = 0; i < params.length - 1; i++) {\n      const outer = params[i];\n      for (let j = i + 1; j < params.length; j++) {\n        const inner = params[j];\n        if (outer.name === inner.name && outer.in === inner.in) {\n          const error = `Found multiple \\`${outer.in}\\` parameters named \\`${outer.name}\\` in \\`${schemaId}\\`.`;\n\n          if (this.rules['duplicate-non-request-body-parameters'] === 'warning') {\n            this.reportWarning(error);\n          } else {\n            this.reportError(error);\n          }\n        }\n      }\n    }\n  }\n}\n","import type { ParserRulesOpenAPI, ParserRulesSwagger, ValidationResult } from '../types.js';\nimport type { SpecificationValidator } from './spec/index.js';\nimport type { OpenAPIV2, OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\nimport { isOpenAPI } from '../lib/assertions.js';\nimport { getSpecificationName } from '../lib/index.js';\n\nimport { OpenAPISpecificationValidator } from './spec/openapi.js';\nimport { SwaggerSpecificationValidator } from './spec/swagger.js';\n\n/**\n * Validates either a Swagger 2.0 or OpenAPI 3.x API definition against cases that aren't covered\n * by their respective JSON Schema definitions.\n *\n * Some specification-level cases can be treated as warnings, instead of hard validation erros, by\n * supplying a `rules` configuration to the parsers `validate` option.\n *\n */\nexport function validateSpec(\n  api: OpenAPIV2.Document | OpenAPIV3_1.Document | OpenAPIV3.Document,\n  rules: {\n    openapi: ParserRulesOpenAPI;\n    swagger: ParserRulesSwagger;\n  },\n): ValidationResult {\n  let validator: SpecificationValidator;\n\n  const specificationName = getSpecificationName(api);\n  if (isOpenAPI(api)) {\n    validator = new OpenAPISpecificationValidator(api, rules.openapi);\n  } else {\n    validator = new SwaggerSpecificationValidator(api, rules.swagger);\n  }\n\n  validator.run();\n\n  if (!validator.errors.length) {\n    return {\n      valid: true,\n      warnings: validator.warnings,\n      specification: specificationName,\n    };\n  }\n\n  return {\n    valid: false,\n    errors: validator.errors,\n    warnings: validator.warnings,\n    additionalErrors: 0,\n    specification: specificationName,\n  };\n}\n\n/**\n * Runs spec-level validation that should happen **before** AJV's JSON Schema validation, so that\n * the user gets clear, actionable errors instead of confusing schema-level noise.\n *\n * @returns The pre-schema validation outcome.\n * @returns return.result - The `ValidationResult` of the pre-schema checks; `valid: false` when\n *   any check reported an error, otherwise `valid: true` (warnings are carried either way).\n * @returns return.flaggedInstancePaths - Instance paths (e.g. `/components/securitySchemes/MyAuth`)\n *   for which the pre-schema validator already emitted an error or warning. Pass these into\n *   `validateSchema` so AJV's redundant `oneOf` errors against the same paths get suppressed.\n */\nexport function validateSpecPreSchema(\n  api: OpenAPIV2.Document | OpenAPIV3_1.Document | OpenAPIV3.Document,\n  rules: {\n    openapi: ParserRulesOpenAPI;\n    swagger: ParserRulesSwagger;\n  },\n): { flaggedInstancePaths: string[]; result: ValidationResult } {\n  let validator: SpecificationValidator;\n\n  const specificationName = getSpecificationName(api);\n  if (isOpenAPI(api)) {\n    validator = new OpenAPISpecificationValidator(api, rules.openapi);\n  } else {\n    validator = new SwaggerSpecificationValidator(api, rules.swagger);\n  }\n\n  validator.runPreSchemaChecks();\n\n  const flaggedInstancePaths = validator.flaggedInstancePaths;\n\n  if (!validator.errors.length) {\n    return {\n      flaggedInstancePaths,\n      result: {\n        valid: true,\n        warnings: validator.warnings,\n        specification: specificationName,\n      },\n    };\n  }\n\n  return {\n    flaggedInstancePaths,\n    result: {\n      valid: false,\n      errors: validator.errors,\n      warnings: validator.warnings,\n      additionalErrors: 0,\n      specification: specificationName,\n    },\n  };\n}\n","import type { APIDocument, ErrorDetails, ParserOptions, ValidationResult, WarningDetails } from './types.js';\n\nimport { $RefParser, dereferenceInternal, MissingPointerError } from '@apidevtools/json-schema-ref-parser';\n\nimport { isOpenAPI, isSwagger } from './lib/assertions.js';\nimport { stripOrphanedIds } from './repair.js';\nimport { convertOptionsForParser, normalizeArguments, repairSchema } from './util.js';\nimport { validateSchema } from './validators/schema.js';\nimport { validateSpec, validateSpecPreSchema } from './validators/spec.js';\n\nexport { MissingPointerError };\nexport { ResolverError } from '@apidevtools/json-schema-ref-parser';\nexport type { ParserOptions, ValidationResult, ErrorDetails, WarningDetails };\n\nfunction isFilesystemPathSource(api: unknown): boolean {\n  return typeof api === 'string' && !/^https?:\\/\\//i.test(api);\n}\n\n/**\n * Load the API definition (from an object, file path, or URL) and drop orphaned `$id` keywords\n * before `$ref` resolution. Path and URL sources must be parsed first — stripping only inline\n * objects leaves those sources throwing a spurious \"Missing $ref pointer\" when an orphaned `$id`\n * re-scopes a document-root `#/…` pointer.\n *\n * The original source path is preserved so relative file and HTTP `$ref`s still resolve.\n */\nasync function parseAndStripOrphanedIds<S extends APIDocument>(\n  api: S | string,\n  options?: ParserOptions,\n): Promise<{\n  path: string;\n  schema: S;\n  parserOptions: ReturnType<typeof convertOptionsForParser>;\n}> {\n  const args = normalizeArguments<S>(api);\n  const parserOptions = convertOptionsForParser(options, {\n    allowFileResolution: isFilesystemPathSource(api),\n  });\n\n  if (args.schema) {\n    stripOrphanedIds(args.schema);\n    return { path: args.path, schema: args.schema, parserOptions };\n  }\n\n  const parser = new $RefParser<S>();\n  const schema = await parser.parse(args.path, args.schema, parserOptions);\n  stripOrphanedIds(schema);\n\n  return { path: args.path, schema, parserOptions };\n}\n\n/**\n * Parses the given API definition, in JSON or YAML format, and returns it as a JSON object. This\n * method **does not** resolve `$ref` pointers or dereference anything. It simply parses _one_ file\n * and returns it.\n *\n * @param api - A file path or URL to a JSON Schema object, or the JSON Schema object itself.\n * @param options\n */\nexport async function parse<S extends APIDocument = APIDocument>(api: S | string, options?: ParserOptions): Promise<S> {\n  const args = normalizeArguments<S>(api);\n  const parserOptions = convertOptionsForParser(options, {\n    allowFileResolution: isFilesystemPathSource(api),\n  });\n\n  const parser = new $RefParser<S>();\n  const schema = await parser.parse(args.path, args.schema, parserOptions);\n\n  // If necessary, repair the schema of any anomalies and quirks.\n  repairSchema(schema, args.path);\n\n  return schema;\n}\n\n/**\n * Bundles all referenced files and URLs into a single API definition that only has _internal_\n * `$ref` pointers. This lets you split up your definition however you want while you're building\n * it, but later combine all those files together when it's time to package or distribute the API\n * definition to other people. The resulting definition size will be small, since it will still\n * contain _internal_ JSON references rather than being fully-dereferenced.\n *\n * @param api - A file path or URL to a JSON Schema object, or the JSON Schema object itself.\n * @param options\n */\nexport async function bundle<S extends APIDocument = APIDocument>(\n  api: S | string,\n  options?: ParserOptions,\n): Promise<S> {\n  const { path, schema: preparedSchema, parserOptions } = await parseAndStripOrphanedIds(api, options);\n\n  const parser = new $RefParser<S>();\n  await parser.bundle(path, preparedSchema, parserOptions);\n\n  // Our API definitions are always objects, never bare JSON Schema booleans.\n  const schema = parser.schema as S;\n\n  // If necessary, repair the schema of any anomalies and quirks.\n  repairSchema(schema, path);\n\n  return schema;\n}\n\n/**\n * Dereferences all `$ref` pointers in the supplied API definition, replacing each reference with\n * its resolved value. This results in an API definition that does not contain _any_ `$ref`\n * pointers. Instead, it's a normal JSON object tree that can easily be crawled and used just like\n * any other object. This is great for programmatic usage, especially when using tools that don't\n * understand JSON references.\n *\n * @param api - A file path or URL to a JSON Schema object, or the JSON Schema object itself.\n * @param options\n */\nexport async function dereference<S extends APIDocument = APIDocument>(\n  api: S | string,\n  options?: ParserOptions,\n): Promise<S> {\n  const { path, schema: preparedSchema, parserOptions } = await parseAndStripOrphanedIds(api, options);\n\n  const parser = new $RefParser<S>();\n  await parser.dereference(path, preparedSchema, parserOptions);\n\n  // Our API definitions are always objects, never bare JSON Schema booleans.\n  const schema = parser.schema as S;\n\n  // If necessary, repair the schema of any anomalies and quirks.\n  repairSchema(schema, path);\n\n  return schema;\n}\n\n/**\n * Validates the API definition against the Swagger 2.0, OpenAPI 3.0, or OpenAPI 3.1 specifications.\n *\n * In addition to validating the API definition against their respective specification schemas it\n * will also be validated against specific areas that aren't covered by the Swagger or OpenAPI\n * schemas, such as duplicate parameters, invalid component schema names, or duplicate\n * `operationId` values.\n *\n * If validation fails an error will be thrown with information about what, and where, the error\n * lies within the API definition.\n *\n * Internally this method invokes [`dereference()`](#dereference) so the returned object, whether\n * its a Swagger or OpenAPI definition, will be fully dereferenced.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/tree/main/schemas/v2.0}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/tree/main/schemas/v3.0}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/tree/main/schemas/v3.1}\n * @param api - A file path or URL to a JSON Schema object, or the JSON Schema object itself.\n * @param options\n */\nexport async function validate<S extends APIDocument, Options extends ParserOptions>(\n  api: S | string,\n  options?: Options,\n): Promise<ValidationResult> {\n  const { path, schema: preparedSchema, parserOptions } = await parseAndStripOrphanedIds(api, options);\n\n  let result: ValidationResult;\n\n  // ZSchema doesn't support circular objects, so don't dereference circular $refs yet\n  // (see https://github.com/zaggino/z-schema/issues/137)\n  const circular$RefOption = parserOptions.dereference?.circular;\n  if (parserOptions.dereference) {\n    parserOptions.dereference.circular = 'ignore';\n  } else {\n    parserOptions.dereference = {\n      circular: 'ignore',\n    };\n  }\n\n  const parser = new $RefParser<S>();\n  try {\n    await parser.dereference(path, preparedSchema, parserOptions);\n  } catch (err) {\n    // `json-schema-ref-parser` will throw exceptions on things like `$ref` pointers that can't\n    // be resolved so we need to capture and reformat those into our expected `ValidationResult`\n    // format.\n    if (err instanceof MissingPointerError) {\n      return {\n        valid: false,\n        errors: [{ message: err.message }],\n        warnings: [],\n        additionalErrors: 0,\n        specification: null,\n      };\n    }\n\n    throw err;\n  }\n\n  if (!isSwagger(parser.schema) && !isOpenAPI(parser.schema)) {\n    return {\n      valid: false,\n      errors: [{ message: 'Supplied schema is not a valid API definition.' }],\n      warnings: [],\n      additionalErrors: 0,\n      specification: null,\n    };\n  }\n\n  // Restore the original options, now that we're done dereferencing\n  parserOptions.dereference.circular = circular$RefOption;\n\n  const openapiRules = options?.validate?.rules?.openapi;\n  const swaggerRules = options?.validate?.rules?.swagger;\n  const rules = {\n    openapi: {\n      'array-without-items': openapiRules?.['array-without-items'] || 'error',\n      'duplicate-non-request-body-parameters': openapiRules?.['duplicate-non-request-body-parameters'] || 'error',\n      'duplicate-operation-id': openapiRules?.['duplicate-operation-id'] || 'error',\n      'invalid-security-scheme-properties': openapiRules?.['invalid-security-scheme-properties'] || 'error',\n      'non-optional-path-parameters': openapiRules?.['non-optional-path-parameters'] || 'error',\n      'path-parameters-not-in-parameters': openapiRules?.['path-parameters-not-in-parameters'] || 'error',\n      'path-parameters-not-in-path': openapiRules?.['path-parameters-not-in-path'] || 'error',\n    },\n    swagger: {\n      'array-without-items': swaggerRules?.['array-without-items'] || 'error',\n      'duplicate-non-request-body-parameters': swaggerRules?.['duplicate-non-request-body-parameters'] || 'error',\n      'duplicate-operation-id': swaggerRules?.['duplicate-operation-id'] || 'error',\n      'invalid-security-scheme-properties': swaggerRules?.['invalid-security-scheme-properties'] || 'error',\n      'non-optional-path-parameters': swaggerRules?.['non-optional-path-parameters'] || 'error',\n      'path-parameters-not-in-parameters': swaggerRules?.['path-parameters-not-in-parameters'] || 'error',\n      'path-parameters-not-in-path': swaggerRules?.['path-parameters-not-in-path'] || 'error',\n      'unknown-required-schema-property': swaggerRules?.['unknown-required-schema-property'] || 'error',\n    },\n  };\n\n  // Run pre-schema spec validation (i.e. things that AJV does poorly), like security scheme\n  // structural checks. If these fail, surface their errors directly instead of letting AJV\n  // produce confusing `oneOf` noise.\n  const { result: preSchemaResult, flaggedInstancePaths } = validateSpecPreSchema(parser.schema, rules);\n  if (!preSchemaResult.valid) {\n    return preSchemaResult;\n  }\n\n  // Validate the API against the OpenAPI or Swagger JSON schema definition. We pass the\n  // pre-schema-flagged instance paths so that AJV errors against those paths are filtered out\n  // (their issues have already been reported by the pre-schema validator).\n  // NOTE: This is safe to do, because we haven't dereferenced circular $refs yet\n  result = validateSchema(parser.schema, options, flaggedInstancePaths);\n  if (!result.valid) {\n    if (preSchemaResult.warnings.length) {\n      result.warnings = [...preSchemaResult.warnings, ...result.warnings];\n    }\n    return result;\n  }\n\n  if (parser.$refs?.circular) {\n    if (circular$RefOption === true) {\n      // The API has circular reference so we need to do a second pass to fully dereference it.\n      dereferenceInternal<S>(parser, parserOptions);\n    } else if (circular$RefOption === false) {\n      // The API has circular references but we're configured to not permit that.\n      throw new ReferenceError(\n        'The API contains circular references but the validator is configured to not permit them.',\n      );\n    }\n  }\n\n  // Validate the API against the OpenAPI or Swagger specification.\n  result = validateSpec(parser.schema, rules);\n\n  if (preSchemaResult.warnings.length) {\n    result.warnings = [...preSchemaResult.warnings, ...result.warnings];\n  }\n\n  return result;\n}\n\n/**\n * A utility to transform the `ValidationResult` from a `validate()` call into a human-readable\n * string.\n *\n */\nexport function compileErrors(result: ValidationResult): string {\n  const specName = result.specification || 'API definition';\n  const status = !result.valid ? 'failed' : 'succeeded, but with warnings';\n\n  const message: string[] = [`${specName} schema validation ${status}.`];\n\n  if (result.valid === false) {\n    if (result.errors.length) {\n      message.push(...result.errors.map(err => err.message));\n    }\n  }\n\n  if (result.warnings.length) {\n    if (result.valid === false && result.errors.length) {\n      message.push('We have also found some additional warnings:');\n    }\n\n    message.push(...result.warnings.map(warn => warn.message));\n  }\n\n  if (result.valid === false && result.additionalErrors > 0) {\n    message.push(\n      `Plus an additional ${result.additionalErrors} errors. Please resolve the above and re-run validation to see more.`,\n    );\n  }\n\n  return message.join('\\n\\n');\n}\n"]}