From 26e582d09fd586019e64154693bcd2e0b59a7e53 Mon Sep 17 00:00:00 2001 From: Joel Webber Date: Tue, 19 May 2026 15:23:00 -0400 Subject: [PATCH 1/2] =?UTF-8?q?tunnel:=20package=20hygiene=20=E2=80=94=20s?= =?UTF-8?q?plit=20build/dist,=20untrack=20artifacts,=20harden=20publish?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cleans up the publish flow so the tarball is always self-contained and local builds can't get into a half-built state. - .gitignore: untrack tunnel/build/ and tunnel/dist/. tsc and rollup outputs are reproducible from sources; carrying them in git produced a 38k-line phantom diff every time `bundle` was run because rollup overwrote the small re-export with the full bundled output at the same path. - rollup.config.mjs: bundle the entire CLI (input build/src/index.js) into a single dist/index.js. Build (tsc → build/) and bundle (rollup → dist/) now write to disjoint trees; no more clobbering. - package.json: - bin/files now point at dist/. - clean wipes both build/ and dist/. - build = clean && tsc (always a fresh build). - bundle = build && rollup. - test = build && node --test (self-bootstrapping). - prepack = bundle (covers both `npm pack` and `npm publish`). - verify = npm pack --dry-run (quick "what would ship?" check). - prepublishOnly removed (covered by prepack). - main.ts: walk up to find package.json instead of hard-coding ../.. since the bundled file at dist/index.js sits one level above package.json and the tsc output at build/src/main.js sits two levels above. - CLAUDE.md: add Tunnel Development section documenting the build/test scripts and the gitignored artifact trees. - Version bumps: tunnel 0.1.17 → 0.1.18, plugin 0.2.8 → 0.2.9. Verified: `npm pack --dry-run` ships exactly two files (dist/index.js + package.json); all 137 tests pass. --- .gitignore | 5 + CLAUDE.md | 13 + tunnel/build/src/allowlist.js | 179 - tunnel/build/src/client.js | 281 - tunnel/build/src/index.js | 16 - tunnel/build/src/loopback.js | 89 - tunnel/build/src/main.js | 285 - tunnel/build/src/third_party/index.js | 38011 ------------------------ tunnel/build/src/transport.js | 53 - tunnel/build/src/transport_legacy.js | 247 - tunnel/build/src/transport_yamux.js | 251 - tunnel/build/src/types.js | 22 - tunnel/build/src/yamux.js | 449 - tunnel/package.json | 17 +- tunnel/rollup.config.mjs | 33 +- tunnel/src/main.ts | 57 +- 16 files changed, 82 insertions(+), 39926 deletions(-) delete mode 100644 tunnel/build/src/allowlist.js delete mode 100644 tunnel/build/src/client.js delete mode 100644 tunnel/build/src/index.js delete mode 100644 tunnel/build/src/loopback.js delete mode 100644 tunnel/build/src/main.js delete mode 100644 tunnel/build/src/third_party/index.js delete mode 100644 tunnel/build/src/transport.js delete mode 100644 tunnel/build/src/transport_legacy.js delete mode 100644 tunnel/build/src/transport_yamux.js delete mode 100644 tunnel/build/src/types.js delete mode 100644 tunnel/build/src/yamux.js diff --git a/.gitignore b/.gitignore index 78b8841a..4d57502c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,8 @@ node_modules/ # Local design docs, plans, and skill-eval writeups. Authored alongside # implementation work but not part of the shipped plugin surface. docs/ + +# Tunnel package build artifacts. tsc emits to build/, rollup emits to dist/. +# Both are reproducible from sources; npm publish regenerates them via prepack. +tunnel/build/ +tunnel/dist/ diff --git a/CLAUDE.md b/CLAUDE.md index 808bf16d..498bb778 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,3 +18,16 @@ Version bumps are automated via [Changesets](https://github.com/changesets/chang For any user-facing PR, run `npm run changeset`, pick a bump type, and commit the generated `.changeset/*.md` file. On merge to `main`, the workflow opens a "Version Packages" PR that bumps `package.json` and syncs the version into all harness manifests (`.claude-plugin/`, `.codex-plugin/`, `.cursor-plugin/`, and `marketplace.json`) via `scripts/sync-manifest-versions.mjs`. Merging that PR creates the git tag and GitHub release. See [`.changeset/README.md`](.changeset/README.md) for the full workflow. Pure-infra / docs PRs can skip the changeset. + +# Tunnel Development + +`tunnel/build/` and `tunnel/dist/` are gitignored build artifacts — never commit them. + +| Script | What it does | +|--------|--------------| +| `npm run build` | `clean` then `tsc` → emits JS to `build/` (used by tests and local dev) | +| `npm run bundle` | `build` then `rollup` → emits the single-file CLI to `dist/` (what npm ships) | +| `npm test` | `build` then `node --test` (self-bootstrapping; no stale build surprises) | +| `npm run verify` | `npm pack --dry-run` — shows exactly what `npm publish` would ship | + +`prepack` runs `bundle` automatically, so `npm publish` and `npm pack` are always self-contained even if you forget to run `bundle` first. diff --git a/tunnel/build/src/allowlist.js b/tunnel/build/src/allowlist.js deleted file mode 100644 index 19229840..00000000 --- a/tunnel/build/src/allowlist.js +++ /dev/null @@ -1,179 +0,0 @@ -const LOOPBACK_V4_RE = /^127\.\d+\.\d+\.\d+$/; -const IPV4_RE = /^\d+\.\d+\.\d+\.\d+$/; -function isLoopbackIP(host) { - if (host === '::1' || host === '0:0:0:0:0:0:0:1') - return true; - return LOOPBACK_V4_RE.test(host); -} -function isLoopbackClassDNS(host) { - if (host === 'localhost' || host === 'test') - return true; - return host.endsWith('.localhost') || host.endsWith('.test'); -} -function isAllDigits(s) { - return s.length > 0 && /^\d+$/.test(s); -} -/** - * lastTwoLabels collapses a multi-label DNS host to its last two labels. - * Single-label hosts (like `localhost`) are returned unchanged. - */ -function lastTwoLabels(host) { - const parts = host.split('.'); - if (parts.length <= 2) - return host; - return parts.slice(-2).join('.'); -} -/** - * canonicalizeHost validates a host and returns its canonical form. DNS - * hosts collapse to the last two labels (or stay as-is for bare `test` / - * `localhost`). IP literals must be loopback and are returned unchanged. - */ -function canonicalizeHost(host) { - const lc = host.toLowerCase(); - if (!lc) - throw new Error('missing host'); - // IPv6 (contains a colon outside brackets) or IPv4: classify and validate. - if (lc === '::1' || lc === '0:0:0:0:0:0:0:1') { - return { canonical: '::1', isIP: true }; - } - if (IPV4_RE.test(lc)) { - if (!isLoopbackIP(lc)) { - throw new Error(`IP ${JSON.stringify(host)} must be loopback (127.x or ::1)`); - } - return { canonical: lc, isIP: true }; - } - if (!isLoopbackClassDNS(lc)) { - throw new Error(`host ${JSON.stringify(host)} must be loopback-class (localhost, *.localhost, *.test)`); - } - return { canonical: lastTwoLabels(lc), isIP: false }; -} -/** - * parseOriginPattern parses a single allowlist entry. Accepts the canonical - * "host:port" grammar. For transitional compatibility it also strips a - * leading "scheme://" and a "*." wildcard prefix — both are no-ops under - * the new rules (scheme is ignored, subdomains are implicit) and we prefer - * to canonicalize quietly rather than reject inputs that mean the same - * thing. - */ -export function parseOriginPattern(s) { - if (!s) - throw new Error('empty origin pattern'); - const raw = s; - // Tolerate legacy "scheme://" prefix. - const schemeIdx = s.indexOf('://'); - if (schemeIdx >= 0) - s = s.slice(schemeIdx + 3); - // Tolerate legacy "*." wildcard prefix. - if (s.startsWith('*.')) - s = s.slice(2); - if (s.includes('*')) { - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: '*' is no longer supported; subdomains are implicit`); - } - if (/[/?#@]/.test(s)) { - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: must be host:port (no path, query, fragment, or userinfo)`); - } - let host; - let port; - if (s.startsWith('[')) { - // IPv6 bracketed form: [::1]:443 - const closeIdx = s.indexOf(']'); - if (closeIdx < 0) { - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: unmatched '[' in IPv6 host`); - } - host = s.slice(1, closeIdx); - const rest = s.slice(closeIdx + 1); - if (!rest.startsWith(':')) { - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: must be host:port with an explicit numeric port`); - } - port = rest.slice(1); - } - else { - const colonIdx = s.lastIndexOf(':'); - if (colonIdx < 0) { - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: must be host:port with an explicit numeric port`); - } - host = s.slice(0, colonIdx); - port = s.slice(colonIdx + 1); - } - if (!isAllDigits(port)) { - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: must be host:port with an explicit numeric port`); - } - let canonical; - let isIP; - try { - ({ canonical, isIP } = canonicalizeHost(host)); - } - catch (err) { - const msg = err instanceof Error ? err.message : String(err); - throw new Error(`invalid origin pattern ${JSON.stringify(raw)}: ${msg}`); - } - return { host: canonical, port, isIP, raw }; -} -export function parseOriginPatterns(entries) { - if (!entries || entries.length === 0) - return []; - return entries.map(parseOriginPattern); -} -/** - * originPatternString renders a pattern back to its canonical "host:port" - * form, bracketing IPv6 hosts. Used in error messages and log output so the - * user sees what was actually accepted. - */ -export function originPatternString(p) { - if (p.isIP && p.host.includes(':')) - return `[${p.host}]:${p.port}`; - return `${p.host}:${p.port}`; -} -/** - * canonicalizedFrom returns the original input if it differs from the - * canonical form. Returns undefined when the input was already canonical. - * MCP callers surface this back to agents so they see what was accepted. - */ -export function canonicalizedFrom(p) { - if (!p.raw || p.raw === originPatternString(p)) - return undefined; - return p.raw; -} -/** - * patternMatches reports whether pattern matches the canonical origin string - * `scheme://host:port`. Scheme is ignored; port must match exactly. DNS - * patterns match the bare host plus any subdomain; IP patterns match exactly. - */ -const ORIGIN_RE = /^(?:http|https):\/\/([^/?#]+)$/; -export function patternMatches(pattern, origin) { - const m = ORIGIN_RE.exec(origin); - if (!m) - return false; - const authority = m[1]; - let host; - let port; - if (authority.startsWith('[')) { - const closeIdx = authority.indexOf(']'); - if (closeIdx < 0) - return false; - host = authority.slice(1, closeIdx).toLowerCase(); - const rest = authority.slice(closeIdx + 1); - if (!rest.startsWith(':')) - return false; - port = rest.slice(1); - } - else { - const colonIdx = authority.lastIndexOf(':'); - if (colonIdx < 0) - return false; - host = authority.slice(0, colonIdx).toLowerCase(); - port = authority.slice(colonIdx + 1); - } - if (port !== pattern.port) - return false; - if (pattern.isIP) - return host === pattern.host; - return host === pattern.host || host.endsWith('.' + pattern.host); -} -export function matchesAny(patterns, origin) { - for (const p of patterns) { - if (patternMatches(p, origin)) - return true; - } - return false; -} diff --git a/tunnel/build/src/client.js b/tunnel/build/src/client.js deleted file mode 100644 index 6b443725..00000000 --- a/tunnel/build/src/client.js +++ /dev/null @@ -1,281 +0,0 @@ -import { EventEmitter } from 'node:events'; -import { WebSocket } from './third_party/index.js'; -import { parseOriginPatterns } from './allowlist.js'; -import { RECONNECT_BASE_MS, RECONNECT_MAX_MS, RESUME_SUBPROTOCOL_PREFIX, STALE_CONNECTION_MS, YAMUX_PING_INTERVAL_MS, } from './types.js'; -import { LegacyTransport } from './transport_legacy.js'; -import { YamuxTransport } from './transport_yamux.js'; -/** - * TunnelClient manages the WebSocket connection lifecycle: connect, handshake, - * reconnect. After the hello/ready exchange it delegates all protocol-specific - * work to a TunnelTransport (LegacyTransport or YamuxTransport). - * - * Emits 'need_live_tunnel' when a resume token is rejected (401), indicating - * the caller must obtain a fresh relay URL via live-tunnel before reconnecting. - */ -export class TunnelClient extends EventEmitter { - #relayUrl; - #initialConnectionId; - #connectionId; - #upgradeHeaders; - #log; - #allowedOriginsRaw; - #allowedOrigins; - #staleTimeoutMs; - #yamuxPingIntervalMs; - #ws = null; - #state = 'disconnected'; - #tunnelId; - #transport = null; - #reconnectAttempts = 0; - #reconnectTimer = null; - #staleTimer = null; - #connectedSince = null; - #intentionalDisconnect = false; - #resumeToken; - #traceId; - constructor(opts) { - super(); - this.#relayUrl = opts.relayUrl; - this.#initialConnectionId = opts.connectionId; - this.#connectionId = opts.connectionId; - this.#log = opts.log; - this.#upgradeHeaders = opts.headers ?? {}; - // Parse the allowlist once at construction. Throws if any entry is - // malformed — surfacing the error here is friendlier than waiting for - // the relay to reject the hello. - this.#allowedOriginsRaw = opts.allowedOrigins; - this.#allowedOrigins = parseOriginPatterns(opts.allowedOrigins); - this.#staleTimeoutMs = opts.staleTimeoutMs ?? STALE_CONNECTION_MS; - this.#yamuxPingIntervalMs = opts.yamuxPingIntervalMs ?? YAMUX_PING_INTERVAL_MS; - } - get state() { - return this.#state; - } - get tunnelId() { - return this.#tunnelId; - } - get connectionId() { - return this.#connectionId; - } - get traceId() { - return this.#traceId; - } - connect() { - this.#intentionalDisconnect = false; - this.#doConnect(); - } - disconnect() { - this.#intentionalDisconnect = true; - this.#cleanup(); - this.#state = 'disconnected'; - } - // ----- Connection lifecycle ----- - #doConnect() { - this.#state = 'connecting'; - // Resume path authenticates via subprotocol; strip the (spent) nonce token. - // Keep connection_id in the URL — the relay's affinity router hashes on it - // to send the WS to the pod that owns the chromium browser context. Without - // it, the affinity router mints a fresh UUID and the reconnect lands on a - // random pod; the new tunnel registers there with the (correct, preserved) - // connection_id, but the chromium-side forward proxy on the original pod - // still can't see it and the next navigation gets ERR_TUNNEL_CONNECTION_FAILED. - // Initial path keeps the relay URL intact and sets connection_id if provided. - const u = new URL(this.#relayUrl); - let protocols; - if (this.#resumeToken) { - u.searchParams.delete('token'); - if (this.#connectionId) { - u.searchParams.set('connection_id', this.#connectionId); - } - protocols = [`${RESUME_SUBPROTOCOL_PREFIX}${this.#resumeToken}`]; - } - else if (this.#initialConnectionId) { - u.searchParams.set('connection_id', this.#initialConnectionId); - } - const wsUrlStr = u.toString(); - this.#log(`Connecting to ${wsUrlStr}`); - const ws = protocols - ? new WebSocket(wsUrlStr, protocols, { headers: this.#upgradeHeaders }) - : new WebSocket(wsUrlStr, { headers: this.#upgradeHeaders }); - // Handle non-101 upgrade responses (e.g. 401 on resume token replay). - ws.on('unexpected-response', (_req, res) => { - this.#log(`Relay rejected upgrade: ${res.statusCode}`); - if (res.statusCode === 401) { - this.#resumeToken = undefined; - this.#traceId = undefined; - this.#intentionalDisconnect = true; - this.emit('need_live_tunnel'); - } - res.resume(); // drain so socket can be released - }); - ws.on('open', () => { - this.#state = 'connected'; - this.#connectedSince = Date.now(); - this.#log('WebSocket open, sending hello'); - const hello = { - type: 'hello', - protocol: 'yamux', - streaming: true, - }; - if (this.#allowedOriginsRaw && this.#allowedOriginsRaw.length > 0) { - hello.allowedOrigins = this.#allowedOriginsRaw; - } - // On resume path the server already knows the connectionId; don't echo - // the stale initial value. - if (this.#initialConnectionId && !this.#resumeToken) { - hello.connectionId = this.#initialConnectionId; - } - ws.send(JSON.stringify(hello)); - this.#resetStaleTimer(); - }); - // Listen for the ready message (always JSON, regardless of protocol). - const handshakeHandler = (data) => { - this.#resetStaleTimer(); - let msg; - try { - msg = JSON.parse(data.toString()); - } - catch { - this.#log(`Invalid message from relay: ${data.toString().slice(0, 200)}`); - return; - } - if (msg.type === 'error') { - // Server rejected the resume (e.g. RotateConnection DB failure). - // Token already revoked server-side; skip reconnect and request a - // fresh live-tunnel instead. - this.#log(`Relay handshake error: ${msg.message}`); - this.#resumeToken = undefined; - this.#traceId = undefined; - ws.removeListener('message', handshakeHandler); - this.#intentionalDisconnect = true; - ws.close(); - this.emit('need_live_tunnel'); - return; - } - if (msg.type !== 'ready') { - this.#log(`Expected ready, got: ${msg.type}`); - return; - } - ws.removeListener('message', handshakeHandler); - this.#tunnelId = msg.tunnelId; - this.#connectionId = msg.connectionId; - // Capture rotating resume token and stable trace ID from the server. - // The server preserves the connection_id across resume (lidar - // tryResume reads it from the trace row), so the chromium browser - // context's forward proxy continues to find tunnels after reconnect. - if (msg.resumeToken !== undefined) - this.#resumeToken = msg.resumeToken; - if (msg.traceId !== undefined) - this.#traceId = msg.traceId; - this.#state = 'ready'; - this.#reconnectAttempts = 0; - this.#log(`Tunnel ready: ${msg.tunnelId} (connection ${msg.connectionId})`); - // Create the transport based on negotiated protocol. Both transports - // wire onActivity to the stale-timer reset: yamux server-initiated - // pings alone are not sufficient for liveness, since a silently dropped - // WS leaves us with no way to learn the peer is gone. The yamux session - // also sends its own client-initiated PINGs to keep stateful - // intermediaries (linkerd, NATs, LBs) from idling us out. - if (msg.protocol === 'yamux') { - this.#transport = new YamuxTransport({ - ws, - log: this.#log, - streaming: msg.streaming === true, - allowedOrigins: this.#allowedOrigins, - onActivity: () => this.#resetStaleTimer(), - pingIntervalMs: this.#yamuxPingIntervalMs, - }); - } - else { - this.#transport = new LegacyTransport({ - ws, - log: this.#log, - onActivity: () => this.#resetStaleTimer(), - allowedOrigins: this.#allowedOrigins, - }); - } - // Transport.serve() resolves when the WebSocket closes or the session - // tears down. The close handler below then triggers reconnect. - // Catch unexpected rejections so they don't become unhandled and kill - // the process -- treat them the same as a connection drop. - this.#transport.serve().catch((err) => { - this.#log(`Transport error: ${err instanceof Error ? err.message : String(err)}`); - this.#onDisconnect(); - }); - }; - ws.on('message', handshakeHandler); - ws.on('close', (code, reason) => { - this.#log(`WebSocket closed: ${code} ${reason.toString()}`); - this.#onDisconnect(); - }); - ws.on('error', (err) => { - this.#log(`WebSocket error: ${err.message}`); - // 'close' fires after 'error', so reconnect happens there - }); - this.#ws = ws; - } - // ----- Disconnect / reconnect ----- - #onDisconnect() { - this.#transport?.close(); - this.#transport = null; - this.#clearStaleTimer(); - this.#tunnelId = undefined; - this.#ws = null; - if (this.#intentionalDisconnect) { - this.#state = 'disconnected'; - return; - } - // Reset backoff if we had a healthy connection for >60s - if (this.#connectedSince !== null && - Date.now() - this.#connectedSince > 60_000) { - this.#reconnectAttempts = 0; - } - this.#state = 'disconnected'; - this.#scheduleReconnect(); - } - #scheduleReconnect() { - const delay = Math.min(RECONNECT_BASE_MS * Math.pow(2, this.#reconnectAttempts), RECONNECT_MAX_MS); - // Add jitter: 0-25% of delay - const jitter = Math.random() * delay * 0.25; - const total = Math.round(delay + jitter); - this.#reconnectAttempts++; - this.#log(`Reconnecting in ${total}ms (attempt ${this.#reconnectAttempts})`); - this.#reconnectTimer = setTimeout(() => { - this.#reconnectTimer = null; - this.#doConnect(); - }, total); - } - // ----- Stale connection detection ----- - #resetStaleTimer() { - this.#clearStaleTimer(); - this.#staleTimer = setTimeout(() => { - this.#log('Connection stale, reconnecting'); - this.#ws?.close(); - }, this.#staleTimeoutMs); - } - #clearStaleTimer() { - if (this.#staleTimer !== null) { - clearTimeout(this.#staleTimer); - this.#staleTimer = null; - } - } - // ----- Cleanup ----- - #cleanup() { - this.#transport?.close(); - this.#transport = null; - this.#clearStaleTimer(); - if (this.#reconnectTimer !== null) { - clearTimeout(this.#reconnectTimer); - this.#reconnectTimer = null; - } - if (this.#ws) { - this.#ws.removeAllListeners(); - // Re-attach a no-op error handler: close() on a CONNECTING socket emits - // 'error' synchronously; without a listener Node throws. - this.#ws.on('error', () => { }); - this.#ws.close(); - this.#ws = null; - } - this.#tunnelId = undefined; - } -} diff --git a/tunnel/build/src/index.js b/tunnel/build/src/index.js deleted file mode 100644 index cc385ed0..00000000 --- a/tunnel/build/src/index.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node -import { version } from 'node:process'; -const [major, minor] = version.substring(1).split('.').map(Number); -if (major === 20 && minor < 11) { - console.error(`ERROR: \`subtext-tunnel\` does not support Node ${process.version}. Please upgrade to Node 20.11.0 LTS or a newer LTS.`); - process.exit(1); -} -if (major === 22 && minor < 12) { - console.error(`ERROR: \`subtext-tunnel\` does not support Node ${process.version}. Please upgrade to Node 22.12.0 LTS or a newer LTS.`); - process.exit(1); -} -if (major < 20) { - console.error(`ERROR: \`subtext-tunnel\` does not support Node ${process.version}. Please upgrade to Node 20.11.0 LTS or a newer LTS.`); - process.exit(1); -} -await import('./main.js'); diff --git a/tunnel/build/src/loopback.js b/tunnel/build/src/loopback.js deleted file mode 100644 index d5d8f39c..00000000 --- a/tunnel/build/src/loopback.js +++ /dev/null @@ -1,89 +0,0 @@ -import { promises as dns } from 'node:dns'; -import * as net from 'node:net'; -/** - * resolveLoopbackOrigin verifies that `hostname` resolves to a loopback IP - * and returns the resolved address along with a fetch-friendly URL. - * - * The returned `ipUrl` rewrites the host portion to the resolved IP literal - * so the subsequent fetch() does NOT do its own DNS lookup. This is the - * load-bearing defense against DNS rebinding: by pinning the IP after the - * loopback check, an attacker can no longer flip the resolution between - * "check" and "fetch." - * - * The Host: header should be reset to the original hostname:port by the - * caller so virtual-host routing on the upstream still works. - * - * Throws if: - * - DNS lookup fails entirely - * - The resolved IP is not in 127.0.0.0/8 or ::1 - */ -export async function resolveLoopbackOrigin(origin) { - const u = parseOriginStrict(origin); - const { scheme, host, port } = u; - // If the host is already an IP literal, we still validate it before letting - // it through. Avoids the case where a malicious relay sends an Origin like - // "http://10.0.0.1:80/" expecting fetch() to skip resolution. - let ip; - let family; - if (net.isIP(host)) { - ip = host; - family = net.isIP(host) === 6 ? 6 : 4; - } - else { - // Resolve all addresses and prefer IPv4. On dual-stack hosts, localhost - // maps to both 127.0.0.1 and ::1; the OS may return ::1 first even when - // the server only binds IPv4. Sorting family 4 before 6 fixes that while - // still falling back to ::1 on IPv6-only setups. - const results = await dns.lookup(host, { all: true, family: 0 }); - const sorted = [...results].sort((a, b) => a.family - b.family); - ip = sorted[0].address; - family = sorted[0].family; - } - if (!isLoopbackIP(ip)) { - throw new Error(`loopback check failed: ${host} resolved to ${ip}, not loopback`); - } - // Rewrite the URL to the IP literal so fetch() doesn't re-resolve. Bracket - // IPv6 addresses for URL syntax. - const ipHost = family === 6 ? `[${ip}]` : ip; - const ipUrl = `${scheme}://${ipHost}:${port}`; - return { scheme, hostname: host, port, resolvedIp: ip, family, ipUrl }; -} -const LOOPBACK_V4_RE = /^127\.\d+\.\d+\.\d+$/; -export function isLoopbackIP(ip) { - if (LOOPBACK_V4_RE.test(ip)) - return true; - // IPv6 ::1 has multiple representations after normalization. - if (ip === '::1' || ip === '0:0:0:0:0:0:0:1') - return true; - return false; -} -const ORIGIN_RE = /^(http|https):\/\/([^\/?#]+)$/; -function parseOriginStrict(origin) { - const m = ORIGIN_RE.exec(origin); - if (!m) - throw new Error(`invalid origin: ${origin}`); - const [, scheme, authority] = m; - let host; - let port; - if (authority.startsWith('[')) { - // IPv6 bracketed form: [::1]:8080 - const closeIdx = authority.indexOf(']'); - if (closeIdx < 0) - throw new Error(`invalid origin: ${origin}`); - host = authority.slice(1, closeIdx); - const rest = authority.slice(closeIdx + 1); - if (!rest.startsWith(':')) - throw new Error(`invalid origin: ${origin}`); - port = rest.slice(1); - } - else { - const colonIdx = authority.lastIndexOf(':'); - if (colonIdx < 0) - throw new Error(`invalid origin: ${origin} (port required)`); - host = authority.slice(0, colonIdx); - port = authority.slice(colonIdx + 1); - } - if (!port || !/^\d+$/.test(port)) - throw new Error(`invalid origin: ${origin} (port required)`); - return { scheme: scheme, host, port }; -} diff --git a/tunnel/build/src/main.js b/tunnel/build/src/main.js deleted file mode 100644 index f9f06030..00000000 --- a/tunnel/build/src/main.js +++ /dev/null @@ -1,285 +0,0 @@ -import process from "node:process"; -import { readFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname, join } from "node:path"; -import { McpServer, StdioServerTransport, z, yargs, hideBin, } from "./third_party/index.js"; -import { TunnelClient } from "./client.js"; -import { canonicalizedFrom, originPatternString, parseOriginPatterns, } from "./allowlist.js"; -// Single source of truth: read version from package.json at runtime so it -// can't drift from what npm publishes. From build/src/main.js, package.json -// sits two levels up at the package root. -const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json"), "utf8")); -const VERSION = pkg.version; -await yargs(hideBin(process.argv)) - .version(VERSION) - .help() - .parse(); -// Wrap console.error so a broken stderr (e.g. parent process died and closed -// the read side of the pipe) cannot recurse into our error handlers below. -// Without this guard the sequence stderr.write -> EPIPE -> uncaughtException -// -> log() -> stderr.write spins at 100% CPU forever. See orphan_spin.test.ts. -const log = (msg) => { - try { - console.error(`[subtext-tunnel] ${msg}`); - } - catch { - // Logger itself failed; nothing we can do. Don't recurse. - } -}; -// Multiple tunnels can be active simultaneously, keyed by tunnelId. -const clients = new Map(); -const server = new McpServer({ - name: "subtext_tunnel", - version: VERSION, -}, { capabilities: {} }); -server.registerTool("tunnel-connect", { - description: "Connect a tunnel to the relay. Multiple tunnels can be active simultaneously. " + - "Call live-tunnel on the subtext MCP server first to obtain the relayUrl.", - inputSchema: z.object({ - relayUrl: z - .string() - .describe("WebSocket URL of the relay (from live-tunnel)"), - connectionId: z - .string() - .optional() - .describe("Connection ID to bind this tunnel to. Required for connection-first flow " + - "(pass the connection_id from open_connection). Omit for tunnel-first flow " + - "(the server mints one and returns it in the response)."), - allowedOrigins: z - .array(z.string()) - .optional() - .describe("Optional per-tunnel origin allowlist. Each entry is a bare " + - "`host:port` (no scheme). DNS hosts implicitly match their " + - "subdomains, so list the trunk you want to allow rather than " + - "individual hostnames: `example.test:8043` covers " + - "`app.example.test:8043`, `oauthtest.example.test:8043`, etc. " + - "Hosts are restricted to the loopback class (localhost, 127.x, " + - "::1, *.test, *.localhost). IP literals match exactly with no " + - "subdomain expansion. The response includes a `canonicalized` " + - "field listing any entries that were rewritten (e.g. legacy " + - "scheme prefix stripped, or a sub-trunk collapsed to its parent)."), - }), -}, async ({ relayUrl, connectionId, allowedOrigins }) => { - // Parse + canonicalize up front so the response can carry back any - // rewrites and the caller learns what was actually accepted. The - // TunnelClient parses these again internally; the duplicate cost is - // negligible and keeps the parse-error UX local to this tool. - let canonicalized = []; - if (allowedOrigins && allowedOrigins.length > 0) { - try { - const parsed = parseOriginPatterns(allowedOrigins); - canonicalized = parsed.flatMap((p) => { - const from = canonicalizedFrom(p); - return from === undefined - ? [] - : [{ input: from, canonical: originPatternString(p) }]; - }); - } - catch (err) { - return { - content: [ - { - type: "text", - text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }, null, 2), - }, - ], - isError: true, - }; - } - } - // Optional env-var overrides for the keepalive timing. Production - // defaults (STALE_CONNECTION_MS=90s, YAMUX_PING_INTERVAL_MS=30s) are - // appropriate for staging/cloud LBs. For local testing of the silent- - // drop detection, set e.g. SUBTEXT_TUNNEL_STALE_MS=2000 and - // SUBTEXT_TUNNEL_PING_MS=200 so freezes resolve in seconds. - const staleMs = Number(process.env.SUBTEXT_TUNNEL_STALE_MS) || undefined; - const pingMs = Number(process.env.SUBTEXT_TUNNEL_PING_MS) || undefined; - let client; - try { - client = new TunnelClient({ - relayUrl, - connectionId, - log, - allowedOrigins, - staleTimeoutMs: staleMs, - yamuxPingIntervalMs: pingMs, - }); - } - catch (err) { - // Bad allowlist entry — surfaced before any connect attempt. - return { - content: [ - { - type: "text", - text: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }, null, 2), - }, - ], - isError: true, - }; - } - // Surface a clear error if the initial handshake fails with a rejection. - let needsLiveTunnel = false; - client.once('need_live_tunnel', () => { - needsLiveTunnel = true; - log(`Tunnel needs a fresh live-tunnel call (resume token rejected)`); - }); - client.connect(); - // Wait briefly for the handshake to complete - const deadline = Date.now() + 5000; - while (client.state !== "ready" && !needsLiveTunnel && Date.now() < deadline) { - await new Promise((r) => setTimeout(r, 100)); - } - if (client.tunnelId) { - const id = client.tunnelId; - clients.set(id, client); - // Capture id now: tunnelId is cleared by #onDisconnect() before the - // reconnect that triggers need_live_tunnel, so reading client.tunnelId - // at event-fire time is always undefined → stale map entry. - client.once('need_live_tunnel', () => clients.delete(id)); - } - if (needsLiveTunnel) { - return { - content: [ - { - type: "text", - text: JSON.stringify({ error: "resume token rejected; call live-tunnel to get a fresh relay URL" }, null, 2), - }, - ], - isError: true, - }; - } - return { - content: [ - { - type: "text", - text: JSON.stringify({ - state: client.state, - tunnelId: client.tunnelId ?? null, - connectionId: client.connectionId ?? null, - traceId: client.traceId ?? null, - relayUrl, - // Present only when at least one entry was rewritten; agents - // should treat this as a soft warning ("the relay accepted X - // but registered it as Y") rather than an error. - ...(canonicalized.length > 0 ? { canonicalized } : {}), - }, null, 2), - }, - ], - }; -}); -server.registerTool("tunnel-disconnect", { - description: "Disconnect a specific tunnel by its tunnelId. If no tunnelId is given, disconnects all tunnels.", - inputSchema: z.object({ - tunnelId: z - .string() - .optional() - .describe("The tunnelId to disconnect (from tunnel-connect response). Omit to disconnect all."), - }), -}, async ({ tunnelId }) => { - if (tunnelId) { - const client = clients.get(tunnelId); - if (!client) { - return { - content: [ - { - type: "text", - text: JSON.stringify({ error: `No tunnel with id ${tunnelId}` }, null, 2), - }, - ], - isError: true, - }; - } - client.disconnect(); - clients.delete(tunnelId); - return { - content: [ - { - type: "text", - text: JSON.stringify({ disconnected: tunnelId }, null, 2), - }, - ], - }; - } - // Disconnect all - const ids = [...clients.keys()]; - for (const client of clients.values()) { - client.disconnect(); - } - clients.clear(); - return { - content: [ - { - type: "text", - text: JSON.stringify({ disconnected: ids }, null, 2), - }, - ], - }; -}); -server.registerTool("tunnel-status", { - description: "Returns the status of all active tunnels", - inputSchema: z.object({}), -}, async () => { - const tunnels = [...clients.entries()].map(([id, client]) => ({ - tunnelId: id, - state: client.state, - traceId: client.traceId ?? null, - })); - return { - content: [ - { - type: "text", - text: JSON.stringify({ tunnels, count: tunnels.length }, null, 2), - }, - ], - }; -}); -const transport = new StdioServerTransport(); -await server.connect(transport); -log("MCP server started"); -const shutdown = () => { - log("Shutting down"); - for (const client of clients.values()) { - client.disconnect(); - } - process.exit(0); -}; -process.on("SIGINT", shutdown); -process.on("SIGTERM", shutdown); -// Last-resort handlers to keep the MCP server alive if something slips -// through. There is no process manager to restart us, so a crash means -// Claude Code loses the tunnel tools entirely. log() above is internally -// guarded so it cannot itself throw and re-enter these handlers. -process.on("unhandledRejection", (reason) => { - log(`Unhandled rejection: ${reason instanceof Error ? reason.stack ?? reason.message : String(reason)}`); -}); -process.on("uncaughtException", (err) => { - log(`Uncaught exception: ${err.stack ?? err.message}`); -}); -// Orphan-spin protection: if our parent process (the MCP host) exits, our -// stdio pipes break and any further write triggers EPIPE. Detect that and -// exit cleanly instead of pegging the CPU. Two complementary detectors: -// -// 1. EPIPE on stderr/stdout — fires the moment a write fails. Catches the -// common case where the parent exits while we're mid-log. -// 2. Periodic PPID check — catches the case where the parent exits cleanly -// and we don't write anything until the next tunnel-tool call. On Linux -// orphaned processes are reparented to PID 1; on macOS to launchd (also -// typically PID 1). If we see PPID === 1, we have no MCP host. -// -// Both paths exit(0) — this is not a crash, it's "our reason to live ended." -process.stderr.on("error", (err) => { - if (err.code === "EPIPE") - process.exit(0); -}); -process.stdout.on("error", (err) => { - if (err.code === "EPIPE") - process.exit(0); -}); -// Default 30s; overridable for tests. unref() so the timer alone doesn't -// keep the event loop alive. -const orphanCheckMs = Number(process.env.SUBTEXT_TUNNEL_ORPHAN_CHECK_MS) || 30_000; -const orphanTimer = setInterval(() => { - if (process.ppid === 1) - process.exit(0); -}, orphanCheckMs); -orphanTimer.unref(); diff --git a/tunnel/build/src/third_party/index.js b/tunnel/build/src/third_party/index.js deleted file mode 100644 index 92f2a6c8..00000000 --- a/tunnel/build/src/third_party/index.js +++ /dev/null @@ -1,38011 +0,0 @@ -import process$2 from 'node:process'; -import require$$0$3 from 'events'; -import require$$1$1 from 'https'; -import require$$2 from 'http'; -import require$$3$1 from 'net'; -import require$$4 from 'tls'; -import require$$1 from 'crypto'; -import require$$0$2 from 'stream'; -import require$$7, { fileURLToPath } from 'url'; -import require$$0 from 'zlib'; -import require$$0$1 from 'buffer'; -import { strictEqual, notStrictEqual } from 'assert'; -import { resolve as resolve$1, dirname, normalize, join, relative, extname, basename } from 'path'; -import { statSync, readdirSync, readFileSync, writeFile } from 'fs'; -import { format as format$2, inspect } from 'util'; -import { createRequire } from 'node:module'; -import { readdirSync as readdirSync$1, readFileSync as readFileSync$1 } from 'node:fs'; - -var util$2; -(function (util) { - util.assertEqual = (_) => { }; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" - ? (obj) => Object.keys(obj) - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) - : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util$2 || (util$2 = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, - }; - }; -})(objectUtil || (objectUtil = {})); -const ZodParsedType = util$2.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const getParsedType$1 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -const ZodIssueCode$1 = util$2.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -let ZodError$1 = class ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util$2.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = Object.create(null); - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError$1.create = (issues) => { - const error = new ZodError$1(issues); - return error; -}; - -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode$1.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode$1.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$2.jsonStringifyReplacer)}`; - break; - case ZodIssueCode$1.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util$2.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode$1.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode$1.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util$2.joinValues(issue.options)}`; - break; - case ZodIssueCode$1.invalid_enum_value: - message = `Invalid enum value. Expected ${util$2.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode$1.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode$1.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode$1.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode$1.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util$2.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodIssueCode$1.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode$1.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode$1.custom: - message = `Invalid input`; - break; - case ZodIssueCode$1.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode$1.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode$1.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util$2.assertNever(issue); - } - return { message }; -}; - -let overrideErrorMap = errorMap; -function getErrorMap$1() { - return overrideErrorMap; -} - -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap$1(); - const issue = makeIssue({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === errorMap ? undefined : errorMap, - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -const INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -const OK = (value) => ({ status: "valid", value }); -const isAborted = (x) => x.status === "aborted"; -const isDirty = (x) => x.status === "dirty"; -const isValid = (x) => x.status === "valid"; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -const handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError$1(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -let ZodType$1 = class ZodType { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType$1(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType$1(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType$1(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType$1(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async, - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType$1(data), - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }; - } - catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true, - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType$1(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode$1.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind$1.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data), - }; - } - optional() { - return ZodOptional$1.create(this, this._def); - } - nullable() { - return ZodNullable$1.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray$1.create(this); - } - promise() { - return ZodPromise$1.create(this, this._def); - } - or(option) { - return ZodUnion$1.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection$1.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind$1.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault$1({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind$1.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind$1.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch$1({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind$1.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly$1.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex$2; -const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT$1(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header - .replace(/-/g, "+") - .replace(/_/g, "/") - .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } - catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -let ZodString$1 = class ZodString extends ZodType$1 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex$2) { - emojiRegex$2 = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex$2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "jwt") { - if (!isValidJWT$1(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode$1.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util$2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode$1.invalid_string, - ...errorUtil.errToObj(message), - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message), - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message), - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message), - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options?.position, - ...errorUtil.errToObj(options?.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message), - }); - } - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString$1.create = (params) => { - return new ZodString$1({ - checks: [], - typeName: ZodFirstPartyTypeKind$1.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); -}; -function floatSafeRemainder$1(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / 10 ** decCount; -} -let ZodNumber$1 = class ZodNumber extends ZodType$1 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.number, - received: ctx.parsedType, - }); - return INVALID; - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util$2.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder$1(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util$2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util$2.isInteger(ch.value))); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber$1.create = (params) => { - return new ZodNumber$1({ - checks: [], - typeName: ZodFirstPartyTypeKind$1.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); -}; -let ZodBigInt$1 = class ZodBigInt extends ZodType$1 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } - catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util$2.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt$1.create = (params) => { - return new ZodBigInt$1({ - checks: [], - typeName: ZodFirstPartyTypeKind$1.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); -}; -let ZodBoolean$1 = class ZodBoolean extends ZodType$1 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean$1.create = (params) => { - return new ZodBoolean$1({ - typeName: ZodFirstPartyTypeKind$1.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); -}; -let ZodDate$1 = class ZodDate extends ZodType$1 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.date, - received: ctx.parsedType, - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_date, - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util$2.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate$1.create = (params) => { - return new ZodDate$1({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind$1.ZodDate, - ...processCreateParams(params), - }); -}; -let ZodSymbol$1 = class ZodSymbol extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol$1.create = (params) => { - return new ZodSymbol$1({ - typeName: ZodFirstPartyTypeKind$1.ZodSymbol, - ...processCreateParams(params), - }); -}; -let ZodUndefined$1 = class ZodUndefined extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined$1.create = (params) => { - return new ZodUndefined$1({ - typeName: ZodFirstPartyTypeKind$1.ZodUndefined, - ...processCreateParams(params), - }); -}; -let ZodNull$1 = class ZodNull extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull$1.create = (params) => { - return new ZodNull$1({ - typeName: ZodFirstPartyTypeKind$1.ZodNull, - ...processCreateParams(params), - }); -}; -let ZodAny$1 = class ZodAny extends ZodType$1 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny$1.create = (params) => { - return new ZodAny$1({ - typeName: ZodFirstPartyTypeKind$1.ZodAny, - ...processCreateParams(params), - }); -}; -let ZodUnknown$1 = class ZodUnknown extends ZodType$1 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown$1.create = (params) => { - return new ZodUnknown$1({ - typeName: ZodFirstPartyTypeKind$1.ZodUnknown, - ...processCreateParams(params), - }); -}; -let ZodNever$1 = class ZodNever extends ZodType$1 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return INVALID; - } -}; -ZodNever$1.create = (params) => { - return new ZodNever$1({ - typeName: ZodFirstPartyTypeKind$1.ZodNever, - ...processCreateParams(params), - }); -}; -let ZodVoid$1 = class ZodVoid extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid$1.create = (params) => { - return new ZodVoid$1({ - typeName: ZodFirstPartyTypeKind$1.ZodVoid, - ...processCreateParams(params), - }); -}; -let ZodArray$1 = class ZodArray extends ZodType$1 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode$1.too_big : ZodIssueCode$1.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return ParseStatus.mergeArray(status, result); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray$1.create = (schema, params) => { - return new ZodArray$1({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind$1.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject$1) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional$1.create(deepPartialify(fieldSchema)); - } - return new ZodObject$1({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray$1) { - return new ZodArray$1({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional$1) { - return ZodOptional$1.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable$1) { - return ZodNullable$1.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple$1) { - return ZodTuple$1.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } -} -let ZodObject$1 = class ZodObject extends ZodType$1 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util$2.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever$1 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever$1) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) - ), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind$1.ZodObject, - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - for (const key of util$2.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - omit(mask) { - const shape = {}; - for (const key of util$2.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util$2.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - required(mask) { - const newShape = {}; - for (const key of util$2.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional$1) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util$2.objectKeys(this.shape)); - } -}; -ZodObject$1.create = (shape, params) => { - return new ZodObject$1({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever$1.create(), - typeName: ZodFirstPartyTypeKind$1.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject$1.strictCreate = (shape, params) => { - return new ZodObject$1({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever$1.create(), - typeName: ZodFirstPartyTypeKind$1.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject$1.lazycreate = (shape, params) => { - return new ZodObject$1({ - shape, - unknownKeys: "strip", - catchall: ZodNever$1.create(), - typeName: ZodFirstPartyTypeKind$1.ZodObject, - ...processCreateParams(params), - }); -}; -let ZodUnion$1 = class ZodUnion extends ZodType$1 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError$1(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_union, - unionErrors, - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); - } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError$1(issues)); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_union, - unionErrors, - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion$1.create = (types, params) => { - return new ZodUnion$1({ - options: types, - typeName: ZodFirstPartyTypeKind$1.ZodUnion, - ...processCreateParams(params), - }); -}; -function mergeValues$1(a, b) { - const aType = getParsedType$1(a); - const bType = getParsedType$1(b); - if (a === b) { - return { valid: true, data: a }; - } - else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util$2.objectKeys(b); - const sharedKeys = util$2.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues$1(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues$1(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } - else { - return { valid: false }; - } -} -let ZodIntersection$1 = class ZodIntersection extends ZodType$1 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues$1(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_intersection_types, - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } - } -}; -ZodIntersection$1.create = (left, right, params) => { - return new ZodIntersection$1({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind$1.ZodIntersection, - ...processCreateParams(params), - }); -}; -let ZodTuple$1 = class ZodTuple extends ZodType$1 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } - else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); - } -}; -ZodTuple$1.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple$1({ - items: schemas, - typeName: ZodFirstPartyTypeKind$1.ZodTuple, - rest: null, - ...processCreateParams(params), - }); -}; -let ZodMap$1 = class ZodMap extends ZodType$1 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap$1.create = (keyType, valueType, params) => { - return new ZodMap$1({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind$1.ZodMap, - ...processCreateParams(params), - }); -}; -let ZodSet$1 = class ZodSet extends ZodType$1 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet$1.create = (valueType, params) => { - return new ZodSet$1({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind$1.ZodSet, - ...processCreateParams(params), - }); -}; -let ZodLazy$1 = class ZodLazy extends ZodType$1 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy$1.create = (getter, params) => { - return new ZodLazy$1({ - getter: getter, - typeName: ZodFirstPartyTypeKind$1.ZodLazy, - ...processCreateParams(params), - }); -}; -let ZodLiteral$1 = class ZodLiteral extends ZodType$1 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode$1.invalid_literal, - expected: this._def.value, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral$1.create = (value, params) => { - return new ZodLiteral$1({ - value: value, - typeName: ZodFirstPartyTypeKind$1.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum$1({ - values, - typeName: ZodFirstPartyTypeKind$1.ZodEnum, - ...processCreateParams(params), - }); -} -let ZodEnum$1 = class ZodEnum extends ZodType$1 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util$2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode$1.invalid_type, - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode$1.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, - }); - } -}; -ZodEnum$1.create = createZodEnum; -class ZodNativeEnum extends ZodType$1 { - _parse(input) { - const nativeEnumValues = util$2.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util$2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util$2.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode$1.invalid_type, - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util$2.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util$2.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode$1.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind$1.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -let ZodPromise$1 = class ZodPromise extends ZodType$1 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } -}; -ZodPromise$1.create = (schema, params) => { - return new ZodPromise$1({ - type: schema, - typeName: ZodFirstPartyTypeKind$1.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType$1 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind$1.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result, - })); - }); - } - } - util$2.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind$1.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind$1.ZodEffects, - ...processCreateParams(params), - }); -}; -let ZodOptional$1 = class ZodOptional extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional$1.create = (type, params) => { - return new ZodOptional$1({ - innerType: type, - typeName: ZodFirstPartyTypeKind$1.ZodOptional, - ...processCreateParams(params), - }); -}; -let ZodNullable$1 = class ZodNullable extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable$1.create = (type, params) => { - return new ZodNullable$1({ - innerType: type, - typeName: ZodFirstPartyTypeKind$1.ZodNullable, - ...processCreateParams(params), - }); -}; -let ZodDefault$1 = class ZodDefault extends ZodType$1 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault$1.create = (type, params) => { - return new ZodDefault$1({ - innerType: type, - typeName: ZodFirstPartyTypeKind$1.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params), - }); -}; -let ZodCatch$1 = class ZodCatch extends ZodType$1 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError$1(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError$1(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch$1.create = (type, params) => { - return new ZodCatch$1({ - innerType: type, - typeName: ZodFirstPartyTypeKind$1.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); -}; -let ZodNaN$1 = class ZodNaN extends ZodType$1 { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode$1.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN$1.create = (params) => { - return new ZodNaN$1({ - typeName: ZodFirstPartyTypeKind$1.ZodNaN, - ...processCreateParams(params), - }); -}; -class ZodBranded extends ZodType$1 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } -} -class ZodPipeline extends ZodType$1 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind$1.ZodPipeline, - }); - } -} -let ZodReadonly$1 = class ZodReadonly extends ZodType$1 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly$1.create = (type, params) => { - return new ZodReadonly$1({ - innerType: type, - typeName: ZodFirstPartyTypeKind$1.ZodReadonly, - ...processCreateParams(params), - }); -}; -var ZodFirstPartyTypeKind$1; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {})); -ZodNever$1.create; -ZodArray$1.create; -const objectType = ZodObject$1.create; -ZodUnion$1.create; -ZodIntersection$1.create; -ZodTuple$1.create; -ZodEnum$1.create; -ZodPromise$1.create; -ZodOptional$1.create; -ZodNullable$1.create; - -const NEVER = Object.freeze({ - status: "aborted", -}); -function $constructor(name, initializer, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: new Set(), - }, - enumerable: false, - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a = inst._zod).deferred ?? (_a.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -const $brand = Symbol("zod_brand"); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -const globalConfig = {}; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached(getter) { - return { - get value() { - { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - }, - }; -} -function nullish$1(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepString = step.toString(); - let stepDecCount = (stepString.split(".")[1] || "").length; - if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { - const match = stepString.match(/\d?e-(\d?)/); - if (match?.[1]) { - stepDecCount = Number.parseInt(match[1]); - } - } - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / 10 ** decCount; -} -const EVALUATING = Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - }); - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const allowsEval = cached(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject$1(o) { - if (isObject(o) === false) - return false; - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - const prot = ctor.prototype; - if (isObject(prot) === false) - return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject$1(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = new Set(["string", "number", "symbol"]); -const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); -} -const NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}; -const BIGINT_FORMAT_RANGES = { - int64: [ BigInt("-9223372036854775808"), BigInt("9223372036854775807")], - uint64: [ BigInt(0), BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject$1(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - const existingShape = schema._zod.def.shape; - for (const key in shape) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject$1(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: [], - }); - return clone(a, def); -} -function partial(Class, schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".partial() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - for (const key in oldShape) { - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function required$2(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key in oldShape) { - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); - return shape; - }, - }); - return clone(schema, def); -} -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -function finalizeIssue(iss, ctx, config) { - const full = { ...iss, path: iss.path ?? [] }; - if (!iss.message) { - const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"; - full.message = message; - } - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -class Class { - constructor(..._args) { } -} - -var util$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - BIGINT_FORMAT_RANGES: BIGINT_FORMAT_RANGES, - Class: Class, - NUMBER_FORMAT_RANGES: NUMBER_FORMAT_RANGES, - aborted: aborted, - allowsEval: allowsEval, - assert: assert, - assertEqual: assertEqual, - assertIs: assertIs, - assertNever: assertNever, - assertNotEqual: assertNotEqual, - assignProp: assignProp, - base64ToUint8Array: base64ToUint8Array, - base64urlToUint8Array: base64urlToUint8Array, - cached: cached, - captureStackTrace: captureStackTrace, - cleanEnum: cleanEnum, - cleanRegex: cleanRegex, - clone: clone, - cloneDef: cloneDef, - createTransparentProxy: createTransparentProxy, - defineLazy: defineLazy, - esc: esc, - escapeRegex: escapeRegex, - extend: extend, - finalizeIssue: finalizeIssue, - floatSafeRemainder: floatSafeRemainder, - getElementAtPath: getElementAtPath, - getEnumValues: getEnumValues, - getLengthableOrigin: getLengthableOrigin, - getParsedType: getParsedType, - getSizableOrigin: getSizableOrigin, - hexToUint8Array: hexToUint8Array, - isObject: isObject, - isPlainObject: isPlainObject$1, - issue: issue, - joinValues: joinValues, - jsonStringifyReplacer: jsonStringifyReplacer, - merge: merge, - mergeDefs: mergeDefs, - normalizeParams: normalizeParams, - nullish: nullish$1, - numKeys: numKeys, - objectClone: objectClone, - omit: omit, - optionalKeys: optionalKeys, - parsedType: parsedType, - partial: partial, - pick: pick, - prefixIssues: prefixIssues, - primitiveTypes: primitiveTypes, - promiseAllObject: promiseAllObject, - propertyKeyTypes: propertyKeyTypes, - randomString: randomString, - required: required$2, - safeExtend: safeExtend, - shallowClone: shallowClone, - slugify: slugify, - stringifyPrimitive: stringifyPrimitive, - uint8ArrayToBase64: uint8ArrayToBase64, - uint8ArrayToBase64url: uint8ArrayToBase64url, - uint8ArrayToHex: uint8ArrayToHex, - unwrapMessage: unwrapMessage -}); - -const initializer$1 = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false, - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false, - }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false, - }); -}; -const $ZodError = $constructor("$ZodError", initializer$1); -const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error }); -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues })); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a, _b; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, issue.path)); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, issue.path); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, issue.path); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - return lines.join("\n"); -} - -const _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; -}; -const parse$1 = _parse($ZodRealError); -const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; -}; -const parseAsync$1 = _parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - } - : { success: true, data: result.value }; -}; -const safeParse$2 = _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync$2 = _safeParseAsync($ZodRealError); -const _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); -}; -const encode$1 = _encode($ZodRealError); -const _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); -}; -const decode$1 = _decode($ZodRealError); -const _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); -}; -const encodeAsync$1 = _encodeAsync($ZodRealError); -const _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); -}; -const decodeAsync$1 = _decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode$1 = _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode$1 = _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync$1 = _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync$1 = _safeDecodeAsync($ZodRealError); - -const cuid$1 = /^[cC][^\s-]{8,}$/; -const cuid2$1 = /^[0-9a-z]+$/; -const ulid$1 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; -const xid$1 = /^[0-9a-vA-V]{20}$/; -const ksuid$1 = /^[A-Za-z0-9]{27}$/; -const nanoid$1 = /^[a-zA-Z0-9_-]{21}$/; -const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -const guid$1 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -const uuid$1 = (version) => { - if (!version) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = uuid$1(4); -const uuid6 = uuid$1(6); -const uuid7 = uuid$1(7); -const email$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = unicodeEmail; -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -function emoji$1() { - return new RegExp(_emoji$1, "u"); -} -const ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; -const mac$1 = (delimiter) => { - const escapedDelim = escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4$1 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -const cidrv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -const base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const base64url$1 = /^[A-Za-z0-9_-]*$/; -const hostname$1 = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; -const e164$1 = /^\+[1-9]\d{6,14}$/; -const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -const date$3 = new RegExp(`^${dateSource}$`); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function time$1(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime$1(args) { - const time = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) - opts.push(""); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const string$2 = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint$2 = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number$2 = /^-?\d+(?:\.\d+)?$/; -const boolean$2 = /^(?:true|false)$/i; -const _null$2 = /^null$/i; -const _undefined$2 = /^undefined$/i; -const lowercase = /^[^A-Z]*$/; -const uppercase = /^[^a-z]*$/; -const hex$1 = /^[0-9a-fA-F]*$/; -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = fixedBase64(22, "=="); -const md5_base64url = fixedBase64url(22); -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = fixedBase64(27, "="); -const sha1_base64url = fixedBase64url(27); -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = fixedBase64(43, "="); -const sha256_base64url = fixedBase64url(43); -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = fixedBase64(64, ""); -const sha384_base64url = fixedBase64url(64); -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = fixedBase64(86, "=="); -const sha512_base64url = fixedBase64url(86); - -var regexes = /*#__PURE__*/Object.freeze({ - __proto__: null, - base64: base64$1, - base64url: base64url$1, - bigint: bigint$2, - boolean: boolean$2, - browserEmail: browserEmail, - cidrv4: cidrv4$1, - cidrv6: cidrv6$1, - cuid: cuid$1, - cuid2: cuid2$1, - date: date$3, - datetime: datetime$1, - domain: domain, - duration: duration$1, - e164: e164$1, - email: email$1, - emoji: emoji$1, - extendedDuration: extendedDuration, - guid: guid$1, - hex: hex$1, - hostname: hostname$1, - html5Email: html5Email, - idnEmail: idnEmail, - integer: integer, - ipv4: ipv4$1, - ipv6: ipv6$1, - ksuid: ksuid$1, - lowercase: lowercase, - mac: mac$1, - md5_base64: md5_base64, - md5_base64url: md5_base64url, - md5_hex: md5_hex, - nanoid: nanoid$1, - null: _null$2, - number: number$2, - rfc5322Email: rfc5322Email, - sha1_base64: sha1_base64, - sha1_base64url: sha1_base64url, - sha1_hex: sha1_hex, - sha256_base64: sha256_base64, - sha256_base64url: sha256_base64url, - sha256_hex: sha256_hex, - sha384_base64: sha384_base64, - sha384_base64url: sha384_base64url, - sha384_hex: sha384_hex, - sha512_base64: sha512_base64, - sha512_base64url: sha512_base64url, - sha512_hex: sha512_hex, - string: string$2, - time: time$1, - ulid: ulid$1, - undefined: _undefined$2, - unicodeEmail: unicodeEmail, - uppercase: uppercase, - uuid: uuid$1, - uuid4: uuid4, - uuid6: uuid6, - uuid7: uuid7, - xid: xid$1 -}); - -const $ZodCheck = $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = - $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = $constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); - const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckMaxSize = $constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish$1(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinSize = $constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish$1(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckSizeEquals = $constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish$1(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMaxLength = $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish$1(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish$1(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish$1(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = $constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}); -const $ZodCheckMimeType = $constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckOverwrite = $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) - this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); - } -} - -const version = { - major: 4, - minor: 3, - patch: 6, -}; - -const $ZodType = $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version; - const checks = [...(inst._zod.def.checks ?? [])]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - defineLazy(inst, "~standard", () => ({ - validate: (value) => { - try { - const r = safeParse$2(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } - catch (_) { - return safeParseAsync$2(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); - } - }, - vendor: "zod", - version: 1, - })); -}); -const $ZodString = $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$2(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid$1(v)); - } - else - def.pattern ?? (def.pattern = uuid$1()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodURL = $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const trimmed = payload.value.trim(); - const url = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - } - if (def.normalize) { - payload.value = url.href; - } - else { - payload.value = trimmed; - } - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji$1()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID = $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime$1(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODate = $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date$3); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time$1(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -const $ZodIPv6 = $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } - catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = $constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = mac$1(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}); -const $ZodCIDRv4 = $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4$1); - $ZodStringFormat.init(inst, def); -}); -const $ZodCIDRv6 = $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6$1); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } - catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -function isValidBase64(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -function isValidBase64URL(data) { - if (!base64url$1.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url$1); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164$1); - $ZodStringFormat.init(inst, def); -}); -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = $constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodNumber = $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number$2; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? "Infinity" - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); -}); -const $ZodBoolean = $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = boolean$2; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = $constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = bigint$2; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodBigIntFormat = $constructor("$ZodBigIntFormat", (inst, def) => { - $ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); -}); -const $ZodSymbol = $constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodUndefined = $constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _undefined$2; - inst._zod.values = new Set([undefined]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodNull = $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null$2; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = $constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodDate = $constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -function handlePropertyResult(result, final, key, input, isOptionalOut) { - if (result.issues.length) { - if (isOptionalOut && !(key in input)) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (result.value === undefined) { - if (key in input) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const isOptionalOut = _catchall.optout === "optional"; - for (const key in input) { - if (keySet.has(key)) - continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut))); - } - else { - handlePropertyResult(r, payload, key, input, isOptionalOut); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -const $ZodObject = $constructor("$ZodObject", (inst, def) => { - $ZodType.init(inst, def); - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - return newSh; - }, - }); - } - const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = new Set()); - for (const v of field.values) - propValues[key].add(v); - } - } - return propValues; - }); - const isObject$1 = isObject; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject$1(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const isOptionalOut = el._zod.optout === "optional"; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut))); - } - else { - handlePropertyResult(r, payload, key, input, isOptionalOut); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = $constructor("$ZodObjectJIT", (inst, def) => { - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached(() => normalizeDef(def)); - const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k = esc(key); - const schema = shape[key]; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(key)};`); - if (isOptionalOut) { - doc.write(` - if (${id}.issues.length) { - if (${k} in input) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject$1 = isObject; - const jit = !globalConfig.jitless; - const allowsEval$1 = allowsEval; - const fastEnabled = jit && allowsEval$1.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject$1(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - }); - return final; -} -const $ZodUnion = $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; - return final; - } - if (successes.length === 0) { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - }); - } - else { - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - }); - } - return final; -} -const $ZodXor = $constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}); -const $ZodDiscriminatedUnion = -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = new Set(); - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - const disc = cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - if (def.unionFallback) { - return _super(payload, ctx); - } - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function mergeValues(a, b) { - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject$1(a) && isPlainObject$1(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - const unrecKeys = new Map(); - let unrecIssue; - for (const iss of left.issues) { - if (iss.code === "unrecognized_keys") { - unrecIssue ?? (unrecIssue = iss); - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).l = true; - } - } - else { - result.issues.push(iss); - } - } - for (const iss of right.issues) { - if (iss.code === "unrecognized_keys") { - for (const k of iss.keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k).r = true; - } - } - else { - result.issues.push(iss); - } - } - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length && unrecIssue) { - result.issues.push({ ...unrecIssue, keys: bothKeys }); - } - if (aborted(result)) - return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = $constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = []; - const proms = []; - const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload.issues.push({ - ...(tooBig - ? { code: "too_big", maximum: items.length, inclusive: true } - : { code: "too_small", minimum: items.length }), - input, - inst, - origin: "array", - }); - return payload; - } - } - let i = -1; - for (const item of items) { - i++; - if (i >= input.length) - if (i >= optStart) - continue; - const result = item._zod.run({ - value: input[i], - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleTupleResult(result, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - if (def.rest) { - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ - value: el, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleTupleResult(result, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodRecord = $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject$1(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values) { - payload.value = {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - }); - } - } - else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - const checkNumericKey = typeof key === "string" && number$2.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - payload.value[key] = input[key]; - } - else { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = $constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }); - } - } - if (valueResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = $constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values - .filter((k) => propertyKeyTypes.has(typeof k)) - .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString())) - .join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } - const values = new Set(def.values); - inst._zod.values = values; - inst._zod.pattern = new RegExp(`^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = $constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodTransform = $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(result, input) { - if (result.issues.length && input === undefined) { - return { issues: [], value: undefined }; - } - return result; -} -const $ZodOptional = $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, payload.value)); - return handleOptionalResult(result, payload.value); - } - if (payload.value === undefined) { - return payload; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = $constructor("$ZodExactOptional", (inst, def) => { - $ZodOptional.init(inst, def); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === undefined) { - payload.value = def.defaultValue; - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = $constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}); -const $ZodCatch = $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }, - input: payload.value, - }); - payload.issues = []; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }, - input: payload.value, - }); - payload.issues = []; - } - return payload; - }; -}); -const $ZodNaN = $constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}); -const $ZodPipe = $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = $constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodReadonly = $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = $constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - if (!part._zod.pattern) { - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || primitiveTypes.has(typeof part)) { - regexParts.push(escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}); -const $ZodFunction = $constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - inst._def = def; - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - return function (...args) { - const parsedArgs = inst._def.input ? parse$1(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse$1(inst._def.output, result); - } - return result; - }; - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync$1(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync$1(inst._def.output, result); - } - return result; - }; - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}); -const $ZodPromise = $constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}); -const $ZodLazy = $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "innerType", () => def.getter()); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - path: [...(inst._zod.def.path ?? [])], - continue: !inst._zod.def.abort, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(issue(_iss)); - } -} - -const error$K = () => { - const Sizable = { - string: { unit: "حرف", verb: "أن يحوي" }, - file: { unit: "بايت", verb: "أن يحوي" }, - array: { unit: "عنصر", verb: "أن يحوي" }, - set: { unit: "عنصر", verb: "أن يحوي" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "مدخل", - email: "بريد إلكتروني", - url: "رابط", - emoji: "إيموجي", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "تاريخ ووقت بمعيار ISO", - date: "تاريخ بمعيار ISO", - time: "وقت بمعيار ISO", - duration: "مدة بمعيار ISO", - ipv4: "عنوان IPv4", - ipv6: "عنوان IPv6", - cidrv4: "مدى عناوين بصيغة IPv4", - cidrv6: "مدى عناوين بصيغة IPv6", - base64: "نَص بترميز base64-encoded", - base64url: "نَص بترميز base64url-encoded", - json_string: "نَص على هيئة JSON", - e164: "رقم هاتف بمعيار E.164", - jwt: "JWT", - template_literal: "مدخل", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `مدخلات غير مقبولة: يفترض إدخال instanceof ${issue.expected}، ولكن تم إدخال ${received}`; - } - return `مدخلات غير مقبولة: يفترض إدخال ${expected}، ولكن تم إدخال ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue.values[0])}`; - return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "عنصر"}`; - return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `نَص غير مقبول: يجب أن يبدأ بـ "${issue.prefix}"`; - if (_issue.format === "ends_with") - return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; - if (_issue.format === "includes") - return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; - if (_issue.format === "regex") - return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} غير مقبول`; - } - case "not_multiple_of": - return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`; - case "unrecognized_keys": - return `معرف${issue.keys.length > 1 ? "ات" : ""} غريب${issue.keys.length > 1 ? "ة" : ""}: ${joinValues(issue.keys, "، ")}`; - case "invalid_key": - return `معرف غير مقبول في ${issue.origin}`; - case "invalid_union": - return "مدخل غير مقبول"; - case "invalid_element": - return `مدخل غير مقبول في ${issue.origin}`; - default: - return "مدخل غير مقبول"; - } - }; -}; -function ar () { - return { - localeError: error$K(), - }; -} - -const error$J = () => { - const Sizable = { - string: { unit: "simvol", verb: "olmalıdır" }, - file: { unit: "bayt", verb: "olmalıdır" }, - array: { unit: "element", verb: "olmalıdır" }, - set: { unit: "element", verb: "olmalıdır" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Yanlış dəyər: gözlənilən instanceof ${issue.expected}, daxil olan ${received}`; - } - return `Yanlış dəyər: gözlənilən ${expected}, daxil olan ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue.values[0])}`; - return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; - return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; - if (_issue.format === "ends_with") - return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; - if (_issue.format === "includes") - return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; - if (_issue.format === "regex") - return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; - return `Yanlış ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Yanlış ədəd: ${issue.divisor} ilə bölünə bilən olmalıdır`; - case "unrecognized_keys": - return `Tanınmayan açar${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} daxilində yanlış açar`; - case "invalid_union": - return "Yanlış dəyər"; - case "invalid_element": - return `${issue.origin} daxilində yanlış dəyər`; - default: - return `Yanlış dəyər`; - } - }; -}; -function az () { - return { - localeError: error$J(), - }; -} - -function getBelarusianPlural(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -const error$I = () => { - const Sizable = { - string: { - unit: { - one: "сімвал", - few: "сімвалы", - many: "сімвалаў", - }, - verb: "мець", - }, - array: { - unit: { - one: "элемент", - few: "элементы", - many: "элементаў", - }, - verb: "мець", - }, - set: { - unit: { - one: "элемент", - few: "элементы", - many: "элементаў", - }, - verb: "мець", - }, - file: { - unit: { - one: "байт", - few: "байты", - many: "байтаў", - }, - verb: "мець", - }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "увод", - email: "email адрас", - url: "URL", - emoji: "эмодзі", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO дата і час", - date: "ISO дата", - time: "ISO час", - duration: "ISO працягласць", - ipv4: "IPv4 адрас", - ipv6: "IPv6 адрас", - cidrv4: "IPv4 дыяпазон", - cidrv6: "IPv6 дыяпазон", - base64: "радок у фармаце base64", - base64url: "радок у фармаце base64url", - json_string: "JSON радок", - e164: "нумар E.164", - jwt: "JWT", - template_literal: "увод", - }; - const TypeDictionary = { - nan: "NaN", - number: "лік", - array: "масіў", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Няправільны ўвод: чакаўся instanceof ${issue.expected}, атрымана ${received}`; - } - return `Няправільны ўвод: чакаўся ${expected}, атрымана ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Няправільны ўвод: чакалася ${stringifyPrimitive(issue.values[0])}`; - return `Няправільны варыянт: чакаўся адзін з ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - const maxValue = Number(issue.maximum); - const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`; - } - return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - const minValue = Number(issue.minimum); - const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`; - } - return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; - if (_issue.format === "regex") - return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; - return `Няправільны ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Няправільны лік: павінен быць кратным ${issue.divisor}`; - case "unrecognized_keys": - return `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Няправільны ключ у ${issue.origin}`; - case "invalid_union": - return "Няправільны ўвод"; - case "invalid_element": - return `Няправільнае значэнне ў ${issue.origin}`; - default: - return `Няправільны ўвод`; - } - }; -}; -function be () { - return { - localeError: error$I(), - }; -} - -const error$H = () => { - const Sizable = { - string: { unit: "символа", verb: "да съдържа" }, - file: { unit: "байта", verb: "да съдържа" }, - array: { unit: "елемента", verb: "да съдържа" }, - set: { unit: "елемента", verb: "да съдържа" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "вход", - email: "имейл адрес", - url: "URL", - emoji: "емоджи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO време", - date: "ISO дата", - time: "ISO време", - duration: "ISO продължителност", - ipv4: "IPv4 адрес", - ipv6: "IPv6 адрес", - cidrv4: "IPv4 диапазон", - cidrv6: "IPv6 диапазон", - base64: "base64-кодиран низ", - base64url: "base64url-кодиран низ", - json_string: "JSON низ", - e164: "E.164 номер", - jwt: "JWT", - template_literal: "вход", - }; - const TypeDictionary = { - nan: "NaN", - number: "число", - array: "масив", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Невалиден вход: очакван instanceof ${issue.expected}, получен ${received}`; - } - return `Невалиден вход: очакван ${expected}, получен ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Невалиден вход: очакван ${stringifyPrimitive(issue.values[0])}`; - return `Невалидна опция: очаквано едно от ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да съдържа ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елемента"}`; - return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да бъде ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Твърде малко: очаква се ${issue.origin} да съдържа ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Твърде малко: очаква се ${issue.origin} да бъде ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Невалиден низ: трябва да започва с "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Невалиден низ: трябва да завършва с "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Невалиден низ: трябва да включва "${_issue.includes}"`; - if (_issue.format === "regex") - return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`; - let invalid_adj = "Невалиден"; - if (_issue.format === "emoji") - invalid_adj = "Невалидно"; - if (_issue.format === "datetime") - invalid_adj = "Невалидно"; - if (_issue.format === "date") - invalid_adj = "Невалидна"; - if (_issue.format === "time") - invalid_adj = "Невалидно"; - if (_issue.format === "duration") - invalid_adj = "Невалидна"; - return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Невалидно число: трябва да бъде кратно на ${issue.divisor}`; - case "unrecognized_keys": - return `Неразпознат${issue.keys.length > 1 ? "и" : ""} ключ${issue.keys.length > 1 ? "ове" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Невалиден ключ в ${issue.origin}`; - case "invalid_union": - return "Невалиден вход"; - case "invalid_element": - return `Невалидна стойност в ${issue.origin}`; - default: - return `Невалиден вход`; - } - }; -}; -function bg () { - return { - localeError: error$H(), - }; -} - -const error$G = () => { - const Sizable = { - string: { unit: "caràcters", verb: "contenir" }, - file: { unit: "bytes", verb: "contenir" }, - array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrada", - email: "adreça electrònica", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "durada ISO", - ipv4: "adreça IPv4", - ipv6: "adreça IPv6", - cidrv4: "rang IPv4", - cidrv6: "rang IPv6", - base64: "cadena codificada en base64", - base64url: "cadena codificada en base64url", - json_string: "cadena JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Tipus invàlid: s'esperava instanceof ${issue.expected}, s'ha rebut ${received}`; - } - return `Tipus invàlid: s'esperava ${expected}, s'ha rebut ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Valor invàlid: s'esperava ${stringifyPrimitive(issue.values[0])}`; - return `Opció invàlida: s'esperava una de ${joinValues(issue.values, " o ")}`; - case "too_big": { - const adj = issue.inclusive ? "com a màxim" : "menys de"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} fos ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? "com a mínim" : "més de"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Format invàlid: ha de començar amb "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Format invàlid: ha d'incloure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; - return `Format invàlid per a ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Número invàlid: ha de ser múltiple de ${issue.divisor}`; - case "unrecognized_keys": - return `Clau${issue.keys.length > 1 ? "s" : ""} no reconeguda${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Clau invàlida a ${issue.origin}`; - case "invalid_union": - return "Entrada invàlida"; - case "invalid_element": - return `Element invàlid a ${issue.origin}`; - default: - return `Entrada invàlida`; - } - }; -}; -function ca () { - return { - localeError: error$G(), - }; -} - -const error$F = () => { - const Sizable = { - string: { unit: "znaků", verb: "mít" }, - file: { unit: "bajtů", verb: "mít" }, - array: { unit: "prvků", verb: "mít" }, - set: { unit: "prvků", verb: "mít" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "regulární výraz", - email: "e-mailová adresa", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "datum a čas ve formátu ISO", - date: "datum ve formátu ISO", - time: "čas ve formátu ISO", - duration: "doba trvání ISO", - ipv4: "IPv4 adresa", - ipv6: "IPv6 adresa", - cidrv4: "rozsah IPv4", - cidrv6: "rozsah IPv6", - base64: "řetězec zakódovaný ve formátu base64", - base64url: "řetězec zakódovaný ve formátu base64url", - json_string: "řetězec ve formátu JSON", - e164: "číslo E.164", - jwt: "JWT", - template_literal: "vstup", - }; - const TypeDictionary = { - nan: "NaN", - number: "číslo", - string: "řetězec", - function: "funkce", - array: "pole", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Neplatný vstup: očekáváno instanceof ${issue.expected}, obdrženo ${received}`; - } - return `Neplatný vstup: očekáváno ${expected}, obdrženo ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Neplatný vstup: očekáváno ${stringifyPrimitive(issue.values[0])}`; - return `Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.maximum.toString()} ${sizing.unit ?? "prvků"}`; - } - return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.minimum.toString()} ${sizing.unit ?? "prvků"}`; - } - return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; - return `Neplatný formát ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Neplatné číslo: musí být násobkem ${issue.divisor}`; - case "unrecognized_keys": - return `Neznámé klíče: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Neplatný klíč v ${issue.origin}`; - case "invalid_union": - return "Neplatný vstup"; - case "invalid_element": - return `Neplatná hodnota v ${issue.origin}`; - default: - return `Neplatný vstup`; - } - }; -}; -function cs () { - return { - localeError: error$F(), - }; -} - -const error$E = () => { - const Sizable = { - string: { unit: "tegn", verb: "havde" }, - file: { unit: "bytes", verb: "havde" }, - array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "e-mailadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkeslæt", - date: "ISO-dato", - time: "ISO-klokkeslæt", - duration: "ISO-varighed", - ipv4: "IPv4-område", - ipv6: "IPv6-område", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodet streng", - base64url: "base64url-kodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - string: "streng", - number: "tal", - boolean: "boolean", - array: "liste", - object: "objekt", - set: "sæt", - file: "fil", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Ugyldigt input: forventede instanceof ${issue.expected}, fik ${received}`; - } - return `Ugyldigt input: forventede ${expected}, fik ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Ugyldig værdi: forventede ${stringifyPrimitive(issue.values[0])}`; - return `Ugyldigt valg: forventede en af følgende ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - const origin = TypeDictionary[issue.origin] ?? issue.origin; - if (sizing) - return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - const origin = TypeDictionary[issue.origin] ?? issue.origin; - if (sizing) { - return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ugyldig streng: skal starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: skal ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: skal indeholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`; - return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ugyldigt tal: skal være deleligt med ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ugyldig nøgle i ${issue.origin}`; - case "invalid_union": - return "Ugyldigt input: matcher ingen af de tilladte typer"; - case "invalid_element": - return `Ugyldig værdi i ${issue.origin}`; - default: - return `Ugyldigt input`; - } - }; -}; -function da () { - return { - localeError: error$E(), - }; -} - -const error$D = () => { - const Sizable = { - string: { unit: "Zeichen", verb: "zu haben" }, - file: { unit: "Bytes", verb: "zu haben" }, - array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "Eingabe", - email: "E-Mail-Adresse", - url: "URL", - emoji: "Emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-Datum und -Uhrzeit", - date: "ISO-Datum", - time: "ISO-Uhrzeit", - duration: "ISO-Dauer", - ipv4: "IPv4-Adresse", - ipv6: "IPv6-Adresse", - cidrv4: "IPv4-Bereich", - cidrv6: "IPv6-Bereich", - base64: "Base64-codierter String", - base64url: "Base64-URL-codierter String", - json_string: "JSON-String", - e164: "E.164-Nummer", - jwt: "JWT", - template_literal: "Eingabe", - }; - const TypeDictionary = { - nan: "NaN", - number: "Zahl", - array: "Array", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Ungültige Eingabe: erwartet instanceof ${issue.expected}, erhalten ${received}`; - } - return `Ungültige Eingabe: erwartet ${expected}, erhalten ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Ungültige Eingabe: erwartet ${stringifyPrimitive(issue.values[0])}`; - return `Ungültige Option: erwartet eine von ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; - return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ist`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`; - } - return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; - if (_issue.format === "ends_with") - return `Ungültiger String: muss mit "${_issue.suffix}" enden`; - if (_issue.format === "includes") - return `Ungültiger String: muss "${_issue.includes}" enthalten`; - if (_issue.format === "regex") - return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; - return `Ungültig: ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ungültiger Schlüssel in ${issue.origin}`; - case "invalid_union": - return "Ungültige Eingabe"; - case "invalid_element": - return `Ungültiger Wert in ${issue.origin}`; - default: - return `Ungültige Eingabe`; - } - }; -}; -function de () { - return { - localeError: error$D(), - }; -} - -const error$C = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - mac: "MAC address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -function en () { - return { - localeError: error$C(), - }; -} - -const error$B = () => { - const Sizable = { - string: { unit: "karaktrojn", verb: "havi" }, - file: { unit: "bajtojn", verb: "havi" }, - array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "enigo", - email: "retadreso", - url: "URL", - emoji: "emoĝio", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datotempo", - date: "ISO-dato", - time: "ISO-tempo", - duration: "ISO-daŭro", - ipv4: "IPv4-adreso", - ipv6: "IPv6-adreso", - cidrv4: "IPv4-rango", - cidrv6: "IPv6-rango", - base64: "64-ume kodita karaktraro", - base64url: "URL-64-ume kodita karaktraro", - json_string: "JSON-karaktraro", - e164: "E.164-nombro", - jwt: "JWT", - template_literal: "enigo", - }; - const TypeDictionary = { - nan: "NaN", - number: "nombro", - array: "tabelo", - null: "senvalora", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Nevalida enigo: atendiĝis instanceof ${issue.expected}, riceviĝis ${received}`; - } - return `Nevalida enigo: atendiĝis ${expected}, riceviĝis ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Nevalida enigo: atendiĝis ${stringifyPrimitive(issue.values[0])}`; - return `Nevalida opcio: atendiĝis unu el ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Tro granda: atendiĝis ke ${issue.origin ?? "valoro"} havu ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementojn"}`; - return `Tro granda: atendiĝis ke ${issue.origin ?? "valoro"} havu ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Tro malgranda: atendiĝis ke ${issue.origin} havu ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Tro malgranda: atendiĝis ke ${issue.origin} estu ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; - return `Nevalida ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Nevalida nombro: devas esti oblo de ${issue.divisor}`; - case "unrecognized_keys": - return `Nekonata${issue.keys.length > 1 ? "j" : ""} ŝlosilo${issue.keys.length > 1 ? "j" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Nevalida ŝlosilo en ${issue.origin}`; - case "invalid_union": - return "Nevalida enigo"; - case "invalid_element": - return `Nevalida valoro en ${issue.origin}`; - default: - return `Nevalida enigo`; - } - }; -}; -function eo () { - return { - localeError: error$B(), - }; -} - -const error$A = () => { - const Sizable = { - string: { unit: "caracteres", verb: "tener" }, - file: { unit: "bytes", verb: "tener" }, - array: { unit: "elementos", verb: "tener" }, - set: { unit: "elementos", verb: "tener" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrada", - email: "dirección de correo electrónico", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "fecha y hora ISO", - date: "fecha ISO", - time: "hora ISO", - duration: "duración ISO", - ipv4: "dirección IPv4", - ipv6: "dirección IPv6", - cidrv4: "rango IPv4", - cidrv6: "rango IPv6", - base64: "cadena codificada en base64", - base64url: "URL codificada en base64", - json_string: "cadena JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada", - }; - const TypeDictionary = { - nan: "NaN", - string: "texto", - number: "número", - boolean: "booleano", - array: "arreglo", - object: "objeto", - set: "conjunto", - file: "archivo", - date: "fecha", - bigint: "número grande", - symbol: "símbolo", - undefined: "indefinido", - null: "nulo", - function: "función", - map: "mapa", - record: "registro", - tuple: "tupla", - enum: "enumeración", - union: "unión", - literal: "literal", - promise: "promesa", - void: "vacío", - never: "nunca", - unknown: "desconocido", - any: "cualquiera", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Entrada inválida: se esperaba instanceof ${issue.expected}, recibido ${received}`; - } - return `Entrada inválida: se esperaba ${expected}, recibido ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Entrada inválida: se esperaba ${stringifyPrimitive(issue.values[0])}`; - return `Opción inválida: se esperaba una de ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - const origin = TypeDictionary[issue.origin] ?? issue.origin; - if (sizing) - return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - const origin = TypeDictionary[issue.origin] ?? issue.origin; - if (sizing) { - return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cadena inválida: debe terminar en "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cadena inválida: debe incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; - return `Inválido ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Número inválido: debe ser múltiplo de ${issue.divisor}`; - case "unrecognized_keys": - return `Llave${issue.keys.length > 1 ? "s" : ""} desconocida${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Llave inválida en ${TypeDictionary[issue.origin] ?? issue.origin}`; - case "invalid_union": - return "Entrada inválida"; - case "invalid_element": - return `Valor inválido en ${TypeDictionary[issue.origin] ?? issue.origin}`; - default: - return `Entrada inválida`; - } - }; -}; -function es () { - return { - localeError: error$A(), - }; -} - -const error$z = () => { - const Sizable = { - string: { unit: "کاراکتر", verb: "داشته باشد" }, - file: { unit: "بایت", verb: "داشته باشد" }, - array: { unit: "آیتم", verb: "داشته باشد" }, - set: { unit: "آیتم", verb: "داشته باشد" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ورودی", - email: "آدرس ایمیل", - url: "URL", - emoji: "ایموجی", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "تاریخ و زمان ایزو", - date: "تاریخ ایزو", - time: "زمان ایزو", - duration: "مدت زمان ایزو", - ipv4: "IPv4 آدرس", - ipv6: "IPv6 آدرس", - cidrv4: "IPv4 دامنه", - cidrv6: "IPv6 دامنه", - base64: "base64-encoded رشته", - base64url: "base64url-encoded رشته", - json_string: "JSON رشته", - e164: "E.164 عدد", - jwt: "JWT", - template_literal: "ورودی", - }; - const TypeDictionary = { - nan: "NaN", - number: "عدد", - array: "آرایه", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `ورودی نامعتبر: می‌بایست instanceof ${issue.expected} می‌بود، ${received} دریافت شد`; - } - return `ورودی نامعتبر: می‌بایست ${expected} می‌بود، ${received} دریافت شد`; - } - case "invalid_value": - if (issue.values.length === 1) { - return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue.values[0])} می‌بود`; - } - return `گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue.values, "|")} می‌بود`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; - } - return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} باشد`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`; - } - return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; - } - if (_issue.format === "ends_with") { - return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; - } - if (_issue.format === "includes") { - return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; - } - if (_issue.format === "regex") { - return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; - } - return `${FormatDictionary[_issue.format] ?? issue.format} نامعتبر`; - } - case "not_multiple_of": - return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`; - case "unrecognized_keys": - return `کلید${issue.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `کلید ناشناس در ${issue.origin}`; - case "invalid_union": - return `ورودی نامعتبر`; - case "invalid_element": - return `مقدار نامعتبر در ${issue.origin}`; - default: - return `ورودی نامعتبر`; - } - }; -}; -function fa () { - return { - localeError: error$z(), - }; -} - -const error$y = () => { - const Sizable = { - string: { unit: "merkkiä", subject: "merkkijonon" }, - file: { unit: "tavua", subject: "tiedoston" }, - array: { unit: "alkiota", subject: "listan" }, - set: { unit: "alkiota", subject: "joukon" }, - number: { unit: "", subject: "luvun" }, - bigint: { unit: "", subject: "suuren kokonaisluvun" }, - int: { unit: "", subject: "kokonaisluvun" }, - date: { unit: "", subject: "päivämäärän" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "säännöllinen lauseke", - email: "sähköpostiosoite", - url: "URL-osoite", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-aikaleima", - date: "ISO-päivämäärä", - time: "ISO-aika", - duration: "ISO-kesto", - ipv4: "IPv4-osoite", - ipv6: "IPv6-osoite", - cidrv4: "IPv4-alue", - cidrv6: "IPv6-alue", - base64: "base64-koodattu merkkijono", - base64url: "base64url-koodattu merkkijono", - json_string: "JSON-merkkijono", - e164: "E.164-luku", - jwt: "JWT", - template_literal: "templaattimerkkijono", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Virheellinen tyyppi: odotettiin instanceof ${issue.expected}, oli ${received}`; - } - return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue.values[0])}`; - return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim(); - } - return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim(); - } - return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; - if (_issue.format === "regex") { - return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; - } - return `Virheellinen ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return "Virheellinen avain tietueessa"; - case "invalid_union": - return "Virheellinen unioni"; - case "invalid_element": - return "Virheellinen arvo joukossa"; - default: - return `Virheellinen syöte`; - } - }; -}; -function fi () { - return { - localeError: error$y(), - }; -} - -const error$x = () => { - const Sizable = { - string: { unit: "caractères", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "éléments", verb: "avoir" }, - set: { unit: "éléments", verb: "avoir" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrée", - email: "adresse e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date et heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "durée ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "chaîne encodée en base64", - base64url: "chaîne encodée en base64url", - json_string: "chaîne JSON", - e164: "numéro E.164", - jwt: "JWT", - template_literal: "entrée", - }; - const TypeDictionary = { - nan: "NaN", - number: "nombre", - array: "tableau", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Entrée invalide : instanceof ${issue.expected} attendu, ${received} reçu`; - } - return `Entrée invalide : ${expected} attendu, ${received} reçu`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Entrée invalide : ${stringifyPrimitive(issue.values[0])} attendu`; - return `Option invalide : une valeur parmi ${joinValues(issue.values, "|")} attendue`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; - return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chaîne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit être un multiple de ${issue.divisor}`; - case "unrecognized_keys": - return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Clé invalide dans ${issue.origin}`; - case "invalid_union": - return "Entrée invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue.origin}`; - default: - return `Entrée invalide`; - } - }; -}; -function fr () { - return { - localeError: error$x(), - }; -} - -const error$w = () => { - const Sizable = { - string: { unit: "caractères", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "éléments", verb: "avoir" }, - set: { unit: "éléments", verb: "avoir" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "entrée", - email: "adresse courriel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date-heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "durée ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "chaîne encodée en base64", - base64url: "chaîne encodée en base64url", - json_string: "chaîne JSON", - e164: "numéro E.164", - jwt: "JWT", - template_literal: "entrée", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Entrée invalide : attendu instanceof ${issue.expected}, reçu ${received}`; - } - return `Entrée invalide : attendu ${expected}, reçu ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Entrée invalide : attendu ${stringifyPrimitive(issue.values[0])}`; - return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "≤" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Trop grand : attendu que ${issue.origin ?? "la valeur"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`; - return `Trop grand : attendu que ${issue.origin ?? "la valeur"} soit ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? "≥" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chaîne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit être un multiple de ${issue.divisor}`; - case "unrecognized_keys": - return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Clé invalide dans ${issue.origin}`; - case "invalid_union": - return "Entrée invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue.origin}`; - default: - return `Entrée invalide`; - } - }; -}; -function frCA () { - return { - localeError: error$w(), - }; -} - -const error$v = () => { - const TypeNames = { - string: { label: "מחרוזת", gender: "f" }, - number: { label: "מספר", gender: "m" }, - boolean: { label: "ערך בוליאני", gender: "m" }, - bigint: { label: "BigInt", gender: "m" }, - date: { label: "תאריך", gender: "m" }, - array: { label: "מערך", gender: "m" }, - object: { label: "אובייקט", gender: "m" }, - null: { label: "ערך ריק (null)", gender: "m" }, - undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" }, - symbol: { label: "סימבול (Symbol)", gender: "m" }, - function: { label: "פונקציה", gender: "f" }, - map: { label: "מפה (Map)", gender: "f" }, - set: { label: "קבוצה (Set)", gender: "f" }, - file: { label: "קובץ", gender: "m" }, - promise: { label: "Promise", gender: "m" }, - NaN: { label: "NaN", gender: "m" }, - unknown: { label: "ערך לא ידוע", gender: "m" }, - value: { label: "ערך", gender: "m" }, - }; - const Sizable = { - string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" }, - file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" }, - array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, - set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, - number: { unit: "", shortLabel: "קטן", longLabel: "גדול" }, - }; - const typeEntry = (t) => (t ? TypeNames[t] : undefined); - const typeLabel = (t) => { - const e = typeEntry(t); - if (e) - return e.label; - return t ?? TypeNames.unknown.label; - }; - const withDefinite = (t) => `ה${typeLabel(t)}`; - const verbFor = (t) => { - const e = typeEntry(t); - const gender = e?.gender ?? "m"; - return gender === "f" ? "צריכה להיות" : "צריך להיות"; - }; - const getSizing = (origin) => { - if (!origin) - return null; - return Sizable[origin] ?? null; - }; - const FormatDictionary = { - regex: { label: "קלט", gender: "m" }, - email: { label: "כתובת אימייל", gender: "f" }, - url: { label: "כתובת רשת", gender: "f" }, - emoji: { label: "אימוג'י", gender: "m" }, - uuid: { label: "UUID", gender: "m" }, - nanoid: { label: "nanoid", gender: "m" }, - guid: { label: "GUID", gender: "m" }, - cuid: { label: "cuid", gender: "m" }, - cuid2: { label: "cuid2", gender: "m" }, - ulid: { label: "ULID", gender: "m" }, - xid: { label: "XID", gender: "m" }, - ksuid: { label: "KSUID", gender: "m" }, - datetime: { label: "תאריך וזמן ISO", gender: "m" }, - date: { label: "תאריך ISO", gender: "m" }, - time: { label: "זמן ISO", gender: "m" }, - duration: { label: "משך זמן ISO", gender: "m" }, - ipv4: { label: "כתובת IPv4", gender: "f" }, - ipv6: { label: "כתובת IPv6", gender: "f" }, - cidrv4: { label: "טווח IPv4", gender: "m" }, - cidrv6: { label: "טווח IPv6", gender: "m" }, - base64: { label: "מחרוזת בבסיס 64", gender: "f" }, - base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" }, - json_string: { label: "מחרוזת JSON", gender: "f" }, - e164: { label: "מספר E.164", gender: "m" }, - jwt: { label: "JWT", gender: "m" }, - ends_with: { label: "קלט", gender: "m" }, - includes: { label: "קלט", gender: "m" }, - lowercase: { label: "קלט", gender: "m" }, - starts_with: { label: "קלט", gender: "m" }, - uppercase: { label: "קלט", gender: "m" }, - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expectedKey = issue.expected; - const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey); - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `קלט לא תקין: צריך להיות instanceof ${issue.expected}, התקבל ${received}`; - } - return `קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`; - } - case "invalid_value": { - if (issue.values.length === 1) { - return `ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue.values[0])}`; - } - const stringified = issue.values.map((v) => stringifyPrimitive(v)); - if (issue.values.length === 2) { - return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`; - } - const lastValue = stringified[stringified.length - 1]; - const restValues = stringified.slice(0, -1).join(", "); - return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`; - } - case "too_big": { - const sizing = getSizing(issue.origin); - const subject = withDefinite(issue.origin ?? "value"); - if (issue.origin === "string") { - return `${sizing?.longLabel ?? "ארוך"} מדי: ${subject} צריכה להכיל ${issue.maximum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או פחות" : "לכל היותר"}`.trim(); - } - if (issue.origin === "number") { - const comparison = issue.inclusive ? `קטן או שווה ל-${issue.maximum}` : `קטן מ-${issue.maximum}`; - return `גדול מדי: ${subject} צריך להיות ${comparison}`; - } - if (issue.origin === "array" || issue.origin === "set") { - const verb = issue.origin === "set" ? "צריכה" : "צריך"; - const comparison = issue.inclusive - ? `${issue.maximum} ${sizing?.unit ?? ""} או פחות` - : `פחות מ-${issue.maximum} ${sizing?.unit ?? ""}`; - return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim(); - } - const adj = issue.inclusive ? "<=" : "<"; - const be = verbFor(issue.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`; - } - return `${sizing?.longLabel ?? "גדול"} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const sizing = getSizing(issue.origin); - const subject = withDefinite(issue.origin ?? "value"); - if (issue.origin === "string") { - return `${sizing?.shortLabel ?? "קצר"} מדי: ${subject} צריכה להכיל ${issue.minimum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או יותר" : "לפחות"}`.trim(); - } - if (issue.origin === "number") { - const comparison = issue.inclusive ? `גדול או שווה ל-${issue.minimum}` : `גדול מ-${issue.minimum}`; - return `קטן מדי: ${subject} צריך להיות ${comparison}`; - } - if (issue.origin === "array" || issue.origin === "set") { - const verb = issue.origin === "set" ? "צריכה" : "צריך"; - if (issue.minimum === 1 && issue.inclusive) { - const singularPhrase = issue.origin === "set" ? "לפחות פריט אחד" : "לפחות פריט אחד"; - return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`; - } - const comparison = issue.inclusive - ? `${issue.minimum} ${sizing?.unit ?? ""} או יותר` - : `יותר מ-${issue.minimum} ${sizing?.unit ?? ""}`; - return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim(); - } - const adj = issue.inclusive ? ">=" : ">"; - const be = verbFor(issue.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `${sizing?.shortLabel ?? "קטן"} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `המחרוזת חייבת להתחיל ב "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `המחרוזת חייבת להסתיים ב "${_issue.suffix}"`; - if (_issue.format === "includes") - return `המחרוזת חייבת לכלול "${_issue.includes}"`; - if (_issue.format === "regex") - return `המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`; - const nounEntry = FormatDictionary[_issue.format]; - const noun = nounEntry?.label ?? _issue.format; - const gender = nounEntry?.gender ?? "m"; - const adjective = gender === "f" ? "תקינה" : "תקין"; - return `${noun} לא ${adjective}`; - } - case "not_multiple_of": - return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`; - case "unrecognized_keys": - return `מפתח${issue.keys.length > 1 ? "ות" : ""} לא מזוה${issue.keys.length > 1 ? "ים" : "ה"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": { - return `שדה לא תקין באובייקט`; - } - case "invalid_union": - return "קלט לא תקין"; - case "invalid_element": { - const place = withDefinite(issue.origin ?? "array"); - return `ערך לא תקין ב${place}`; - } - default: - return `קלט לא תקין`; - } - }; -}; -function he () { - return { - localeError: error$v(), - }; -} - -const error$u = () => { - const Sizable = { - string: { unit: "karakter", verb: "legyen" }, - file: { unit: "byte", verb: "legyen" }, - array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "bemenet", - email: "email cím", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO időbélyeg", - date: "ISO dátum", - time: "ISO idő", - duration: "ISO időintervallum", - ipv4: "IPv4 cím", - ipv6: "IPv6 cím", - cidrv4: "IPv4 tartomány", - cidrv6: "IPv6 tartomány", - base64: "base64-kódolt string", - base64url: "base64url-kódolt string", - json_string: "JSON string", - e164: "E.164 szám", - jwt: "JWT", - template_literal: "bemenet", - }; - const TypeDictionary = { - nan: "NaN", - number: "szám", - array: "tömb", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Érvénytelen bemenet: a várt érték instanceof ${issue.expected}, a kapott érték ${received}`; - } - return `Érvénytelen bemenet: a várt érték ${expected}, a kapott érték ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue.values[0])}`; - return `Érvénytelen opció: valamelyik érték várt ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`; - return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; - if (_issue.format === "ends_with") - return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; - if (_issue.format === "includes") - return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; - if (_issue.format === "regex") - return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; - return `Érvénytelen ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`; - case "unrecognized_keys": - return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Érvénytelen kulcs ${issue.origin}`; - case "invalid_union": - return "Érvénytelen bemenet"; - case "invalid_element": - return `Érvénytelen érték: ${issue.origin}`; - default: - return `Érvénytelen bemenet`; - } - }; -}; -function hu () { - return { - localeError: error$u(), - }; -} - -function getArmenianPlural(count, one, many) { - return Math.abs(count) === 1 ? one : many; -} -function withDefiniteArticle(word) { - if (!word) - return ""; - const vowels = ["ա", "ե", "ը", "ի", "ո", "ու", "օ"]; - const lastChar = word[word.length - 1]; - return word + (vowels.includes(lastChar) ? "ն" : "ը"); -} -const error$t = () => { - const Sizable = { - string: { - unit: { - one: "նշան", - many: "նշաններ", - }, - verb: "ունենալ", - }, - file: { - unit: { - one: "բայթ", - many: "բայթեր", - }, - verb: "ունենալ", - }, - array: { - unit: { - one: "տարր", - many: "տարրեր", - }, - verb: "ունենալ", - }, - set: { - unit: { - one: "տարր", - many: "տարրեր", - }, - verb: "ունենալ", - }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "մուտք", - email: "էլ. հասցե", - url: "URL", - emoji: "էմոջի", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO ամսաթիվ և ժամ", - date: "ISO ամսաթիվ", - time: "ISO ժամ", - duration: "ISO տևողություն", - ipv4: "IPv4 հասցե", - ipv6: "IPv6 հասցե", - cidrv4: "IPv4 միջակայք", - cidrv6: "IPv6 միջակայք", - base64: "base64 ձևաչափով տող", - base64url: "base64url ձևաչափով տող", - json_string: "JSON տող", - e164: "E.164 համար", - jwt: "JWT", - template_literal: "մուտք", - }; - const TypeDictionary = { - nan: "NaN", - number: "թիվ", - array: "զանգված", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Սխալ մուտքագրում․ սպասվում էր instanceof ${issue.expected}, ստացվել է ${received}`; - } - return `Սխալ մուտքագրում․ սպասվում էր ${expected}, ստացվել է ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Սխալ մուտքագրում․ սպասվում էր ${stringifyPrimitive(issue.values[1])}`; - return `Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - const maxValue = Number(issue.maximum); - const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); - return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin ?? "արժեք")} կունենա ${adj}${issue.maximum.toString()} ${unit}`; - } - return `Չափազանց մեծ արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin ?? "արժեք")} լինի ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - const minValue = Number(issue.minimum); - const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); - return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin)} կունենա ${adj}${issue.minimum.toString()} ${unit}`; - } - return `Չափազանց փոքր արժեք․ սպասվում է, որ ${withDefiniteArticle(issue.origin)} լինի ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Սխալ տող․ պետք է սկսվի "${_issue.prefix}"-ով`; - if (_issue.format === "ends_with") - return `Սխալ տող․ պետք է ավարտվի "${_issue.suffix}"-ով`; - if (_issue.format === "includes") - return `Սխալ տող․ պետք է պարունակի "${_issue.includes}"`; - if (_issue.format === "regex") - return `Սխալ տող․ պետք է համապատասխանի ${_issue.pattern} ձևաչափին`; - return `Սխալ ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Սխալ թիվ․ պետք է բազմապատիկ լինի ${issue.divisor}-ի`; - case "unrecognized_keys": - return `Չճանաչված բանալի${issue.keys.length > 1 ? "ներ" : ""}. ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Սխալ բանալի ${withDefiniteArticle(issue.origin)}-ում`; - case "invalid_union": - return "Սխալ մուտքագրում"; - case "invalid_element": - return `Սխալ արժեք ${withDefiniteArticle(issue.origin)}-ում`; - default: - return `Սխալ մուտքագրում`; - } - }; -}; -function hy () { - return { - localeError: error$t(), - }; -} - -const error$s = () => { - const Sizable = { - string: { unit: "karakter", verb: "memiliki" }, - file: { unit: "byte", verb: "memiliki" }, - array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "alamat email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tanggal dan waktu format ISO", - date: "tanggal format ISO", - time: "jam format ISO", - duration: "durasi format ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "rentang alamat IPv4", - cidrv6: "rentang alamat IPv6", - base64: "string dengan enkode base64", - base64url: "string dengan enkode base64url", - json_string: "string JSON", - e164: "angka E.164", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Input tidak valid: diharapkan instanceof ${issue.expected}, diterima ${received}`; - } - return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Input tidak valid: diharapkan ${stringifyPrimitive(issue.values[0])}`; - return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Terlalu besar: diharapkan ${issue.origin ?? "value"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: diharapkan ${issue.origin ?? "value"} menjadi ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak valid: harus menyertakan "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak valid: harus sesuai pola ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} tidak valid`; - } - case "not_multiple_of": - return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali ${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak valid di ${issue.origin}`; - case "invalid_union": - return "Input tidak valid"; - case "invalid_element": - return `Nilai tidak valid di ${issue.origin}`; - default: - return `Input tidak valid`; - } - }; -}; -function id$1 () { - return { - localeError: error$s(), - }; -} - -const error$r = () => { - const Sizable = { - string: { unit: "stafi", verb: "að hafa" }, - file: { unit: "bæti", verb: "að hafa" }, - array: { unit: "hluti", verb: "að hafa" }, - set: { unit: "hluti", verb: "að hafa" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "gildi", - email: "netfang", - url: "vefslóð", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dagsetning og tími", - date: "ISO dagsetning", - time: "ISO tími", - duration: "ISO tímalengd", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded strengur", - base64url: "base64url-encoded strengur", - json_string: "JSON strengur", - e164: "E.164 tölugildi", - jwt: "JWT", - template_literal: "gildi", - }; - const TypeDictionary = { - nan: "NaN", - number: "númer", - array: "fylki", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera instanceof ${issue.expected}`; - } - return `Rangt gildi: Þú slóst inn ${received} þar sem á að vera ${expected}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue.values[0])}`; - return `Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? "hluti"}`; - return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} sé ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Of lítið: gert er ráð fyrir að ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Of lítið: gert er ráð fyrir að ${issue.origin} sé ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Ógildur strengur: verður að byrja á "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Ógildur strengur: verður að enda á "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ógildur strengur: verður að innihalda "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`; - return `Rangt ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Röng tala: verður að vera margfeldi af ${issue.divisor}`; - case "unrecognized_keys": - return `Óþekkt ${issue.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Rangur lykill í ${issue.origin}`; - case "invalid_union": - return "Rangt gildi"; - case "invalid_element": - return `Rangt gildi í ${issue.origin}`; - default: - return `Rangt gildi`; - } - }; -}; -function is () { - return { - localeError: error$r(), - }; -} - -const error$q = () => { - const Sizable = { - string: { unit: "caratteri", verb: "avere" }, - file: { unit: "byte", verb: "avere" }, - array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "indirizzo email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e ora ISO", - date: "data ISO", - time: "ora ISO", - duration: "durata ISO", - ipv4: "indirizzo IPv4", - ipv6: "indirizzo IPv6", - cidrv4: "intervallo IPv4", - cidrv6: "intervallo IPv6", - base64: "stringa codificata in base64", - base64url: "URL codificata in base64", - json_string: "stringa JSON", - e164: "numero E.164", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - number: "numero", - array: "vettore", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Input non valido: atteso instanceof ${issue.expected}, ricevuto ${received}`; - } - return `Input non valido: atteso ${expected}, ricevuto ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Input non valido: atteso ${stringifyPrimitive(issue.values[0])}`; - return `Opzione non valida: atteso uno tra ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`; - return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Stringa non valida: deve terminare con "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Stringa non valida: deve includere "${_issue.includes}"`; - if (_issue.format === "regex") - return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Numero non valido: deve essere un multiplo di ${issue.divisor}`; - case "unrecognized_keys": - return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Chiave non valida in ${issue.origin}`; - case "invalid_union": - return "Input non valido"; - case "invalid_element": - return `Valore non valido in ${issue.origin}`; - default: - return `Input non valido`; - } - }; -}; -function it () { - return { - localeError: error$q(), - }; -} - -const error$p = () => { - const Sizable = { - string: { unit: "文字", verb: "である" }, - file: { unit: "バイト", verb: "である" }, - array: { unit: "要素", verb: "である" }, - set: { unit: "要素", verb: "である" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "入力値", - email: "メールアドレス", - url: "URL", - emoji: "絵文字", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO日時", - date: "ISO日付", - time: "ISO時刻", - duration: "ISO期間", - ipv4: "IPv4アドレス", - ipv6: "IPv6アドレス", - cidrv4: "IPv4範囲", - cidrv6: "IPv6範囲", - base64: "base64エンコード文字列", - base64url: "base64urlエンコード文字列", - json_string: "JSON文字列", - e164: "E.164番号", - jwt: "JWT", - template_literal: "入力値", - }; - const TypeDictionary = { - nan: "NaN", - number: "数値", - array: "配列", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `無効な入力: instanceof ${issue.expected}が期待されましたが、${received}が入力されました`; - } - return `無効な入力: ${expected}が期待されましたが、${received}が入力されました`; - } - case "invalid_value": - if (issue.values.length === 1) - return `無効な入力: ${stringifyPrimitive(issue.values[0])}が期待されました`; - return `無効な選択: ${joinValues(issue.values, "、")}のいずれかである必要があります`; - case "too_big": { - const adj = issue.inclusive ? "以下である" : "より小さい"; - const sizing = getSizing(issue.origin); - if (sizing) - return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; - return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${adj}必要があります`; - } - case "too_small": { - const adj = issue.inclusive ? "以上である" : "より大きい"; - const sizing = getSizing(issue.origin); - if (sizing) - return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${sizing.unit}${adj}必要があります`; - return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${adj}必要があります`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; - if (_issue.format === "ends_with") - return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; - if (_issue.format === "includes") - return `無効な文字列: "${_issue.includes}"を含む必要があります`; - if (_issue.format === "regex") - return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; - return `無効な${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `無効な数値: ${issue.divisor}の倍数である必要があります`; - case "unrecognized_keys": - return `認識されていないキー${issue.keys.length > 1 ? "群" : ""}: ${joinValues(issue.keys, "、")}`; - case "invalid_key": - return `${issue.origin}内の無効なキー`; - case "invalid_union": - return "無効な入力"; - case "invalid_element": - return `${issue.origin}内の無効な値`; - default: - return `無効な入力`; - } - }; -}; -function ja () { - return { - localeError: error$p(), - }; -} - -const error$o = () => { - const Sizable = { - string: { unit: "სიმბოლო", verb: "უნდა შეიცავდეს" }, - file: { unit: "ბაიტი", verb: "უნდა შეიცავდეს" }, - array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, - set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "შეყვანა", - email: "ელ-ფოსტის მისამართი", - url: "URL", - emoji: "ემოჯი", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "თარიღი-დრო", - date: "თარიღი", - time: "დრო", - duration: "ხანგრძლივობა", - ipv4: "IPv4 მისამართი", - ipv6: "IPv6 მისამართი", - cidrv4: "IPv4 დიაპაზონი", - cidrv6: "IPv6 დიაპაზონი", - base64: "base64-კოდირებული სტრინგი", - base64url: "base64url-კოდირებული სტრინგი", - json_string: "JSON სტრინგი", - e164: "E.164 ნომერი", - jwt: "JWT", - template_literal: "შეყვანა", - }; - const TypeDictionary = { - nan: "NaN", - number: "რიცხვი", - string: "სტრინგი", - boolean: "ბულეანი", - function: "ფუნქცია", - array: "მასივი", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `არასწორი შეყვანა: მოსალოდნელი instanceof ${issue.expected}, მიღებული ${received}`; - } - return `არასწორი შეყვანა: მოსალოდნელი ${expected}, მიღებული ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue.values[0])}`; - return `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue.values, "|")}-დან`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? "მნიშვნელობა"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit}`; - return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? "მნიშვნელობა"} იყოს ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} იყოს ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`; - } - if (_issue.format === "ends_with") - return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`; - if (_issue.format === "includes") - return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`; - if (_issue.format === "regex") - return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`; - return `არასწორი ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `არასწორი რიცხვი: უნდა იყოს ${issue.divisor}-ის ჯერადი`; - case "unrecognized_keys": - return `უცნობი გასაღებ${issue.keys.length > 1 ? "ები" : "ი"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `არასწორი გასაღები ${issue.origin}-ში`; - case "invalid_union": - return "არასწორი შეყვანა"; - case "invalid_element": - return `არასწორი მნიშვნელობა ${issue.origin}-ში`; - default: - return `არასწორი შეყვანა`; - } - }; -}; -function ka () { - return { - localeError: error$o(), - }; -} - -const error$n = () => { - const Sizable = { - string: { unit: "តួអក្សរ", verb: "គួរមាន" }, - file: { unit: "បៃ", verb: "គួរមាន" }, - array: { unit: "ធាតុ", verb: "គួរមាន" }, - set: { unit: "ធាតុ", verb: "គួរមាន" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ទិន្នន័យបញ្ចូល", - email: "អាសយដ្ឋានអ៊ីមែល", - url: "URL", - emoji: "សញ្ញាអារម្មណ៍", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", - date: "កាលបរិច្ឆេទ ISO", - time: "ម៉ោង ISO", - duration: "រយៈពេល ISO", - ipv4: "អាសយដ្ឋាន IPv4", - ipv6: "អាសយដ្ឋាន IPv6", - cidrv4: "ដែនអាសយដ្ឋាន IPv4", - cidrv6: "ដែនអាសយដ្ឋាន IPv6", - base64: "ខ្សែអក្សរអ៊ិកូដ base64", - base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", - json_string: "ខ្សែអក្សរ JSON", - e164: "លេខ E.164", - jwt: "JWT", - template_literal: "ទិន្នន័យបញ្ចូល", - }; - const TypeDictionary = { - nan: "NaN", - number: "លេខ", - array: "អារេ (Array)", - null: "គ្មានតម្លៃ (null)", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${issue.expected} ប៉ុន្តែទទួលបាន ${received}`; - } - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${expected} ប៉ុន្តែទទួលបាន ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue.values[0])}`; - return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; - return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; - if (_issue.format === "includes") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; - if (_issue.format === "regex") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; - return `មិនត្រឹមត្រូវ៖ ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`; - case "unrecognized_keys": - return `រកឃើញសោមិនស្គាល់៖ ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; - case "invalid_union": - return `ទិន្នន័យមិនត្រឹមត្រូវ`; - case "invalid_element": - return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; - default: - return `ទិន្នន័យមិនត្រឹមត្រូវ`; - } - }; -}; -function km () { - return { - localeError: error$n(), - }; -} - -function kh () { - return km(); -} - -const error$m = () => { - const Sizable = { - string: { unit: "문자", verb: "to have" }, - file: { unit: "바이트", verb: "to have" }, - array: { unit: "개", verb: "to have" }, - set: { unit: "개", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "입력", - email: "이메일 주소", - url: "URL", - emoji: "이모지", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO 날짜시간", - date: "ISO 날짜", - time: "ISO 시간", - duration: "ISO 기간", - ipv4: "IPv4 주소", - ipv6: "IPv6 주소", - cidrv4: "IPv4 범위", - cidrv6: "IPv6 범위", - base64: "base64 인코딩 문자열", - base64url: "base64url 인코딩 문자열", - json_string: "JSON 문자열", - e164: "E.164 번호", - jwt: "JWT", - template_literal: "입력", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `잘못된 입력: 예상 타입은 instanceof ${issue.expected}, 받은 타입은 ${received}입니다`; - } - return `잘못된 입력: 예상 타입은 ${expected}, 받은 타입은 ${received}입니다`; - } - case "invalid_value": - if (issue.values.length === 1) - return `잘못된 입력: 값은 ${stringifyPrimitive(issue.values[0])} 이어야 합니다`; - return `잘못된 옵션: ${joinValues(issue.values, "또는 ")} 중 하나여야 합니다`; - case "too_big": { - const adj = issue.inclusive ? "이하" : "미만"; - const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; - const sizing = getSizing(issue.origin); - const unit = sizing?.unit ?? "요소"; - if (sizing) - return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`; - return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`; - } - case "too_small": { - const adj = issue.inclusive ? "이상" : "초과"; - const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; - const sizing = getSizing(issue.origin); - const unit = sizing?.unit ?? "요소"; - if (sizing) { - return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`; - } - return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; - } - if (_issue.format === "ends_with") - return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; - if (_issue.format === "includes") - return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; - if (_issue.format === "regex") - return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; - return `잘못된 ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`; - case "unrecognized_keys": - return `인식할 수 없는 키: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `잘못된 키: ${issue.origin}`; - case "invalid_union": - return `잘못된 입력`; - case "invalid_element": - return `잘못된 값: ${issue.origin}`; - default: - return `잘못된 입력`; - } - }; -}; -function ko () { - return { - localeError: error$m(), - }; -} - -const capitalizeFirstCharacter = (text) => { - return text.charAt(0).toUpperCase() + text.slice(1); -}; -function getUnitTypeFromNumber(number) { - const abs = Math.abs(number); - const last = abs % 10; - const last2 = abs % 100; - if ((last2 >= 11 && last2 <= 19) || last === 0) - return "many"; - if (last === 1) - return "one"; - return "few"; -} -const error$l = () => { - const Sizable = { - string: { - unit: { - one: "simbolis", - few: "simboliai", - many: "simbolių", - }, - verb: { - smaller: { - inclusive: "turi būti ne ilgesnė kaip", - notInclusive: "turi būti trumpesnė kaip", - }, - bigger: { - inclusive: "turi būti ne trumpesnė kaip", - notInclusive: "turi būti ilgesnė kaip", - }, - }, - }, - file: { - unit: { - one: "baitas", - few: "baitai", - many: "baitų", - }, - verb: { - smaller: { - inclusive: "turi būti ne didesnis kaip", - notInclusive: "turi būti mažesnis kaip", - }, - bigger: { - inclusive: "turi būti ne mažesnis kaip", - notInclusive: "turi būti didesnis kaip", - }, - }, - }, - array: { - unit: { - one: "elementą", - few: "elementus", - many: "elementų", - }, - verb: { - smaller: { - inclusive: "turi turėti ne daugiau kaip", - notInclusive: "turi turėti mažiau kaip", - }, - bigger: { - inclusive: "turi turėti ne mažiau kaip", - notInclusive: "turi turėti daugiau kaip", - }, - }, - }, - set: { - unit: { - one: "elementą", - few: "elementus", - many: "elementų", - }, - verb: { - smaller: { - inclusive: "turi turėti ne daugiau kaip", - notInclusive: "turi turėti mažiau kaip", - }, - bigger: { - inclusive: "turi turėti ne mažiau kaip", - notInclusive: "turi turėti daugiau kaip", - }, - }, - }, - }; - function getSizing(origin, unitType, inclusive, targetShouldBe) { - const result = Sizable[origin] ?? null; - if (result === null) - return result; - return { - unit: result.unit[unitType], - verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"], - }; - } - const FormatDictionary = { - regex: "įvestis", - email: "el. pašto adresas", - url: "URL", - emoji: "jaustukas", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO data ir laikas", - date: "ISO data", - time: "ISO laikas", - duration: "ISO trukmė", - ipv4: "IPv4 adresas", - ipv6: "IPv6 adresas", - cidrv4: "IPv4 tinklo prefiksas (CIDR)", - cidrv6: "IPv6 tinklo prefiksas (CIDR)", - base64: "base64 užkoduota eilutė", - base64url: "base64url užkoduota eilutė", - json_string: "JSON eilutė", - e164: "E.164 numeris", - jwt: "JWT", - template_literal: "įvestis", - }; - const TypeDictionary = { - nan: "NaN", - number: "skaičius", - bigint: "sveikasis skaičius", - string: "eilutė", - boolean: "loginė reikšmė", - undefined: "neapibrėžta reikšmė", - function: "funkcija", - symbol: "simbolis", - array: "masyvas", - object: "objektas", - null: "nulinė reikšmė", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Gautas tipas ${received}, o tikėtasi - instanceof ${issue.expected}`; - } - return `Gautas tipas ${received}, o tikėtasi - ${expected}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Privalo būti ${stringifyPrimitive(issue.values[0])}`; - return `Privalo būti vienas iš ${joinValues(issue.values, "|")} pasirinkimų`; - case "too_big": { - const origin = TypeDictionary[issue.origin] ?? issue.origin; - const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.maximum)), issue.inclusive ?? false, "smaller"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} ${sizing.verb} ${issue.maximum.toString()} ${sizing.unit ?? "elementų"}`; - const adj = issue.inclusive ? "ne didesnis kaip" : "mažesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi būti ${adj} ${issue.maximum.toString()} ${sizing?.unit}`; - } - case "too_small": { - const origin = TypeDictionary[issue.origin] ?? issue.origin; - const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.minimum)), issue.inclusive ?? false, "bigger"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} ${sizing.verb} ${issue.minimum.toString()} ${sizing.unit ?? "elementų"}`; - const adj = issue.inclusive ? "ne mažesnis kaip" : "didesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi būti ${adj} ${issue.minimum.toString()} ${sizing?.unit}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Eilutė privalo prasidėti "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Eilutė privalo pasibaigti "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Eilutė privalo įtraukti "${_issue.includes}"`; - if (_issue.format === "regex") - return `Eilutė privalo atitikti ${_issue.pattern}`; - return `Neteisingas ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Skaičius privalo būti ${issue.divisor} kartotinis.`; - case "unrecognized_keys": - return `Neatpažint${issue.keys.length > 1 ? "i" : "as"} rakt${issue.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return "Rastas klaidingas raktas"; - case "invalid_union": - return "Klaidinga įvestis"; - case "invalid_element": { - const origin = TypeDictionary[issue.origin] ?? issue.origin; - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi klaidingą įvestį`; - } - default: - return "Klaidinga įvestis"; - } - }; -}; -function lt () { - return { - localeError: error$l(), - }; -} - -const error$k = () => { - const Sizable = { - string: { unit: "знаци", verb: "да имаат" }, - file: { unit: "бајти", verb: "да имаат" }, - array: { unit: "ставки", verb: "да имаат" }, - set: { unit: "ставки", verb: "да имаат" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "внес", - email: "адреса на е-пошта", - url: "URL", - emoji: "емоџи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO датум и време", - date: "ISO датум", - time: "ISO време", - duration: "ISO времетраење", - ipv4: "IPv4 адреса", - ipv6: "IPv6 адреса", - cidrv4: "IPv4 опсег", - cidrv6: "IPv6 опсег", - base64: "base64-енкодирана низа", - base64url: "base64url-енкодирана низа", - json_string: "JSON низа", - e164: "E.164 број", - jwt: "JWT", - template_literal: "внес", - }; - const TypeDictionary = { - nan: "NaN", - number: "број", - array: "низа", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Грешен внес: се очекува instanceof ${issue.expected}, примено ${received}`; - } - return `Грешен внес: се очекува ${expected}, примено ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Грешана опција: се очекува една ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да има ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементи"}`; - return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да биде ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Премногу мал: се очекува ${issue.origin} да има ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Премногу мал: се очекува ${issue.origin} да биде ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неважечка низа: мора да вклучува "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Грешен број: мора да биде делив со ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Грешен клуч во ${issue.origin}`; - case "invalid_union": - return "Грешен внес"; - case "invalid_element": - return `Грешна вредност во ${issue.origin}`; - default: - return `Грешен внес`; - } - }; -}; -function mk () { - return { - localeError: error$k(), - }; -} - -const error$j = () => { - const Sizable = { - string: { unit: "aksara", verb: "mempunyai" }, - file: { unit: "bait", verb: "mempunyai" }, - array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "alamat e-mel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tarikh masa ISO", - date: "tarikh ISO", - time: "masa ISO", - duration: "tempoh ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "julat IPv4", - cidrv6: "julat IPv6", - base64: "string dikodkan base64", - base64url: "string dikodkan base64url", - json_string: "string JSON", - e164: "nombor E.164", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - number: "nombor", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Input tidak sah: dijangka instanceof ${issue.expected}, diterima ${received}`; - } - return `Input tidak sah: dijangka ${expected}, diterima ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Input tidak sah: dijangka ${stringifyPrimitive(issue.values[0])}`; - return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} adalah ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak sah: mesti mengandungi "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} tidak sah`; - } - case "not_multiple_of": - return `Nombor tidak sah: perlu gandaan ${issue.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak sah dalam ${issue.origin}`; - case "invalid_union": - return "Input tidak sah"; - case "invalid_element": - return `Nilai tidak sah dalam ${issue.origin}`; - default: - return `Input tidak sah`; - } - }; -}; -function ms () { - return { - localeError: error$j(), - }; -} - -const error$i = () => { - const Sizable = { - string: { unit: "tekens", verb: "heeft" }, - file: { unit: "bytes", verb: "heeft" }, - array: { unit: "elementen", verb: "heeft" }, - set: { unit: "elementen", verb: "heeft" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "invoer", - email: "emailadres", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum en tijd", - date: "ISO datum", - time: "ISO tijd", - duration: "ISO duur", - ipv4: "IPv4-adres", - ipv6: "IPv6-adres", - cidrv4: "IPv4-bereik", - cidrv6: "IPv6-bereik", - base64: "base64-gecodeerde tekst", - base64url: "base64 URL-gecodeerde tekst", - json_string: "JSON string", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "invoer", - }; - const TypeDictionary = { - nan: "NaN", - number: "getal", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Ongeldige invoer: verwacht instanceof ${issue.expected}, ontving ${received}`; - } - return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue.values[0])}`; - return `Ongeldige optie: verwacht één van ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - const longName = issue.origin === "date" ? "laat" : issue.origin === "string" ? "lang" : "groot"; - if (sizing) - return `Te ${longName}: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`; - return `Te ${longName}: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} is`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - const shortName = issue.origin === "date" ? "vroeg" : issue.origin === "string" ? "kort" : "klein"; - if (sizing) { - return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`; - } - return `Te ${shortName}: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; - } - if (_issue.format === "ends_with") - return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; - if (_issue.format === "includes") - return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; - if (_issue.format === "regex") - return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; - return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`; - case "unrecognized_keys": - return `Onbekende key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ongeldige key in ${issue.origin}`; - case "invalid_union": - return "Ongeldige invoer"; - case "invalid_element": - return `Ongeldige waarde in ${issue.origin}`; - default: - return `Ongeldige invoer`; - } - }; -}; -function nl () { - return { - localeError: error$i(), - }; -} - -const error$h = () => { - const Sizable = { - string: { unit: "tegn", verb: "å ha" }, - file: { unit: "bytes", verb: "å ha" }, - array: { unit: "elementer", verb: "å inneholde" }, - set: { unit: "elementer", verb: "å inneholde" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "e-postadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkeslett", - date: "ISO-dato", - time: "ISO-klokkeslett", - duration: "ISO-varighet", - ipv4: "IPv4-område", - ipv6: "IPv6-område", - cidrv4: "IPv4-spekter", - cidrv6: "IPv6-spekter", - base64: "base64-enkodet streng", - base64url: "base64url-enkodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - number: "tall", - array: "liste", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Ugyldig input: forventet instanceof ${issue.expected}, fikk ${received}`; - } - return `Ugyldig input: forventet ${expected}, fikk ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Ugyldig verdi: forventet ${stringifyPrimitive(issue.values[0])}`; - return `Ugyldig valg: forventet en av ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ugyldig streng: må starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: må ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: må inneholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; - return `Ugyldig ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ugyldig tall: må være et multiplum av ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ugyldig nøkkel i ${issue.origin}`; - case "invalid_union": - return "Ugyldig input"; - case "invalid_element": - return `Ugyldig verdi i ${issue.origin}`; - default: - return `Ugyldig input`; - } - }; -}; -function no () { - return { - localeError: error$h(), - }; -} - -const error$g = () => { - const Sizable = { - string: { unit: "harf", verb: "olmalıdır" }, - file: { unit: "bayt", verb: "olmalıdır" }, - array: { unit: "unsur", verb: "olmalıdır" }, - set: { unit: "unsur", verb: "olmalıdır" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "giren", - email: "epostagâh", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO hengâmı", - date: "ISO tarihi", - time: "ISO zamanı", - duration: "ISO müddeti", - ipv4: "IPv4 nişânı", - ipv6: "IPv6 nişânı", - cidrv4: "IPv4 menzili", - cidrv6: "IPv6 menzili", - base64: "base64-şifreli metin", - base64url: "base64url-şifreli metin", - json_string: "JSON metin", - e164: "E.164 sayısı", - jwt: "JWT", - template_literal: "giren", - }; - const TypeDictionary = { - nan: "NaN", - number: "numara", - array: "saf", - null: "gayb", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Fâsit giren: umulan instanceof ${issue.expected}, alınan ${received}`; - } - return `Fâsit giren: umulan ${expected}, alınan ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Fâsit giren: umulan ${stringifyPrimitive(issue.values[0])}`; - return `Fâsit tercih: mûteberler ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; - return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; - } - return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; - if (_issue.format === "ends_with") - return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; - if (_issue.format === "includes") - return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; - if (_issue.format === "regex") - return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; - return `Fâsit ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`; - case "unrecognized_keys": - return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} için tanınmayan anahtar var.`; - case "invalid_union": - return "Giren tanınamadı."; - case "invalid_element": - return `${issue.origin} için tanınmayan kıymet var.`; - default: - return `Kıymet tanınamadı.`; - } - }; -}; -function ota () { - return { - localeError: error$g(), - }; -} - -const error$f = () => { - const Sizable = { - string: { unit: "توکي", verb: "ولري" }, - file: { unit: "بایټس", verb: "ولري" }, - array: { unit: "توکي", verb: "ولري" }, - set: { unit: "توکي", verb: "ولري" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ورودي", - email: "بریښنالیک", - url: "یو آر ال", - emoji: "ایموجي", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "نیټه او وخت", - date: "نېټه", - time: "وخت", - duration: "موده", - ipv4: "د IPv4 پته", - ipv6: "د IPv6 پته", - cidrv4: "د IPv4 ساحه", - cidrv6: "د IPv6 ساحه", - base64: "base64-encoded متن", - base64url: "base64url-encoded متن", - json_string: "JSON متن", - e164: "د E.164 شمېره", - jwt: "JWT", - template_literal: "ورودي", - }; - const TypeDictionary = { - nan: "NaN", - number: "عدد", - array: "ارې", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `ناسم ورودي: باید instanceof ${issue.expected} وای, مګر ${received} ترلاسه شو`; - } - return `ناسم ورودي: باید ${expected} وای, مګر ${received} ترلاسه شو`; - } - case "invalid_value": - if (issue.values.length === 1) { - return `ناسم ورودي: باید ${stringifyPrimitive(issue.values[0])} وای`; - } - return `ناسم انتخاب: باید یو له ${joinValues(issue.values, "|")} څخه وای`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; - } - return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} وي`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`; - } - return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; - } - if (_issue.format === "ends_with") { - return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; - } - if (_issue.format === "includes") { - return `ناسم متن: باید "${_issue.includes}" ولري`; - } - if (_issue.format === "regex") { - return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; - } - return `${FormatDictionary[_issue.format] ?? issue.format} ناسم دی`; - } - case "not_multiple_of": - return `ناسم عدد: باید د ${issue.divisor} مضرب وي`; - case "unrecognized_keys": - return `ناسم ${issue.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `ناسم کلیډ په ${issue.origin} کې`; - case "invalid_union": - return `ناسمه ورودي`; - case "invalid_element": - return `ناسم عنصر په ${issue.origin} کې`; - default: - return `ناسمه ورودي`; - } - }; -}; -function ps () { - return { - localeError: error$f(), - }; -} - -const error$e = () => { - const Sizable = { - string: { unit: "znaków", verb: "mieć" }, - file: { unit: "bajtów", verb: "mieć" }, - array: { unit: "elementów", verb: "mieć" }, - set: { unit: "elementów", verb: "mieć" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "wyrażenie", - email: "adres email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i godzina w formacie ISO", - date: "data w formacie ISO", - time: "godzina w formacie ISO", - duration: "czas trwania ISO", - ipv4: "adres IPv4", - ipv6: "adres IPv6", - cidrv4: "zakres IPv4", - cidrv6: "zakres IPv6", - base64: "ciąg znaków zakodowany w formacie base64", - base64url: "ciąg znaków zakodowany w formacie base64url", - json_string: "ciąg znaków w formacie JSON", - e164: "liczba E.164", - jwt: "JWT", - template_literal: "wejście", - }; - const TypeDictionary = { - nan: "NaN", - number: "liczba", - array: "tablica", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Nieprawidłowe dane wejściowe: oczekiwano instanceof ${issue.expected}, otrzymano ${received}`; - } - return `Nieprawidłowe dane wejściowe: oczekiwano ${expected}, otrzymano ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue.values[0])}`; - return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`; - } - return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`; - } - return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; - return `Nieprawidłow(y/a/e) ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`; - case "unrecognized_keys": - return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Nieprawidłowy klucz w ${issue.origin}`; - case "invalid_union": - return "Nieprawidłowe dane wejściowe"; - case "invalid_element": - return `Nieprawidłowa wartość w ${issue.origin}`; - default: - return `Nieprawidłowe dane wejściowe`; - } - }; -}; -function pl () { - return { - localeError: error$e(), - }; -} - -const error$d = () => { - const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "padrão", - email: "endereço de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "duração ISO", - ipv4: "endereço IPv4", - ipv6: "endereço IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada", - }; - const TypeDictionary = { - nan: "NaN", - number: "número", - null: "nulo", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Tipo inválido: esperado instanceof ${issue.expected}, recebido ${received}`; - } - return `Tipo inválido: esperado ${expected}, recebido ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Entrada inválida: esperado ${stringifyPrimitive(issue.values[0])}`; - return `Opção inválida: esperada uma das ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Muito grande: esperado que ${issue.origin ?? "valor"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue.origin ?? "valor"} fosse ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Texto inválido: deve começar com "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Texto inválido: deve terminar com "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Texto inválido: deve incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} inválido`; - } - case "not_multiple_of": - return `Número inválido: deve ser múltiplo de ${issue.divisor}`; - case "unrecognized_keys": - return `Chave${issue.keys.length > 1 ? "s" : ""} desconhecida${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Chave inválida em ${issue.origin}`; - case "invalid_union": - return "Entrada inválida"; - case "invalid_element": - return `Valor inválido em ${issue.origin}`; - default: - return `Campo inválido`; - } - }; -}; -function pt () { - return { - localeError: error$d(), - }; -} - -function getRussianPlural(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -const error$c = () => { - const Sizable = { - string: { - unit: { - one: "символ", - few: "символа", - many: "символов", - }, - verb: "иметь", - }, - file: { - unit: { - one: "байт", - few: "байта", - many: "байт", - }, - verb: "иметь", - }, - array: { - unit: { - one: "элемент", - few: "элемента", - many: "элементов", - }, - verb: "иметь", - }, - set: { - unit: { - one: "элемент", - few: "элемента", - many: "элементов", - }, - verb: "иметь", - }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ввод", - email: "email адрес", - url: "URL", - emoji: "эмодзи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO дата и время", - date: "ISO дата", - time: "ISO время", - duration: "ISO длительность", - ipv4: "IPv4 адрес", - ipv6: "IPv6 адрес", - cidrv4: "IPv4 диапазон", - cidrv6: "IPv6 диапазон", - base64: "строка в формате base64", - base64url: "строка в формате base64url", - json_string: "JSON строка", - e164: "номер E.164", - jwt: "JWT", - template_literal: "ввод", - }; - const TypeDictionary = { - nan: "NaN", - number: "число", - array: "массив", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Неверный ввод: ожидалось instanceof ${issue.expected}, получено ${received}`; - } - return `Неверный ввод: ожидалось ${expected}, получено ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Неверный ввод: ожидалось ${stringifyPrimitive(issue.values[0])}`; - return `Неверный вариант: ожидалось одно из ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - const maxValue = Number(issue.maximum); - const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`; - } - return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - const minValue = Number(issue.minimum); - const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`; - } - return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Неверная строка: должна начинаться с "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неверная строка: должна содержать "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; - return `Неверный ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Неверное число: должно быть кратным ${issue.divisor}`; - case "unrecognized_keys": - return `Нераспознанн${issue.keys.length > 1 ? "ые" : "ый"} ключ${issue.keys.length > 1 ? "и" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Неверный ключ в ${issue.origin}`; - case "invalid_union": - return "Неверные входные данные"; - case "invalid_element": - return `Неверное значение в ${issue.origin}`; - default: - return `Неверные входные данные`; - } - }; -}; -function ru () { - return { - localeError: error$c(), - }; -} - -const error$b = () => { - const Sizable = { - string: { unit: "znakov", verb: "imeti" }, - file: { unit: "bajtov", verb: "imeti" }, - array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "vnos", - email: "e-poštni naslov", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum in čas", - date: "ISO datum", - time: "ISO čas", - duration: "ISO trajanje", - ipv4: "IPv4 naslov", - ipv6: "IPv6 naslov", - cidrv4: "obseg IPv4", - cidrv6: "obseg IPv6", - base64: "base64 kodiran niz", - base64url: "base64url kodiran niz", - json_string: "JSON niz", - e164: "E.164 številka", - jwt: "JWT", - template_literal: "vnos", - }; - const TypeDictionary = { - nan: "NaN", - number: "število", - array: "tabela", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Neveljaven vnos: pričakovano instanceof ${issue.expected}, prejeto ${received}`; - } - return `Neveljaven vnos: pričakovano ${expected}, prejeto ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Neveljaven vnos: pričakovano ${stringifyPrimitive(issue.values[0])}`; - return `Neveljavna možnost: pričakovano eno izmed ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementov"}`; - return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Premajhno: pričakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Premajhno: pričakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; - return `Neveljaven ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Neveljavno število: mora biti večkratnik ${issue.divisor}`; - case "unrecognized_keys": - return `Neprepoznan${issue.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Neveljaven ključ v ${issue.origin}`; - case "invalid_union": - return "Neveljaven vnos"; - case "invalid_element": - return `Neveljavna vrednost v ${issue.origin}`; - default: - return "Neveljaven vnos"; - } - }; -}; -function sl () { - return { - localeError: error$b(), - }; -} - -const error$a = () => { - const Sizable = { - string: { unit: "tecken", verb: "att ha" }, - file: { unit: "bytes", verb: "att ha" }, - array: { unit: "objekt", verb: "att innehålla" }, - set: { unit: "objekt", verb: "att innehålla" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "reguljärt uttryck", - email: "e-postadress", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datum och tid", - date: "ISO-datum", - time: "ISO-tid", - duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodad sträng", - base64url: "base64url-kodad sträng", - json_string: "JSON-sträng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "mall-literal", - }; - const TypeDictionary = { - nan: "NaN", - number: "antal", - array: "lista", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Ogiltig inmatning: förväntat instanceof ${issue.expected}, fick ${received}`; - } - return `Ogiltig inmatning: förväntat ${expected}, fick ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Ogiltig inmatning: förväntat ${stringifyPrimitive(issue.values[0])}`; - return `Ogiltigt val: förväntade en av ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; - } - return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; - return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`; - case "invalid_union": - return "Ogiltig input"; - case "invalid_element": - return `Ogiltigt värde i ${issue.origin ?? "värdet"}`; - default: - return `Ogiltig input`; - } - }; -}; -function sv () { - return { - localeError: error$a(), - }; -} - -const error$9 = () => { - const Sizable = { - string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, - file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, - array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, - set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "உள்ளீடு", - email: "மின்னஞ்சல் முகவரி", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO தேதி நேரம்", - date: "ISO தேதி", - time: "ISO நேரம்", - duration: "ISO கால அளவு", - ipv4: "IPv4 முகவரி", - ipv6: "IPv6 முகவரி", - cidrv4: "IPv4 வரம்பு", - cidrv6: "IPv6 வரம்பு", - base64: "base64-encoded சரம்", - base64url: "base64url-encoded சரம்", - json_string: "JSON சரம்", - e164: "E.164 எண்", - jwt: "JWT", - template_literal: "input", - }; - const TypeDictionary = { - nan: "NaN", - number: "எண்", - array: "அணி", - null: "வெறுமை", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${issue.expected}, பெறப்பட்டது ${received}`; - } - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${expected}, பெறப்பட்டது ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue.values[0])}`; - return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue.values, "|")} இல் ஒன்று`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; - } - return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; - } - return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; - if (_issue.format === "ends_with") - return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; - if (_issue.format === "includes") - return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; - if (_issue.format === "regex") - return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; - return `தவறான ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`; - case "unrecognized_keys": - return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? "கள்" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} இல் தவறான விசை`; - case "invalid_union": - return "தவறான உள்ளீடு"; - case "invalid_element": - return `${issue.origin} இல் தவறான மதிப்பு`; - default: - return `தவறான உள்ளீடு`; - } - }; -}; -function ta () { - return { - localeError: error$9(), - }; -} - -const error$8 = () => { - const Sizable = { - string: { unit: "ตัวอักษร", verb: "ควรมี" }, - file: { unit: "ไบต์", verb: "ควรมี" }, - array: { unit: "รายการ", verb: "ควรมี" }, - set: { unit: "รายการ", verb: "ควรมี" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ข้อมูลที่ป้อน", - email: "ที่อยู่อีเมล", - url: "URL", - emoji: "อิโมจิ", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "วันที่เวลาแบบ ISO", - date: "วันที่แบบ ISO", - time: "เวลาแบบ ISO", - duration: "ช่วงเวลาแบบ ISO", - ipv4: "ที่อยู่ IPv4", - ipv6: "ที่อยู่ IPv6", - cidrv4: "ช่วง IP แบบ IPv4", - cidrv6: "ช่วง IP แบบ IPv6", - base64: "ข้อความแบบ Base64", - base64url: "ข้อความแบบ Base64 สำหรับ URL", - json_string: "ข้อความแบบ JSON", - e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", - jwt: "โทเคน JWT", - template_literal: "ข้อมูลที่ป้อน", - }; - const TypeDictionary = { - nan: "NaN", - number: "ตัวเลข", - array: "อาร์เรย์ (Array)", - null: "ไม่มีค่า (null)", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${issue.expected} แต่ได้รับ ${received}`; - } - return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${expected} แต่ได้รับ ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue.values[0])}`; - return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "ไม่เกิน" : "น้อยกว่า"; - const sizing = getSizing(issue.origin); - if (sizing) - return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? "รายการ"}`; - return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? "อย่างน้อย" : "มากกว่า"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; - if (_issue.format === "includes") - return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; - if (_issue.format === "regex") - return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; - return `รูปแบบไม่ถูกต้อง: ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`; - case "unrecognized_keys": - return `พบคีย์ที่ไม่รู้จัก: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `คีย์ไม่ถูกต้องใน ${issue.origin}`; - case "invalid_union": - return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; - case "invalid_element": - return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`; - default: - return `ข้อมูลไม่ถูกต้อง`; - } - }; -}; -function th () { - return { - localeError: error$8(), - }; -} - -const error$7 = () => { - const Sizable = { - string: { unit: "karakter", verb: "olmalı" }, - file: { unit: "bayt", verb: "olmalı" }, - array: { unit: "öğe", verb: "olmalı" }, - set: { unit: "öğe", verb: "olmalı" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "girdi", - email: "e-posta adresi", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO tarih ve saat", - date: "ISO tarih", - time: "ISO saat", - duration: "ISO süre", - ipv4: "IPv4 adresi", - ipv6: "IPv6 adresi", - cidrv4: "IPv4 aralığı", - cidrv6: "IPv6 aralığı", - base64: "base64 ile şifrelenmiş metin", - base64url: "base64url ile şifrelenmiş metin", - json_string: "JSON dizesi", - e164: "E.164 sayısı", - jwt: "JWT", - template_literal: "Şablon dizesi", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Geçersiz değer: beklenen instanceof ${issue.expected}, alınan ${received}`; - } - return `Geçersiz değer: beklenen ${expected}, alınan ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Geçersiz değer: beklenen ${stringifyPrimitive(issue.values[0])}`; - return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "öğe"}`; - return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; - if (_issue.format === "ends_with") - return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; - if (_issue.format === "includes") - return `Geçersiz metin: "${_issue.includes}" içermeli`; - if (_issue.format === "regex") - return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; - return `Geçersiz ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Geçersiz sayı: ${issue.divisor} ile tam bölünebilmeli`; - case "unrecognized_keys": - return `Tanınmayan anahtar${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} içinde geçersiz anahtar`; - case "invalid_union": - return "Geçersiz değer"; - case "invalid_element": - return `${issue.origin} içinde geçersiz değer`; - default: - return `Geçersiz değer`; - } - }; -}; -function tr () { - return { - localeError: error$7(), - }; -} - -const error$6 = () => { - const Sizable = { - string: { unit: "символів", verb: "матиме" }, - file: { unit: "байтів", verb: "матиме" }, - array: { unit: "елементів", verb: "матиме" }, - set: { unit: "елементів", verb: "матиме" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "вхідні дані", - email: "адреса електронної пошти", - url: "URL", - emoji: "емодзі", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "дата та час ISO", - date: "дата ISO", - time: "час ISO", - duration: "тривалість ISO", - ipv4: "адреса IPv4", - ipv6: "адреса IPv6", - cidrv4: "діапазон IPv4", - cidrv6: "діапазон IPv6", - base64: "рядок у кодуванні base64", - base64url: "рядок у кодуванні base64url", - json_string: "рядок JSON", - e164: "номер E.164", - jwt: "JWT", - template_literal: "вхідні дані", - }; - const TypeDictionary = { - nan: "NaN", - number: "число", - array: "масив", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Неправильні вхідні дані: очікується instanceof ${issue.expected}, отримано ${received}`; - } - return `Неправильні вхідні дані: очікується ${expected}, отримано ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Неправильні вхідні дані: очікується ${stringifyPrimitive(issue.values[0])}`; - return `Неправильна опція: очікується одне з ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Занадто велике: очікується, що ${issue.origin ?? "значення"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементів"}`; - return `Занадто велике: очікується, що ${issue.origin ?? "значення"} буде ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Занадто мале: очікується, що ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Занадто мале: очікується, що ${issue.origin} буде ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неправильний рядок: повинен містити "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; - return `Неправильний ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Неправильне число: повинно бути кратним ${issue.divisor}`; - case "unrecognized_keys": - return `Нерозпізнаний ключ${issue.keys.length > 1 ? "і" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Неправильний ключ у ${issue.origin}`; - case "invalid_union": - return "Неправильні вхідні дані"; - case "invalid_element": - return `Неправильне значення у ${issue.origin}`; - default: - return `Неправильні вхідні дані`; - } - }; -}; -function uk () { - return { - localeError: error$6(), - }; -} - -function ua () { - return uk(); -} - -const error$5 = () => { - const Sizable = { - string: { unit: "حروف", verb: "ہونا" }, - file: { unit: "بائٹس", verb: "ہونا" }, - array: { unit: "آئٹمز", verb: "ہونا" }, - set: { unit: "آئٹمز", verb: "ہونا" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ان پٹ", - email: "ای میل ایڈریس", - url: "یو آر ایل", - emoji: "ایموجی", - uuid: "یو یو آئی ڈی", - uuidv4: "یو یو آئی ڈی وی 4", - uuidv6: "یو یو آئی ڈی وی 6", - nanoid: "نینو آئی ڈی", - guid: "جی یو آئی ڈی", - cuid: "سی یو آئی ڈی", - cuid2: "سی یو آئی ڈی 2", - ulid: "یو ایل آئی ڈی", - xid: "ایکس آئی ڈی", - ksuid: "کے ایس یو آئی ڈی", - datetime: "آئی ایس او ڈیٹ ٹائم", - date: "آئی ایس او تاریخ", - time: "آئی ایس او وقت", - duration: "آئی ایس او مدت", - ipv4: "آئی پی وی 4 ایڈریس", - ipv6: "آئی پی وی 6 ایڈریس", - cidrv4: "آئی پی وی 4 رینج", - cidrv6: "آئی پی وی 6 رینج", - base64: "بیس 64 ان کوڈڈ سٹرنگ", - base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", - json_string: "جے ایس او این سٹرنگ", - e164: "ای 164 نمبر", - jwt: "جے ڈبلیو ٹی", - template_literal: "ان پٹ", - }; - const TypeDictionary = { - nan: "NaN", - number: "نمبر", - array: "آرے", - null: "نل", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `غلط ان پٹ: instanceof ${issue.expected} متوقع تھا، ${received} موصول ہوا`; - } - return `غلط ان پٹ: ${expected} متوقع تھا، ${received} موصول ہوا`; - } - case "invalid_value": - if (issue.values.length === 1) - return `غلط ان پٹ: ${stringifyPrimitive(issue.values[0])} متوقع تھا`; - return `غلط آپشن: ${joinValues(issue.values, "|")} میں سے ایک متوقع تھا`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; - return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; - } - return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; - } - if (_issue.format === "ends_with") - return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; - if (_issue.format === "includes") - return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; - if (_issue.format === "regex") - return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; - return `غلط ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`; - case "unrecognized_keys": - return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${joinValues(issue.keys, "، ")}`; - case "invalid_key": - return `${issue.origin} میں غلط کی`; - case "invalid_union": - return "غلط ان پٹ"; - case "invalid_element": - return `${issue.origin} میں غلط ویلیو`; - default: - return `غلط ان پٹ`; - } - }; -}; -function ur () { - return { - localeError: error$5(), - }; -} - -const error$4 = () => { - const Sizable = { - string: { unit: "belgi", verb: "bo‘lishi kerak" }, - file: { unit: "bayt", verb: "bo‘lishi kerak" }, - array: { unit: "element", verb: "bo‘lishi kerak" }, - set: { unit: "element", verb: "bo‘lishi kerak" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "kirish", - email: "elektron pochta manzili", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO sana va vaqti", - date: "ISO sana", - time: "ISO vaqt", - duration: "ISO davomiylik", - ipv4: "IPv4 manzil", - ipv6: "IPv6 manzil", - mac: "MAC manzil", - cidrv4: "IPv4 diapazon", - cidrv6: "IPv6 diapazon", - base64: "base64 kodlangan satr", - base64url: "base64url kodlangan satr", - json_string: "JSON satr", - e164: "E.164 raqam", - jwt: "JWT", - template_literal: "kirish", - }; - const TypeDictionary = { - nan: "NaN", - number: "raqam", - array: "massiv", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Noto‘g‘ri kirish: kutilgan instanceof ${issue.expected}, qabul qilingan ${received}`; - } - return `Noto‘g‘ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Noto‘g‘ri kirish: kutilgan ${stringifyPrimitive(issue.values[0])}`; - return `Noto‘g‘ri variant: quyidagilardan biri kutilgan ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Juda katta: kutilgan ${issue.origin ?? "qiymat"} ${adj}${issue.maximum.toString()} ${sizing.unit} ${sizing.verb}`; - return `Juda katta: kutilgan ${issue.origin ?? "qiymat"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ${sizing.verb}`; - } - return `Juda kichik: kutilgan ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Noto‘g‘ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; - if (_issue.format === "ends_with") - return `Noto‘g‘ri satr: "${_issue.suffix}" bilan tugashi kerak`; - if (_issue.format === "includes") - return `Noto‘g‘ri satr: "${_issue.includes}" ni o‘z ichiga olishi kerak`; - if (_issue.format === "regex") - return `Noto‘g‘ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; - return `Noto‘g‘ri ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Noto‘g‘ri raqam: ${issue.divisor} ning karralisi bo‘lishi kerak`; - case "unrecognized_keys": - return `Noma’lum kalit${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} dagi kalit noto‘g‘ri`; - case "invalid_union": - return "Noto‘g‘ri kirish"; - case "invalid_element": - return `${issue.origin} da noto‘g‘ri qiymat`; - default: - return `Noto‘g‘ri kirish`; - } - }; -}; -function uz () { - return { - localeError: error$4(), - }; -} - -const error$3 = () => { - const Sizable = { - string: { unit: "ký tự", verb: "có" }, - file: { unit: "byte", verb: "có" }, - array: { unit: "phần tử", verb: "có" }, - set: { unit: "phần tử", verb: "có" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "đầu vào", - email: "địa chỉ email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ngày giờ ISO", - date: "ngày ISO", - time: "giờ ISO", - duration: "khoảng thời gian ISO", - ipv4: "địa chỉ IPv4", - ipv6: "địa chỉ IPv6", - cidrv4: "dải IPv4", - cidrv6: "dải IPv6", - base64: "chuỗi mã hóa base64", - base64url: "chuỗi mã hóa base64url", - json_string: "chuỗi JSON", - e164: "số E.164", - jwt: "JWT", - template_literal: "đầu vào", - }; - const TypeDictionary = { - nan: "NaN", - number: "số", - array: "mảng", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Đầu vào không hợp lệ: mong đợi instanceof ${issue.expected}, nhận được ${received}`; - } - return `Đầu vào không hợp lệ: mong đợi ${expected}, nhận được ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue.values[0])}`; - return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "phần tử"}`; - return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; - return `${FormatDictionary[_issue.format] ?? issue.format} không hợp lệ`; - } - case "not_multiple_of": - return `Số không hợp lệ: phải là bội số của ${issue.divisor}`; - case "unrecognized_keys": - return `Khóa không được nhận dạng: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Khóa không hợp lệ trong ${issue.origin}`; - case "invalid_union": - return "Đầu vào không hợp lệ"; - case "invalid_element": - return `Giá trị không hợp lệ trong ${issue.origin}`; - default: - return `Đầu vào không hợp lệ`; - } - }; -}; -function vi () { - return { - localeError: error$3(), - }; -} - -const error$2 = () => { - const Sizable = { - string: { unit: "字符", verb: "包含" }, - file: { unit: "字节", verb: "包含" }, - array: { unit: "项", verb: "包含" }, - set: { unit: "项", verb: "包含" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "输入", - email: "电子邮件", - url: "URL", - emoji: "表情符号", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO日期时间", - date: "ISO日期", - time: "ISO时间", - duration: "ISO时长", - ipv4: "IPv4地址", - ipv6: "IPv6地址", - cidrv4: "IPv4网段", - cidrv6: "IPv6网段", - base64: "base64编码字符串", - base64url: "base64url编码字符串", - json_string: "JSON字符串", - e164: "E.164号码", - jwt: "JWT", - template_literal: "输入", - }; - const TypeDictionary = { - nan: "NaN", - number: "数字", - array: "数组", - null: "空值(null)", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `无效输入:期望 instanceof ${issue.expected},实际接收 ${received}`; - } - return `无效输入:期望 ${expected},实际接收 ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `无效输入:期望 ${stringifyPrimitive(issue.values[0])}`; - return `无效选项:期望以下之一 ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "个元素"}`; - return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `无效字符串:必须以 "${_issue.prefix}" 开头`; - if (_issue.format === "ends_with") - return `无效字符串:必须以 "${_issue.suffix}" 结尾`; - if (_issue.format === "includes") - return `无效字符串:必须包含 "${_issue.includes}"`; - if (_issue.format === "regex") - return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; - return `无效${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `无效数字:必须是 ${issue.divisor} 的倍数`; - case "unrecognized_keys": - return `出现未知的键(key): ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} 中的键(key)无效`; - case "invalid_union": - return "无效输入"; - case "invalid_element": - return `${issue.origin} 中包含无效值(value)`; - default: - return `无效输入`; - } - }; -}; -function zhCN () { - return { - localeError: error$2(), - }; -} - -const error$1 = () => { - const Sizable = { - string: { unit: "字元", verb: "擁有" }, - file: { unit: "位元組", verb: "擁有" }, - array: { unit: "項目", verb: "擁有" }, - set: { unit: "項目", verb: "擁有" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "輸入", - email: "郵件地址", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO 日期時間", - date: "ISO 日期", - time: "ISO 時間", - duration: "ISO 期間", - ipv4: "IPv4 位址", - ipv6: "IPv6 位址", - cidrv4: "IPv4 範圍", - cidrv6: "IPv6 範圍", - base64: "base64 編碼字串", - base64url: "base64url 編碼字串", - json_string: "JSON 字串", - e164: "E.164 數值", - jwt: "JWT", - template_literal: "輸入", - }; - const TypeDictionary = { - nan: "NaN", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `無效的輸入值:預期為 instanceof ${issue.expected},但收到 ${received}`; - } - return `無效的輸入值:預期為 ${expected},但收到 ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `無效的輸入值:預期為 ${stringifyPrimitive(issue.values[0])}`; - return `無效的選項:預期為以下其中之一 ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()} ${sizing.unit ?? "個元素"}`; - return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `無效的字串:必須以 "${_issue.prefix}" 開頭`; - } - if (_issue.format === "ends_with") - return `無效的字串:必須以 "${_issue.suffix}" 結尾`; - if (_issue.format === "includes") - return `無效的字串:必須包含 "${_issue.includes}"`; - if (_issue.format === "regex") - return `無效的字串:必須符合格式 ${_issue.pattern}`; - return `無效的 ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `無效的數字:必須為 ${issue.divisor} 的倍數`; - case "unrecognized_keys": - return `無法識別的鍵值${issue.keys.length > 1 ? "們" : ""}:${joinValues(issue.keys, "、")}`; - case "invalid_key": - return `${issue.origin} 中有無效的鍵值`; - case "invalid_union": - return "無效的輸入值"; - case "invalid_element": - return `${issue.origin} 中有無效的值`; - default: - return `無效的輸入值`; - } - }; -}; -function zhTW () { - return { - localeError: error$1(), - }; -} - -const error = () => { - const Sizable = { - string: { unit: "àmi", verb: "ní" }, - file: { unit: "bytes", verb: "ní" }, - array: { unit: "nkan", verb: "ní" }, - set: { unit: "nkan", verb: "ní" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "ẹ̀rọ ìbáwọlé", - email: "àdírẹ́sì ìmẹ́lì", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "àkókò ISO", - date: "ọjọ́ ISO", - time: "àkókò ISO", - duration: "àkókò tó pé ISO", - ipv4: "àdírẹ́sì IPv4", - ipv6: "àdírẹ́sì IPv6", - cidrv4: "àgbègbè IPv4", - cidrv6: "àgbègbè IPv6", - base64: "ọ̀rọ̀ tí a kọ́ ní base64", - base64url: "ọ̀rọ̀ base64url", - json_string: "ọ̀rọ̀ JSON", - e164: "nọ́mbà E.164", - jwt: "JWT", - template_literal: "ẹ̀rọ ìbáwọlé", - }; - const TypeDictionary = { - nan: "NaN", - number: "nọ́mbà", - array: "akopọ", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = TypeDictionary[issue.expected] ?? issue.expected; - const receivedType = parsedType(issue.input); - const received = TypeDictionary[receivedType] ?? receivedType; - if (/^[A-Z]/.test(issue.expected)) { - return `Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${issue.expected}, àmọ̀ a rí ${received}`; - } - return `Ìbáwọlé aṣìṣe: a ní láti fi ${expected}, àmọ̀ a rí ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue.values[0])}`; - return `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Tó pọ̀ jù: a ní láti jẹ́ pé ${issue.origin ?? "iye"} ${sizing.verb} ${adj}${issue.maximum} ${sizing.unit}`; - return `Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue.maximum}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Kéré ju: a ní láti jẹ́ pé ${issue.origin} ${sizing.verb} ${adj}${issue.minimum} ${sizing.unit}`; - return `Kéré ju: a ní láti jẹ́ ${adj}${issue.minimum}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`; - return `Aṣìṣe: ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue.divisor}`; - case "unrecognized_keys": - return `Bọtìnì àìmọ̀: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Bọtìnì aṣìṣe nínú ${issue.origin}`; - case "invalid_union": - return "Ìbáwọlé aṣìṣe"; - case "invalid_element": - return `Iye aṣìṣe nínú ${issue.origin}`; - default: - return "Ìbáwọlé aṣìṣe"; - } - }; -}; -function yo () { - return { - localeError: error(), - }; -} - -var index$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - ar: ar, - az: az, - be: be, - bg: bg, - ca: ca, - cs: cs, - da: da, - de: de, - en: en, - eo: eo, - es: es, - fa: fa, - fi: fi, - fr: fr, - frCA: frCA, - he: he, - hu: hu, - hy: hy, - id: id$1, - is: is, - it: it, - ja: ja, - ka: ka, - kh: kh, - km: km, - ko: ko, - lt: lt, - mk: mk, - ms: ms, - nl: nl, - no: no, - ota: ota, - pl: pl, - ps: ps, - pt: pt, - ru: ru, - sl: sl, - sv: sv, - ta: ta, - th: th, - tr: tr, - ua: ua, - uk: uk, - ur: ur, - uz: uz, - vi: vi, - yo: yo, - zhCN: zhCN, - zhTW: zhTW -}); - -var _a$1; -const $output = Symbol("ZodOutput"); -const $input = Symbol("ZodInput"); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -function registry() { - return new $ZodRegistry(); -} -(_a$1 = globalThis).__zod_globalRegistry ?? (_a$1.__zod_globalRegistry = registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...normalizeParams(params), - }); -} -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = { - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -}; -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...normalizeParams(params), - }); -} -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...normalizeParams(params), - }); -} -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...normalizeParams(params), - }); -} -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...normalizeParams(params), - }); -} -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...normalizeParams(params), - }); -} -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...normalizeParams(params), - }); -} -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...normalizeParams(params), - }); -} -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...normalizeParams(params), - }); -} -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...normalizeParams(params), - }); -} -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...normalizeParams(params), - }); -} -function _undefined$1(Class, params) { - return new Class({ - type: "undefined", - ...normalizeParams(params), - }); -} -function _null$1(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -function _any(Class) { - return new Class({ - type: "any", - }); -} -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -function _void$1(Class, params) { - return new Class({ - type: "void", - ...normalizeParams(params), - }); -} -function _date(Class, params) { - return new Class({ - type: "date", - ...normalizeParams(params), - }); -} -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...normalizeParams(params), - }); -} -function _nan(Class, params) { - return new Class({ - type: "nan", - ...normalizeParams(params), - }); -} -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} -function _positive(params) { - return _gt(0, params); -} -function _negative(params) { - return _lt(0, params); -} -function _nonpositive(params) { - return _lte(0, params); -} -function _nonnegative(params) { - return _gte(0, params); -} -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -function _maxSize(maximum, params) { - return new $ZodCheckMaxSize({ - check: "max_size", - ...normalizeParams(params), - maximum, - }); -} -function _minSize(minimum, params) { - return new $ZodCheckMinSize({ - check: "min_size", - ...normalizeParams(params), - minimum, - }); -} -function _size(size, params) { - return new $ZodCheckSizeEquals({ - check: "size_equals", - ...normalizeParams(params), - size, - }); -} -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -function _property(property, schema, params) { - return new $ZodCheckProperty({ - check: "property", - property, - schema, - ...normalizeParams(params), - }); -} -function _mime(types, params) { - return new $ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...normalizeParams(params), - }); -} -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -function _trim() { - return _overwrite((input) => input.trim()); -} -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -function _slugify() { - return _overwrite((input) => slugify(input)); -} -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - ...normalizeParams(params), - }); -} -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...normalizeParams(params), - }); -} -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options, - discriminator, - ...normalizeParams(params), - }); -} -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...normalizeParams(params), - }); -} -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...normalizeParams(params), - }); -} -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...normalizeParams(params), - }); -} -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...normalizeParams(params), - }); -} -function _enum$2(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new Class({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -function _file(Class, params) { - return new Class({ - type: "file", - ...normalizeParams(params), - }); -} -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -function _default$1(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...normalizeParams(params), - }); -} -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -function _catch$1(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), - }); -} -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...normalizeParams(params), - }); -} -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -function _custom(Class, fn, _params) { - const norm = normalizeParams(_params); - norm.abort ?? (norm.abort = true); - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -function _superRefine(fn) { - const ch = _check((payload) => { - payload.addIssue = (issue$1) => { - if (typeof issue$1 === "string") { - payload.issues.push(issue(issue$1, payload.value, ch._zod.def)); - } - else { - const _issue = issue$1; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(issue(_issue)); - } - }; - return fn(payload.value, payload); - }); - return ch; -} -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function describe$1(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; - return ch; -} -function meta$1(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; - return ch; -} -function _stringbool(Classes, _params) { - const params = normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? $ZodCodec; - const _Boolean = Classes.Boolean ?? $ZodBoolean; - const _String = Classes.String ?? $ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - return codec; -} -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = normalizeParams(_params); - const def = { - ...normalizeParams(_params), - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - -function initializeContext(params) { - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? undefined, - }; -} -function process$1(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - if (!result.ref) - result.ref = parent; - process$1(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - const meta = ctx.metadataRegistry.get(schema); - if (meta) - Object.assign(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - delete result.schema.examples; - delete result.schema.default; - } - if (ctx.io === "input" && result.schema._prefault) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - const _result = ctx.seen.get(schema); - return _result.schema; -} -function extractDefs(ctx, schema -) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - const makeURI = (entry) => { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) - seen.defId = defId; - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (schema === entry[0]) { - extractToDef(entry); - continue; - } - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - continue; - } - } - } -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - Object.assign(schema, refSchema); - } - Object.assign(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") ; - else ; - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - Object.assign(result, root.def ?? root.schema); - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } - } - if (ctx.external) ; - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - process$1(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - process$1(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", -}; -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; - if (format === "time") { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json.pattern = regexes[0].source; - else if (regexes.length > 1) { - json.allOf = [ - ...regexes.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, _params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - if (typeof exclusiveMinimum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - if (typeof minimum === "number") { - json.minimum = minimum; - if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { - if (exclusiveMinimum >= minimum) - delete json.minimum; - else - delete json.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - if (typeof maximum === "number") { - json.maximum = maximum; - if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { - if (exclusiveMaximum <= maximum) - delete json.maximum; - else - delete json.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json.multipleOf = multipleOf; -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } -}; -const symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } -}; -const voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { -}; -const dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, _params) => { - const def = schema._zod.def; - const vals = []; - for (const val of def.values) { - if (val === undefined) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } - } - else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } - else { - vals.push(Number(val)); - } - } - else { - vals.push(val); - } - } - if (vals.length === 0) ; - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } -}; -const functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } -}; -const transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } -}; -const mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } -}; -const setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } -}; -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = process$1(def.element, ctx, { ...params, path: [...params.path, "items"] }); -}; -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - json.properties = {}; - const shape = def.shape; - for (const key in shape) { - json.properties[key] = process$1(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - }); - } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === undefined; - } - else { - return v.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - if (def.catchall?._zod.def.type === "never") { - json.additionalProperties = false; - } - else if (!def.catchall) { - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = process$1(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => process$1(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = process$1(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = process$1(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => process$1(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? process$1(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (rest) { - json.items = rest; - } - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - json.minItems = prefixItems.length; - if (!rest) { - json.maxItems = prefixItems.length; - } - } - else { - json.items = prefixItems; - if (rest) { - json.additionalItems = rest; - } - } - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - const valueSchema = process$1(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - json.patternProperties[pattern.source] = valueSchema; - } - } - else { - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = process$1(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - } - json.additionalProperties = process$1(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - const keyValues = keyType._zod.values; - if (keyValues) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues; - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.default = JSON.parse(JSON.stringify(def.defaultValue)); -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io === "input") - json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; - process$1(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - process$1(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - process$1(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - process$1(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - ctx.external = external; - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - schemas[key] = finalize(ctx, schema); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - const ctx = initializeContext({ ...params, processors: allProcessors }); - process$1(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - -class JSONSchemaGenerator { - get metadataRegistry() { - return this.ctx.metadataRegistry; - } - get target() { - return this.ctx.target; - } - get unrepresentable() { - return this.ctx.unrepresentable; - } - get override() { - return this.ctx.override; - } - get io() { - return this.ctx.io; - } - get counter() { - return this.ctx.counter; - } - set counter(value) { - this.ctx.counter = value; - } - get seen() { - return this.ctx.seen; - } - constructor(params) { - let normalizedTarget = params?.target ?? "draft-2020-12"; - if (normalizedTarget === "draft-4") - normalizedTarget = "draft-04"; - if (normalizedTarget === "draft-7") - normalizedTarget = "draft-07"; - this.ctx = initializeContext({ - processors: allProcessors, - target: normalizedTarget, - ...(params?.metadata && { metadata: params.metadata }), - ...(params?.unrepresentable && { unrepresentable: params.unrepresentable }), - ...(params?.override && { override: params.override }), - ...(params?.io && { io: params.io }), - }); - } - process(schema, _params = { path: [], schemaPath: [] }) { - return process$1(schema, this.ctx, _params); - } - emit(schema, _params) { - if (_params) { - if (_params.cycles) - this.ctx.cycles = _params.cycles; - if (_params.reused) - this.ctx.reused = _params.reused; - if (_params.external) - this.ctx.external = _params.external; - } - extractDefs(this.ctx, schema); - const result = finalize(this.ctx, schema); - const { "~standard": _, ...plainResult } = result; - return plainResult; - } -} - -var jsonSchema = /*#__PURE__*/Object.freeze({ - __proto__: null -}); - -var index = /*#__PURE__*/Object.freeze({ - __proto__: null, - $ZodAny: $ZodAny, - $ZodArray: $ZodArray, - $ZodAsyncError: $ZodAsyncError, - $ZodBase64: $ZodBase64, - $ZodBase64URL: $ZodBase64URL, - $ZodBigInt: $ZodBigInt, - $ZodBigIntFormat: $ZodBigIntFormat, - $ZodBoolean: $ZodBoolean, - $ZodCIDRv4: $ZodCIDRv4, - $ZodCIDRv6: $ZodCIDRv6, - $ZodCUID: $ZodCUID, - $ZodCUID2: $ZodCUID2, - $ZodCatch: $ZodCatch, - $ZodCheck: $ZodCheck, - $ZodCheckBigIntFormat: $ZodCheckBigIntFormat, - $ZodCheckEndsWith: $ZodCheckEndsWith, - $ZodCheckGreaterThan: $ZodCheckGreaterThan, - $ZodCheckIncludes: $ZodCheckIncludes, - $ZodCheckLengthEquals: $ZodCheckLengthEquals, - $ZodCheckLessThan: $ZodCheckLessThan, - $ZodCheckLowerCase: $ZodCheckLowerCase, - $ZodCheckMaxLength: $ZodCheckMaxLength, - $ZodCheckMaxSize: $ZodCheckMaxSize, - $ZodCheckMimeType: $ZodCheckMimeType, - $ZodCheckMinLength: $ZodCheckMinLength, - $ZodCheckMinSize: $ZodCheckMinSize, - $ZodCheckMultipleOf: $ZodCheckMultipleOf, - $ZodCheckNumberFormat: $ZodCheckNumberFormat, - $ZodCheckOverwrite: $ZodCheckOverwrite, - $ZodCheckProperty: $ZodCheckProperty, - $ZodCheckRegex: $ZodCheckRegex, - $ZodCheckSizeEquals: $ZodCheckSizeEquals, - $ZodCheckStartsWith: $ZodCheckStartsWith, - $ZodCheckStringFormat: $ZodCheckStringFormat, - $ZodCheckUpperCase: $ZodCheckUpperCase, - $ZodCodec: $ZodCodec, - $ZodCustom: $ZodCustom, - $ZodCustomStringFormat: $ZodCustomStringFormat, - $ZodDate: $ZodDate, - $ZodDefault: $ZodDefault, - $ZodDiscriminatedUnion: $ZodDiscriminatedUnion, - $ZodE164: $ZodE164, - $ZodEmail: $ZodEmail, - $ZodEmoji: $ZodEmoji, - $ZodEncodeError: $ZodEncodeError, - $ZodEnum: $ZodEnum, - $ZodError: $ZodError, - $ZodExactOptional: $ZodExactOptional, - $ZodFile: $ZodFile, - $ZodFunction: $ZodFunction, - $ZodGUID: $ZodGUID, - $ZodIPv4: $ZodIPv4, - $ZodIPv6: $ZodIPv6, - $ZodISODate: $ZodISODate, - $ZodISODateTime: $ZodISODateTime, - $ZodISODuration: $ZodISODuration, - $ZodISOTime: $ZodISOTime, - $ZodIntersection: $ZodIntersection, - $ZodJWT: $ZodJWT, - $ZodKSUID: $ZodKSUID, - $ZodLazy: $ZodLazy, - $ZodLiteral: $ZodLiteral, - $ZodMAC: $ZodMAC, - $ZodMap: $ZodMap, - $ZodNaN: $ZodNaN, - $ZodNanoID: $ZodNanoID, - $ZodNever: $ZodNever, - $ZodNonOptional: $ZodNonOptional, - $ZodNull: $ZodNull, - $ZodNullable: $ZodNullable, - $ZodNumber: $ZodNumber, - $ZodNumberFormat: $ZodNumberFormat, - $ZodObject: $ZodObject, - $ZodObjectJIT: $ZodObjectJIT, - $ZodOptional: $ZodOptional, - $ZodPipe: $ZodPipe, - $ZodPrefault: $ZodPrefault, - $ZodPromise: $ZodPromise, - $ZodReadonly: $ZodReadonly, - $ZodRealError: $ZodRealError, - $ZodRecord: $ZodRecord, - $ZodRegistry: $ZodRegistry, - $ZodSet: $ZodSet, - $ZodString: $ZodString, - $ZodStringFormat: $ZodStringFormat, - $ZodSuccess: $ZodSuccess, - $ZodSymbol: $ZodSymbol, - $ZodTemplateLiteral: $ZodTemplateLiteral, - $ZodTransform: $ZodTransform, - $ZodTuple: $ZodTuple, - $ZodType: $ZodType, - $ZodULID: $ZodULID, - $ZodURL: $ZodURL, - $ZodUUID: $ZodUUID, - $ZodUndefined: $ZodUndefined, - $ZodUnion: $ZodUnion, - $ZodUnknown: $ZodUnknown, - $ZodVoid: $ZodVoid, - $ZodXID: $ZodXID, - $ZodXor: $ZodXor, - $brand: $brand, - $constructor: $constructor, - $input: $input, - $output: $output, - Doc: Doc, - JSONSchema: jsonSchema, - JSONSchemaGenerator: JSONSchemaGenerator, - NEVER: NEVER, - TimePrecision: TimePrecision, - _any: _any, - _array: _array, - _base64: _base64, - _base64url: _base64url, - _bigint: _bigint, - _boolean: _boolean, - _catch: _catch$1, - _check: _check, - _cidrv4: _cidrv4, - _cidrv6: _cidrv6, - _coercedBigint: _coercedBigint, - _coercedBoolean: _coercedBoolean, - _coercedDate: _coercedDate, - _coercedNumber: _coercedNumber, - _coercedString: _coercedString, - _cuid: _cuid, - _cuid2: _cuid2, - _custom: _custom, - _date: _date, - _decode: _decode, - _decodeAsync: _decodeAsync, - _default: _default$1, - _discriminatedUnion: _discriminatedUnion, - _e164: _e164, - _email: _email, - _emoji: _emoji, - _encode: _encode, - _encodeAsync: _encodeAsync, - _endsWith: _endsWith, - _enum: _enum$2, - _file: _file, - _float32: _float32, - _float64: _float64, - _gt: _gt, - _gte: _gte, - _guid: _guid, - _includes: _includes, - _int: _int, - _int32: _int32, - _int64: _int64, - _intersection: _intersection, - _ipv4: _ipv4, - _ipv6: _ipv6, - _isoDate: _isoDate, - _isoDateTime: _isoDateTime, - _isoDuration: _isoDuration, - _isoTime: _isoTime, - _jwt: _jwt, - _ksuid: _ksuid, - _lazy: _lazy, - _length: _length, - _literal: _literal, - _lowercase: _lowercase, - _lt: _lt, - _lte: _lte, - _mac: _mac, - _map: _map, - _max: _lte, - _maxLength: _maxLength, - _maxSize: _maxSize, - _mime: _mime, - _min: _gte, - _minLength: _minLength, - _minSize: _minSize, - _multipleOf: _multipleOf, - _nan: _nan, - _nanoid: _nanoid, - _nativeEnum: _nativeEnum, - _negative: _negative, - _never: _never, - _nonnegative: _nonnegative, - _nonoptional: _nonoptional, - _nonpositive: _nonpositive, - _normalize: _normalize, - _null: _null$1, - _nullable: _nullable, - _number: _number, - _optional: _optional, - _overwrite: _overwrite, - _parse: _parse, - _parseAsync: _parseAsync, - _pipe: _pipe, - _positive: _positive, - _promise: _promise, - _property: _property, - _readonly: _readonly, - _record: _record, - _refine: _refine, - _regex: _regex, - _safeDecode: _safeDecode, - _safeDecodeAsync: _safeDecodeAsync, - _safeEncode: _safeEncode, - _safeEncodeAsync: _safeEncodeAsync, - _safeParse: _safeParse, - _safeParseAsync: _safeParseAsync, - _set: _set, - _size: _size, - _slugify: _slugify, - _startsWith: _startsWith, - _string: _string, - _stringFormat: _stringFormat, - _stringbool: _stringbool, - _success: _success, - _superRefine: _superRefine, - _symbol: _symbol, - _templateLiteral: _templateLiteral, - _toLowerCase: _toLowerCase, - _toUpperCase: _toUpperCase, - _transform: _transform, - _trim: _trim, - _tuple: _tuple, - _uint32: _uint32, - _uint64: _uint64, - _ulid: _ulid, - _undefined: _undefined$1, - _union: _union, - _unknown: _unknown, - _uppercase: _uppercase, - _url: _url, - _uuid: _uuid, - _uuidv4: _uuidv4, - _uuidv6: _uuidv6, - _uuidv7: _uuidv7, - _void: _void$1, - _xid: _xid, - _xor: _xor, - clone: clone, - config: config, - createStandardJSONSchemaMethod: createStandardJSONSchemaMethod, - createToJSONSchemaMethod: createToJSONSchemaMethod, - decode: decode$1, - decodeAsync: decodeAsync$1, - describe: describe$1, - encode: encode$1, - encodeAsync: encodeAsync$1, - extractDefs: extractDefs, - finalize: finalize, - flattenError: flattenError, - formatError: formatError, - globalConfig: globalConfig, - globalRegistry: globalRegistry, - initializeContext: initializeContext, - isValidBase64: isValidBase64, - isValidBase64URL: isValidBase64URL, - isValidJWT: isValidJWT, - locales: index$1, - meta: meta$1, - parse: parse$1, - parseAsync: parseAsync$1, - prettifyError: prettifyError, - process: process$1, - regexes: regexes, - registry: registry, - safeDecode: safeDecode$1, - safeDecodeAsync: safeDecodeAsync$1, - safeEncode: safeEncode$1, - safeEncodeAsync: safeEncodeAsync$1, - safeParse: safeParse$2, - safeParseAsync: safeParseAsync$2, - toDotPath: toDotPath, - toJSONSchema: toJSONSchema, - treeifyError: treeifyError, - util: util$1, - version: version -}); - -const ZodMiniType = $constructor("ZodMiniType", (inst, def) => { - if (!inst._zod) - throw new Error("Uninitialized schema in ZodMiniType."); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - inst.parse = (data, params) => parse$1(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse$2(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync$1(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync$2(inst, data, params); - inst.check = (...checks) => { - return inst.clone({ - ...def, - checks: [ - ...(def.checks ?? []), - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }, { parent: true }); - }; - inst.with = inst.check; - inst.clone = (_def, params) => clone(inst, _def, params); - inst.brand = () => inst; - inst.register = ((reg, meta) => { - reg.add(inst, meta); - return inst; - }); - inst.apply = (fn) => fn(inst); -}); -const ZodMiniString = $constructor("ZodMiniString", (inst, def) => { - $ZodString.init(inst, def); - ZodMiniType.init(inst, def); -}); -const ZodMiniStringFormat = $constructor("ZodMiniStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - ZodMiniString.init(inst, def); -}); -$constructor("ZodMiniEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniMAC", (inst, def) => { - $ZodMAC.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -$constructor("ZodMiniCustomStringFormat", (inst, def) => { - $ZodCustomStringFormat.init(inst, def); - ZodMiniStringFormat.init(inst, def); -}); -const ZodMiniNumber = $constructor("ZodMiniNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodMiniNumber.init(inst, def); -}); -$constructor("ZodMiniBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodMiniType.init(inst, def); -}); -const ZodMiniBigInt = $constructor("ZodMiniBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniBigIntFormat", (inst, def) => { - $ZodBigIntFormat.init(inst, def); - ZodMiniBigInt.init(inst, def); -}); -$constructor("ZodMiniSymbol", (inst, def) => { - $ZodSymbol.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniUndefined", (inst, def) => { - $ZodUndefined.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniVoid", (inst, def) => { - $ZodVoid.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodMiniType.init(inst, def); -}); -const ZodMiniObject = $constructor("ZodMiniObject", (inst, def) => { - $ZodObject.init(inst, def); - ZodMiniType.init(inst, def); - defineLazy(inst, "shape", () => def.shape); -}); -function object$1(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodMiniObject(def); -} -const ZodMiniUnion = $constructor("ZodMiniUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniXor", (inst, def) => { - ZodMiniUnion.init(inst, def); - $ZodXor.init(inst, def); -}); -$constructor("ZodMiniDiscriminatedUnion", (inst, def) => { - $ZodDiscriminatedUnion.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniTuple", (inst, def) => { - $ZodTuple.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniMap", (inst, def) => { - $ZodMap.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniSet", (inst, def) => { - $ZodSet.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodMiniType.init(inst, def); - inst.options = Object.values(def.entries); -}); -$constructor("ZodMiniLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniFile", (inst, def) => { - $ZodFile.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniSuccess", (inst, def) => { - $ZodSuccess.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniNaN", (inst, def) => { - $ZodNaN.init(inst, def); - ZodMiniType.init(inst, def); -}); -const ZodMiniPipe = $constructor("ZodMiniPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniCodec", (inst, def) => { - ZodMiniPipe.init(inst, def); - $ZodCodec.init(inst, def); -}); -$constructor("ZodMiniReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniPromise", (inst, def) => { - $ZodPromise.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodMiniType.init(inst, def); -}); -$constructor("ZodMiniFunction", (inst, def) => { - $ZodFunction.init(inst, def); - ZodMiniType.init(inst, def); -}); - -function isZ4Schema(s) { - const schema = s; - return !!schema._zod; -} -function objectFromShape(shape) { - const values = Object.values(shape); - if (values.length === 0) - return object$1({}); - const allV4 = values.every(isZ4Schema); - const allV3 = values.every(s => !isZ4Schema(s)); - if (allV4) - return object$1(shape); - if (allV3) - return objectType(shape); - throw new Error('Mixed Zod versions detected in object shape.'); -} -function safeParse$1(schema, data) { - if (isZ4Schema(schema)) { - const result = safeParse$2(schema, data); - return result; - } - const v3Schema = schema; - const result = v3Schema.safeParse(data); - return result; -} -async function safeParseAsync$1(schema, data) { - if (isZ4Schema(schema)) { - const result = await safeParseAsync$2(schema, data); - return result; - } - const v3Schema = schema; - const result = await v3Schema.safeParseAsync(data); - return result; -} -function getObjectShape(schema) { - if (!schema) - return undefined; - let rawShape; - if (isZ4Schema(schema)) { - const v4Schema = schema; - rawShape = v4Schema._zod?.def?.shape; - } - else { - const v3Schema = schema; - rawShape = v3Schema.shape; - } - if (!rawShape) - return undefined; - if (typeof rawShape === 'function') { - try { - return rawShape(); - } - catch { - return undefined; - } - } - return rawShape; -} -function normalizeObjectSchema(schema) { - if (!schema) - return undefined; - if (typeof schema === 'object') { - const asV3 = schema; - const asV4 = schema; - if (!asV3._def && !asV4._zod) { - const values = Object.values(schema); - if (values.length > 0 && - values.every(v => typeof v === 'object' && - v !== null && - (v._def !== undefined || - v._zod !== undefined || - typeof v.parse === 'function'))) { - return objectFromShape(schema); - } - } - } - if (isZ4Schema(schema)) { - const v4Schema = schema; - const def = v4Schema._zod?.def; - if (def && (def.type === 'object' || def.shape !== undefined)) { - return schema; - } - } - else { - const v3Schema = schema; - if (v3Schema.shape !== undefined) { - return schema; - } - } - return undefined; -} -function getParseErrorMessage(error) { - if (error && typeof error === 'object') { - if ('message' in error && typeof error.message === 'string') { - return error.message; - } - if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { - const firstIssue = error.issues[0]; - if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { - return String(firstIssue.message); - } - } - try { - return JSON.stringify(error); - } - catch { - return String(error); - } - } - return String(error); -} -function getSchemaDescription(schema) { - return schema.description; -} -function isSchemaOptional(schema) { - if (isZ4Schema(schema)) { - const v4Schema = schema; - return v4Schema._zod?.def?.type === 'optional'; - } - const v3Schema = schema; - if (typeof schema.isOptional === 'function') { - return schema.isOptional(); - } - return v3Schema._def?.typeName === 'ZodOptional'; -} -function getLiteralValue(schema) { - if (isZ4Schema(schema)) { - const v4Schema = schema; - const def = v4Schema._zod?.def; - if (def) { - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - } - const v3Schema = schema; - const def = v3Schema._def; - if (def) { - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - const directValue = schema.value; - if (directValue !== undefined) - return directValue; - return undefined; -} - -var _checks = /*#__PURE__*/Object.freeze({ - __proto__: null, - endsWith: _endsWith, - gt: _gt, - gte: _gte, - includes: _includes, - length: _length, - lowercase: _lowercase, - lt: _lt, - lte: _lte, - maxLength: _maxLength, - maxSize: _maxSize, - mime: _mime, - minLength: _minLength, - minSize: _minSize, - multipleOf: _multipleOf, - negative: _negative, - nonnegative: _nonnegative, - nonpositive: _nonpositive, - normalize: _normalize, - overwrite: _overwrite, - positive: _positive, - property: _property, - regex: _regex, - size: _size, - slugify: _slugify, - startsWith: _startsWith, - toLowerCase: _toLowerCase, - toUpperCase: _toUpperCase, - trim: _trim, - uppercase: _uppercase -}); - -const ZodISODateTime = $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -const ZodISODate = $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date$2(params) { - return _isoDate(ZodISODate, params); -} -const ZodISOTime = $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time(params) { - return _isoTime(ZodISOTime, params); -} -const ZodISODuration = $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration(params) { - return _isoDuration(ZodISODuration, params); -} - -var _iso = /*#__PURE__*/Object.freeze({ - __proto__: null, - ZodISODate: ZodISODate, - ZodISODateTime: ZodISODateTime, - ZodISODuration: ZodISODuration, - ZodISOTime: ZodISOTime, - date: date$2, - datetime: datetime, - duration: duration, - time: time -}); - -const initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper), - }, - flatten: { - value: (mapper) => flattenError(inst, mapper), - }, - addIssue: { - value: (issue) => { - inst.issues.push(issue); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - }, - }, - addIssues: { - value: (issues) => { - inst.issues.push(...issues); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - }, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - }, - }, - }); -}; -const ZodError = $constructor("ZodError", initializer); -const ZodRealError = $constructor("ZodError", initializer, { - Parent: Error, -}); - -const parse = _parse(ZodRealError); -const parseAsync = _parseAsync(ZodRealError); -const safeParse = _safeParse(ZodRealError); -const safeParseAsync = _safeParseAsync(ZodRealError); -const encode = _encode(ZodRealError); -const decode = _decode(ZodRealError); -const encodeAsync = _encodeAsync(ZodRealError); -const decodeAsync = _decodeAsync(ZodRealError); -const safeEncode = _safeEncode(ZodRealError); -const safeDecode = _safeDecode(ZodRealError); -const safeEncodeAsync = _safeEncodeAsync(ZodRealError); -const safeDecodeAsync = _safeDecodeAsync(ZodRealError); - -const ZodType = $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output"), - }, - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); - inst.def = def; - inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - inst.check = (...checks) => { - return inst.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { - parent: true, - }); - }; - inst.with = inst.check; - inst.clone = (def, params) => clone(inst, def, params); - inst.brand = () => inst; - inst.register = ((reg, meta) => { - reg.add(inst, meta); - return inst; - }); - inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode(inst, data, params); - inst.decode = (data, params) => decode(inst, data, params); - inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params); - inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params); - inst.safeEncode = (data, params) => safeEncode(inst, data, params); - inst.safeDecode = (data, params) => safeDecode(inst, data, params); - inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params); - inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params); - inst.refine = (check, params) => inst.check(refine(check, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - inst.optional = () => optional(inst); - inst.exactOptional = () => exactOptional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg) => union([inst, arg]); - inst.and = (arg) => intersection(inst, arg); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def) => _default(inst, def); - inst.prefault = (def) => prefault(inst, def); - inst.catch = (params) => _catch(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true, - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); - } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }; - inst.isOptional = () => inst.safeParse(undefined).success; - inst.isNullable = () => inst.safeParse(null).success; - inst.apply = (fn) => fn(inst); - return inst; -}); -const _ZodString = $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - inst.regex = (...args) => inst.check(_regex(...args)); - inst.includes = (...args) => inst.check(_includes(...args)); - inst.startsWith = (...args) => inst.check(_startsWith(...args)); - inst.endsWith = (...args) => inst.check(_endsWith(...args)); - inst.min = (...args) => inst.check(_minLength(...args)); - inst.max = (...args) => inst.check(_maxLength(...args)); - inst.length = (...args) => inst.check(_length(...args)); - inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase(params)); - inst.uppercase = (params) => inst.check(_uppercase(params)); - inst.trim = () => inst.check(_trim()); - inst.normalize = (...args) => inst.check(_normalize(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase()); - inst.toUpperCase = () => inst.check(_toUpperCase()); - inst.slugify = () => inst.check(_slugify()); -}); -const ZodString = $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime(params)); - inst.date = (params) => inst.check(date$2(params)); - inst.time = (params) => inst.check(time(params)); - inst.duration = (params) => inst.check(duration(params)); -}); -function string$1(params) { - return _string(ZodString, params); -} -const ZodStringFormat = $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodEmail = $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function guid(params) { - return _guid(ZodGUID, params); -} -const ZodUUID = $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function uuid(params) { - return _uuid(ZodUUID, params); -} -function uuidv4(params) { - return _uuidv4(ZodUUID, params); -} -function uuidv6(params) { - return _uuidv6(ZodUUID, params); -} -function uuidv7(params) { - return _uuidv7(ZodUUID, params); -} -const ZodURL = $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return _url(ZodURL, { - protocol: /^https?$/, - hostname: domain, - ...normalizeParams(params), - }); -} -const ZodEmoji = $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function emoji(params) { - return _emoji(ZodEmoji, params); -} -const ZodNanoID = $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function nanoid(params) { - return _nanoid(ZodNanoID, params); -} -const ZodCUID = $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function cuid(params) { - return _cuid(ZodCUID, params); -} -const ZodCUID2 = $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function cuid2(params) { - return _cuid2(ZodCUID2, params); -} -const ZodULID = $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ulid(params) { - return _ulid(ZodULID, params); -} -const ZodXID = $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function xid(params) { - return _xid(ZodXID, params); -} -const ZodKSUID = $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ksuid(params) { - return _ksuid(ZodKSUID, params); -} -const ZodIPv4 = $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ipv4(params) { - return _ipv4(ZodIPv4, params); -} -const ZodMAC = $constructor("ZodMAC", (inst, def) => { - $ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function mac(params) { - return _mac(ZodMAC, params); -} -const ZodIPv6 = $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function ipv6(params) { - return _ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function cidrv4(params) { - return _cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function cidrv6(params) { - return _cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function base64(params) { - return _base64(ZodBase64, params); -} -const ZodBase64URL = $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function base64url(params) { - return _base64url(ZodBase64URL, params); -} -const ZodE164 = $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function e164(params) { - return _e164(ZodE164, params); -} -const ZodJWT = $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return _jwt(ZodJWT, params); -} -const ZodCustomStringFormat = $constructor("ZodCustomStringFormat", (inst, def) => { - $ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function stringFormat(format, fnOrRegex, _params = {}) { - return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function hostname(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", hostname$1, _params); -} -function hex(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", hex$1, _params); -} -function hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return _stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.int = (params) => inst.check(int(params)); - inst.safe = (params) => inst.check(int(params)); - inst.positive = (params) => inst.check(_gt(0, params)); - inst.nonnegative = (params) => inst.check(_gte(0, params)); - inst.negative = (params) => inst.check(_lt(0, params)); - inst.nonpositive = (params) => inst.check(_lte(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - inst.step = (value, params) => inst.check(_multipleOf(value, params)); - inst.finite = () => inst; - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); -function number$1(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return _float32(ZodNumberFormat, params); -} -function float64(params) { - return _float64(ZodNumberFormat, params); -} -function int32(params) { - return _int32(ZodNumberFormat, params); -} -function uint32(params) { - return _uint32(ZodNumberFormat, params); -} -const ZodBoolean = $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json); -}); -function boolean$1(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => bigintProcessor(inst, ctx); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); -function bigint$1(params) { - return _bigint(ZodBigInt, params); -} -const ZodBigIntFormat = $constructor("ZodBigIntFormat", (inst, def) => { - $ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}); -function int64(params) { - return _int64(ZodBigIntFormat, params); -} -function uint64(params) { - return _uint64(ZodBigIntFormat, params); -} -const ZodSymbol = $constructor("ZodSymbol", (inst, def) => { - $ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => symbolProcessor(inst, ctx); -}); -function symbol(params) { - return _symbol(ZodSymbol, params); -} -const ZodUndefined = $constructor("ZodUndefined", (inst, def) => { - $ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => undefinedProcessor(inst, ctx); -}); -function _undefined(params) { - return _undefined$1(ZodUndefined, params); -} -const ZodNull = $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json); -}); -function _null(params) { - return _null$1(ZodNull, params); -} -const ZodAny = $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = $constructor("ZodVoid", (inst, def) => { - $ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => voidProcessor(inst, ctx); -}); -function _void(params) { - return _void$1(ZodVoid, params); -} -const ZodDate = $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => dateProcessor(inst, ctx); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function date$1(params) { - return _date(ZodDate, params); -} -const ZodArray = $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; -}); -function array(element, params) { - return _array(ZodArray, element, params); -} -function keyof(schema) { - const shape = schema._zod.def.shape; - return _enum$1(Object.keys(shape)); -} -const ZodObject = $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - defineLazy(inst, "shape", () => { - return def.shape; - }); - inst.keyof = () => _enum$1(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); - inst.extend = (incoming) => { - return extend(inst, incoming); - }; - inst.safeExtend = (incoming) => { - return safeExtend(inst, incoming); - }; - inst.merge = (other) => merge(inst, other); - inst.pick = (mask) => pick(inst, mask); - inst.omit = (mask) => omit(inst, mask); - inst.partial = (...args) => partial(ZodOptional, inst, args[0]); - inst.required = (...args) => required$2(ZodNonOptional, inst, args[0]); -}); -function object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...normalizeParams(params), - }); -} -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = $constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - $ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion({ - type: "union", - options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = $constructor("ZodTuple", (inst, def) => { - $ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest: rest, - }); -}); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...normalizeParams(params), - }); -} -const ZodRecord = $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function record(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = undefined; - return new ZodRecord({ - type: "record", - keyType: k, - valueType: valueType, - ...normalizeParams(params), - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...normalizeParams(params), - }); -} -const ZodMap = $constructor("ZodMap", (inst, def) => { - $ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => mapProcessor(inst, ctx); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); -}); -function map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -const ZodSet = $constructor("ZodSet", (inst, def) => { - $ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => setProcessor(inst, ctx); - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); -}); -function set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...normalizeParams(params), - }); -} -const ZodEnum = $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function _enum$1(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -const ZodLiteral = $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = $constructor("ZodFile", (inst, def) => { - $ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => fileProcessor(inst, ctx, json); - inst.min = (size, params) => inst.check(_minSize(size, params)); - inst.max = (size, params) => inst.check(_maxSize(size, params)); - inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); -}); -function file(params) { - return _file(ZodFile, params); -} -const ZodTransform = $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue$1) => { - if (typeof issue$1 === "string") { - payload.issues.push(issue(issue$1, payload.value, def)); - } - else { - const _issue = issue$1; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - payload.issues.push(issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -function nullish(innerType) { - return optional(nullable(innerType)); -} -const ZodDefault = $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function _default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = $constructor("ZodSuccess", (inst, def) => { - $ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => successProcessor(inst, ctx, json); - inst.unwrap = () => inst._zod.def.innerType; -}); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function _catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), - }); -} -const ZodNaN = $constructor("ZodNaN", (inst, def) => { - $ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nanProcessor(inst, ctx); -}); -function nan(params) { - return _nan(ZodNaN, params); -} -const ZodPipe = $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - }); -} -const ZodCodec = $constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - $ZodCodec.init(inst, def); -}); -function codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -const ZodReadonly = $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = $constructor("ZodTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => templateLiteralProcessor(inst, ctx, json); -}); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...normalizeParams(params), - }); -} -const ZodLazy = $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = $constructor("ZodPromise", (inst, def) => { - $ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = $constructor("ZodFunction", (inst, def) => { - $ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => functionProcessor(inst, ctx); -}); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())), - output: params?.output ?? unknown(), - }); -} -const ZodCustom = $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx); -}); -function check(fn) { - const ch = new $ZodCheck({ - check: "custom", - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return _custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -function superRefine(fn) { - return _superRefine(fn); -} -const describe = describe$1; -const meta = meta$1; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...normalizeParams(params), - }); - inst._zod.bag.Class = cls; - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} -const stringbool = (...args) => _stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function json(params) { - const jsonSchema = lazy(() => { - return union([string$1(params), number$1(), boolean$1(), _null(), array(jsonSchema), record(string$1(), jsonSchema)]); - }); - return jsonSchema; -} -function preprocess(fn, schema) { - return pipe(transform(fn), schema); -} - -var _schemas = /*#__PURE__*/Object.freeze({ - __proto__: null, - ZodAny: ZodAny, - ZodArray: ZodArray, - ZodBase64: ZodBase64, - ZodBase64URL: ZodBase64URL, - ZodBigInt: ZodBigInt, - ZodBigIntFormat: ZodBigIntFormat, - ZodBoolean: ZodBoolean, - ZodCIDRv4: ZodCIDRv4, - ZodCIDRv6: ZodCIDRv6, - ZodCUID: ZodCUID, - ZodCUID2: ZodCUID2, - ZodCatch: ZodCatch, - ZodCodec: ZodCodec, - ZodCustom: ZodCustom, - ZodCustomStringFormat: ZodCustomStringFormat, - ZodDate: ZodDate, - ZodDefault: ZodDefault, - ZodDiscriminatedUnion: ZodDiscriminatedUnion, - ZodE164: ZodE164, - ZodEmail: ZodEmail, - ZodEmoji: ZodEmoji, - ZodEnum: ZodEnum, - ZodExactOptional: ZodExactOptional, - ZodFile: ZodFile, - ZodFunction: ZodFunction, - ZodGUID: ZodGUID, - ZodIPv4: ZodIPv4, - ZodIPv6: ZodIPv6, - ZodIntersection: ZodIntersection, - ZodJWT: ZodJWT, - ZodKSUID: ZodKSUID, - ZodLazy: ZodLazy, - ZodLiteral: ZodLiteral, - ZodMAC: ZodMAC, - ZodMap: ZodMap, - ZodNaN: ZodNaN, - ZodNanoID: ZodNanoID, - ZodNever: ZodNever, - ZodNonOptional: ZodNonOptional, - ZodNull: ZodNull, - ZodNullable: ZodNullable, - ZodNumber: ZodNumber, - ZodNumberFormat: ZodNumberFormat, - ZodObject: ZodObject, - ZodOptional: ZodOptional, - ZodPipe: ZodPipe, - ZodPrefault: ZodPrefault, - ZodPromise: ZodPromise, - ZodReadonly: ZodReadonly, - ZodRecord: ZodRecord, - ZodSet: ZodSet, - ZodString: ZodString, - ZodStringFormat: ZodStringFormat, - ZodSuccess: ZodSuccess, - ZodSymbol: ZodSymbol, - ZodTemplateLiteral: ZodTemplateLiteral, - ZodTransform: ZodTransform, - ZodTuple: ZodTuple, - ZodType: ZodType, - ZodULID: ZodULID, - ZodURL: ZodURL, - ZodUUID: ZodUUID, - ZodUndefined: ZodUndefined, - ZodUnion: ZodUnion, - ZodUnknown: ZodUnknown, - ZodVoid: ZodVoid, - ZodXID: ZodXID, - ZodXor: ZodXor, - _ZodString: _ZodString, - _default: _default, - _function: _function, - any: any, - array: array, - base64: base64, - base64url: base64url, - bigint: bigint$1, - boolean: boolean$1, - catch: _catch, - check: check, - cidrv4: cidrv4, - cidrv6: cidrv6, - codec: codec, - cuid: cuid, - cuid2: cuid2, - custom: custom, - date: date$1, - describe: describe, - discriminatedUnion: discriminatedUnion, - e164: e164, - email: email, - emoji: emoji, - enum: _enum$1, - exactOptional: exactOptional, - file: file, - float32: float32, - float64: float64, - function: _function, - guid: guid, - hash: hash, - hex: hex, - hostname: hostname, - httpUrl: httpUrl, - instanceof: _instanceof, - int: int, - int32: int32, - int64: int64, - intersection: intersection, - ipv4: ipv4, - ipv6: ipv6, - json: json, - jwt: jwt, - keyof: keyof, - ksuid: ksuid, - lazy: lazy, - literal: literal, - looseObject: looseObject, - looseRecord: looseRecord, - mac: mac, - map: map, - meta: meta, - nan: nan, - nanoid: nanoid, - nativeEnum: nativeEnum, - never: never, - nonoptional: nonoptional, - null: _null, - nullable: nullable, - nullish: nullish, - number: number$1, - object: object, - optional: optional, - partialRecord: partialRecord, - pipe: pipe, - prefault: prefault, - preprocess: preprocess, - promise: promise, - readonly: readonly, - record: record, - refine: refine, - set: set, - strictObject: strictObject, - string: string$1, - stringFormat: stringFormat, - stringbool: stringbool, - success: success, - superRefine: superRefine, - symbol: symbol, - templateLiteral: templateLiteral, - transform: transform, - tuple: tuple, - uint32: uint32, - uint64: uint64, - ulid: ulid, - undefined: _undefined, - union: union, - unknown: unknown, - url: url, - uuid: uuid, - uuidv4: uuidv4, - uuidv6: uuidv6, - uuidv7: uuidv7, - void: _void, - xid: xid, - xor: xor -}); - -const ZodIssueCode = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom", -}; -function setErrorMap(map) { - config({ - customError: map, - }); -} -function getErrorMap() { - return config().customError; -} -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); - -const z$1 = { - ..._schemas, - ..._checks, - iso: _iso, -}; -const RECOGNIZED_KEYS = new Set([ - "$schema", - "$ref", - "$defs", - "definitions", - "$id", - "id", - "$comment", - "$anchor", - "$vocabulary", - "$dynamicRef", - "$dynamicAnchor", - "type", - "enum", - "const", - "anyOf", - "oneOf", - "allOf", - "not", - "properties", - "required", - "additionalProperties", - "patternProperties", - "propertyNames", - "minProperties", - "maxProperties", - "items", - "prefixItems", - "additionalItems", - "minItems", - "maxItems", - "uniqueItems", - "contains", - "minContains", - "maxContains", - "minLength", - "maxLength", - "pattern", - "format", - "minimum", - "maximum", - "exclusiveMinimum", - "exclusiveMaximum", - "multipleOf", - "description", - "default", - "contentEncoding", - "contentMediaType", - "contentSchema", - "unevaluatedItems", - "unevaluatedProperties", - "if", - "then", - "else", - "dependentSchemas", - "dependentRequired", - "nullable", - "readOnly", -]); -function detectVersion(schema, defaultTarget) { - const $schema = schema.$schema; - if ($schema === "https://json-schema.org/draft/2020-12/schema") { - return "draft-2020-12"; - } - if ($schema === "http://json-schema.org/draft-07/schema#") { - return "draft-7"; - } - if ($schema === "http://json-schema.org/draft-04/schema#") { - return "draft-4"; - } - return defaultTarget ?? "draft-2020-12"; -} -function resolveRef(ref, ctx) { - if (!ref.startsWith("#")) { - throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); - } - const path = ref.slice(1).split("/").filter(Boolean); - if (path.length === 0) { - return ctx.rootSchema; - } - const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; - if (path[0] === defsKey) { - const key = path[1]; - if (!key || !ctx.defs[key]) { - throw new Error(`Reference not found: ${ref}`); - } - return ctx.defs[key]; - } - throw new Error(`Reference not found: ${ref}`); -} -function convertBaseSchema(schema, ctx) { - if (schema.not !== undefined) { - if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { - return z$1.never(); - } - throw new Error("not is not supported in Zod (except { not: {} } for never)"); - } - if (schema.unevaluatedItems !== undefined) { - throw new Error("unevaluatedItems is not supported"); - } - if (schema.unevaluatedProperties !== undefined) { - throw new Error("unevaluatedProperties is not supported"); - } - if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) { - throw new Error("Conditional schemas (if/then/else) are not supported"); - } - if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) { - throw new Error("dependentSchemas and dependentRequired are not supported"); - } - if (schema.$ref) { - const refPath = schema.$ref; - if (ctx.refs.has(refPath)) { - return ctx.refs.get(refPath); - } - if (ctx.processing.has(refPath)) { - return z$1.lazy(() => { - if (!ctx.refs.has(refPath)) { - throw new Error(`Circular reference not resolved: ${refPath}`); - } - return ctx.refs.get(refPath); - }); - } - ctx.processing.add(refPath); - const resolved = resolveRef(refPath, ctx); - const zodSchema = convertSchema(resolved, ctx); - ctx.refs.set(refPath, zodSchema); - ctx.processing.delete(refPath); - return zodSchema; - } - if (schema.enum !== undefined) { - const enumValues = schema.enum; - if (ctx.version === "openapi-3.0" && - schema.nullable === true && - enumValues.length === 1 && - enumValues[0] === null) { - return z$1.null(); - } - if (enumValues.length === 0) { - return z$1.never(); - } - if (enumValues.length === 1) { - return z$1.literal(enumValues[0]); - } - if (enumValues.every((v) => typeof v === "string")) { - return z$1.enum(enumValues); - } - const literalSchemas = enumValues.map((v) => z$1.literal(v)); - if (literalSchemas.length < 2) { - return literalSchemas[0]; - } - return z$1.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); - } - if (schema.const !== undefined) { - return z$1.literal(schema.const); - } - const type = schema.type; - if (Array.isArray(type)) { - const typeSchemas = type.map((t) => { - const typeSchema = { ...schema, type: t }; - return convertBaseSchema(typeSchema, ctx); - }); - if (typeSchemas.length === 0) { - return z$1.never(); - } - if (typeSchemas.length === 1) { - return typeSchemas[0]; - } - return z$1.union(typeSchemas); - } - if (!type) { - return z$1.any(); - } - let zodSchema; - switch (type) { - case "string": { - let stringSchema = z$1.string(); - if (schema.format) { - const format = schema.format; - if (format === "email") { - stringSchema = stringSchema.check(z$1.email()); - } - else if (format === "uri" || format === "uri-reference") { - stringSchema = stringSchema.check(z$1.url()); - } - else if (format === "uuid" || format === "guid") { - stringSchema = stringSchema.check(z$1.uuid()); - } - else if (format === "date-time") { - stringSchema = stringSchema.check(z$1.iso.datetime()); - } - else if (format === "date") { - stringSchema = stringSchema.check(z$1.iso.date()); - } - else if (format === "time") { - stringSchema = stringSchema.check(z$1.iso.time()); - } - else if (format === "duration") { - stringSchema = stringSchema.check(z$1.iso.duration()); - } - else if (format === "ipv4") { - stringSchema = stringSchema.check(z$1.ipv4()); - } - else if (format === "ipv6") { - stringSchema = stringSchema.check(z$1.ipv6()); - } - else if (format === "mac") { - stringSchema = stringSchema.check(z$1.mac()); - } - else if (format === "cidr") { - stringSchema = stringSchema.check(z$1.cidrv4()); - } - else if (format === "cidr-v6") { - stringSchema = stringSchema.check(z$1.cidrv6()); - } - else if (format === "base64") { - stringSchema = stringSchema.check(z$1.base64()); - } - else if (format === "base64url") { - stringSchema = stringSchema.check(z$1.base64url()); - } - else if (format === "e164") { - stringSchema = stringSchema.check(z$1.e164()); - } - else if (format === "jwt") { - stringSchema = stringSchema.check(z$1.jwt()); - } - else if (format === "emoji") { - stringSchema = stringSchema.check(z$1.emoji()); - } - else if (format === "nanoid") { - stringSchema = stringSchema.check(z$1.nanoid()); - } - else if (format === "cuid") { - stringSchema = stringSchema.check(z$1.cuid()); - } - else if (format === "cuid2") { - stringSchema = stringSchema.check(z$1.cuid2()); - } - else if (format === "ulid") { - stringSchema = stringSchema.check(z$1.ulid()); - } - else if (format === "xid") { - stringSchema = stringSchema.check(z$1.xid()); - } - else if (format === "ksuid") { - stringSchema = stringSchema.check(z$1.ksuid()); - } - } - if (typeof schema.minLength === "number") { - stringSchema = stringSchema.min(schema.minLength); - } - if (typeof schema.maxLength === "number") { - stringSchema = stringSchema.max(schema.maxLength); - } - if (schema.pattern) { - stringSchema = stringSchema.regex(new RegExp(schema.pattern)); - } - zodSchema = stringSchema; - break; - } - case "number": - case "integer": { - let numberSchema = type === "integer" ? z$1.number().int() : z$1.number(); - if (typeof schema.minimum === "number") { - numberSchema = numberSchema.min(schema.minimum); - } - if (typeof schema.maximum === "number") { - numberSchema = numberSchema.max(schema.maximum); - } - if (typeof schema.exclusiveMinimum === "number") { - numberSchema = numberSchema.gt(schema.exclusiveMinimum); - } - else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { - numberSchema = numberSchema.gt(schema.minimum); - } - if (typeof schema.exclusiveMaximum === "number") { - numberSchema = numberSchema.lt(schema.exclusiveMaximum); - } - else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { - numberSchema = numberSchema.lt(schema.maximum); - } - if (typeof schema.multipleOf === "number") { - numberSchema = numberSchema.multipleOf(schema.multipleOf); - } - zodSchema = numberSchema; - break; - } - case "boolean": { - zodSchema = z$1.boolean(); - break; - } - case "null": { - zodSchema = z$1.null(); - break; - } - case "object": { - const shape = {}; - const properties = schema.properties || {}; - const requiredSet = new Set(schema.required || []); - for (const [key, propSchema] of Object.entries(properties)) { - const propZodSchema = convertSchema(propSchema, ctx); - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" - ? convertSchema(schema.additionalProperties, ctx) - : z$1.any(); - if (Object.keys(shape).length === 0) { - zodSchema = z$1.record(keySchema, valueSchema); - break; - } - const objectSchema = z$1.object(shape).passthrough(); - const recordSchema = z$1.looseRecord(keySchema, valueSchema); - zodSchema = z$1.intersection(objectSchema, recordSchema); - break; - } - if (schema.patternProperties) { - const patternProps = schema.patternProperties; - const patternKeys = Object.keys(patternProps); - const looseRecords = []; - for (const pattern of patternKeys) { - const patternValue = convertSchema(patternProps[pattern], ctx); - const keySchema = z$1.string().regex(new RegExp(pattern)); - looseRecords.push(z$1.looseRecord(keySchema, patternValue)); - } - const schemasToIntersect = []; - if (Object.keys(shape).length > 0) { - schemasToIntersect.push(z$1.object(shape).passthrough()); - } - schemasToIntersect.push(...looseRecords); - if (schemasToIntersect.length === 0) { - zodSchema = z$1.object({}).passthrough(); - } - else if (schemasToIntersect.length === 1) { - zodSchema = schemasToIntersect[0]; - } - else { - let result = z$1.intersection(schemasToIntersect[0], schemasToIntersect[1]); - for (let i = 2; i < schemasToIntersect.length; i++) { - result = z$1.intersection(result, schemasToIntersect[i]); - } - zodSchema = result; - } - break; - } - const objectSchema = z$1.object(shape); - if (schema.additionalProperties === false) { - zodSchema = objectSchema.strict(); - } - else if (typeof schema.additionalProperties === "object") { - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); - } - else { - zodSchema = objectSchema.passthrough(); - } - break; - } - case "array": { - const prefixItems = schema.prefixItems; - const items = schema.items; - if (prefixItems && Array.isArray(prefixItems)) { - const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) - ? convertSchema(items, ctx) - : undefined; - if (rest) { - zodSchema = z$1.tuple(tupleItems).rest(rest); - } - else { - zodSchema = z$1.tuple(tupleItems); - } - if (typeof schema.minItems === "number") { - zodSchema = zodSchema.check(z$1.minLength(schema.minItems)); - } - if (typeof schema.maxItems === "number") { - zodSchema = zodSchema.check(z$1.maxLength(schema.maxItems)); - } - } - else if (Array.isArray(items)) { - const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" - ? convertSchema(schema.additionalItems, ctx) - : undefined; - if (rest) { - zodSchema = z$1.tuple(tupleItems).rest(rest); - } - else { - zodSchema = z$1.tuple(tupleItems); - } - if (typeof schema.minItems === "number") { - zodSchema = zodSchema.check(z$1.minLength(schema.minItems)); - } - if (typeof schema.maxItems === "number") { - zodSchema = zodSchema.check(z$1.maxLength(schema.maxItems)); - } - } - else if (items !== undefined) { - const element = convertSchema(items, ctx); - let arraySchema = z$1.array(element); - if (typeof schema.minItems === "number") { - arraySchema = arraySchema.min(schema.minItems); - } - if (typeof schema.maxItems === "number") { - arraySchema = arraySchema.max(schema.maxItems); - } - zodSchema = arraySchema; - } - else { - zodSchema = z$1.array(z$1.any()); - } - break; - } - default: - throw new Error(`Unsupported type: ${type}`); - } - if (schema.description) { - zodSchema = zodSchema.describe(schema.description); - } - if (schema.default !== undefined) { - zodSchema = zodSchema.default(schema.default); - } - return zodSchema; -} -function convertSchema(schema, ctx) { - if (typeof schema === "boolean") { - return schema ? z$1.any() : z$1.never(); - } - let baseSchema = convertBaseSchema(schema, ctx); - const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined; - if (schema.anyOf && Array.isArray(schema.anyOf)) { - const options = schema.anyOf.map((s) => convertSchema(s, ctx)); - const anyOfUnion = z$1.union(options); - baseSchema = hasExplicitType ? z$1.intersection(baseSchema, anyOfUnion) : anyOfUnion; - } - if (schema.oneOf && Array.isArray(schema.oneOf)) { - const options = schema.oneOf.map((s) => convertSchema(s, ctx)); - const oneOfUnion = z$1.xor(options); - baseSchema = hasExplicitType ? z$1.intersection(baseSchema, oneOfUnion) : oneOfUnion; - } - if (schema.allOf && Array.isArray(schema.allOf)) { - if (schema.allOf.length === 0) { - baseSchema = hasExplicitType ? baseSchema : z$1.any(); - } - else { - let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); - const startIdx = hasExplicitType ? 0 : 1; - for (let i = startIdx; i < schema.allOf.length; i++) { - result = z$1.intersection(result, convertSchema(schema.allOf[i], ctx)); - } - baseSchema = result; - } - } - if (schema.nullable === true && ctx.version === "openapi-3.0") { - baseSchema = z$1.nullable(baseSchema); - } - if (schema.readOnly === true) { - baseSchema = z$1.readonly(baseSchema); - } - const extraMeta = {}; - const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"]; - for (const key of coreMetadataKeys) { - if (key in schema) { - extraMeta[key] = schema[key]; - } - } - const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"]; - for (const key of contentMetadataKeys) { - if (key in schema) { - extraMeta[key] = schema[key]; - } - } - for (const key of Object.keys(schema)) { - if (!RECOGNIZED_KEYS.has(key)) { - extraMeta[key] = schema[key]; - } - } - if (Object.keys(extraMeta).length > 0) { - ctx.registry.add(baseSchema, extraMeta); - } - return baseSchema; -} -function fromJSONSchema(schema, params) { - if (typeof schema === "boolean") { - return schema ? z$1.any() : z$1.never(); - } - const version = detectVersion(schema, params?.defaultTarget); - const defs = (schema.$defs || schema.definitions || {}); - const ctx = { - version, - defs, - refs: new Map(), - processing: new Set(), - rootSchema: schema, - registry: params?.registry ?? globalRegistry, - }; - return convertSchema(schema, ctx); -} - -function string(params) { - return _coercedString(ZodString, params); -} -function number(params) { - return _coercedNumber(ZodNumber, params); -} -function boolean(params) { - return _coercedBoolean(ZodBoolean, params); -} -function bigint(params) { - return _coercedBigint(ZodBigInt, params); -} -function date(params) { - return _coercedDate(ZodDate, params); -} - -var coerce = /*#__PURE__*/Object.freeze({ - __proto__: null, - bigint: bigint, - boolean: boolean, - date: date, - number: number, - string: string -}); - -config(en()); - -var z = /*#__PURE__*/Object.freeze({ - __proto__: null, - $brand: $brand, - $input: $input, - $output: $output, - NEVER: NEVER, - TimePrecision: TimePrecision, - ZodAny: ZodAny, - ZodArray: ZodArray, - ZodBase64: ZodBase64, - ZodBase64URL: ZodBase64URL, - ZodBigInt: ZodBigInt, - ZodBigIntFormat: ZodBigIntFormat, - ZodBoolean: ZodBoolean, - ZodCIDRv4: ZodCIDRv4, - ZodCIDRv6: ZodCIDRv6, - ZodCUID: ZodCUID, - ZodCUID2: ZodCUID2, - ZodCatch: ZodCatch, - ZodCodec: ZodCodec, - ZodCustom: ZodCustom, - ZodCustomStringFormat: ZodCustomStringFormat, - ZodDate: ZodDate, - ZodDefault: ZodDefault, - ZodDiscriminatedUnion: ZodDiscriminatedUnion, - ZodE164: ZodE164, - ZodEmail: ZodEmail, - ZodEmoji: ZodEmoji, - ZodEnum: ZodEnum, - ZodError: ZodError, - ZodExactOptional: ZodExactOptional, - ZodFile: ZodFile, - get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, - ZodFunction: ZodFunction, - ZodGUID: ZodGUID, - ZodIPv4: ZodIPv4, - ZodIPv6: ZodIPv6, - ZodISODate: ZodISODate, - ZodISODateTime: ZodISODateTime, - ZodISODuration: ZodISODuration, - ZodISOTime: ZodISOTime, - ZodIntersection: ZodIntersection, - ZodIssueCode: ZodIssueCode, - ZodJWT: ZodJWT, - ZodKSUID: ZodKSUID, - ZodLazy: ZodLazy, - ZodLiteral: ZodLiteral, - ZodMAC: ZodMAC, - ZodMap: ZodMap, - ZodNaN: ZodNaN, - ZodNanoID: ZodNanoID, - ZodNever: ZodNever, - ZodNonOptional: ZodNonOptional, - ZodNull: ZodNull, - ZodNullable: ZodNullable, - ZodNumber: ZodNumber, - ZodNumberFormat: ZodNumberFormat, - ZodObject: ZodObject, - ZodOptional: ZodOptional, - ZodPipe: ZodPipe, - ZodPrefault: ZodPrefault, - ZodPromise: ZodPromise, - ZodReadonly: ZodReadonly, - ZodRealError: ZodRealError, - ZodRecord: ZodRecord, - ZodSet: ZodSet, - ZodString: ZodString, - ZodStringFormat: ZodStringFormat, - ZodSuccess: ZodSuccess, - ZodSymbol: ZodSymbol, - ZodTemplateLiteral: ZodTemplateLiteral, - ZodTransform: ZodTransform, - ZodTuple: ZodTuple, - ZodType: ZodType, - ZodULID: ZodULID, - ZodURL: ZodURL, - ZodUUID: ZodUUID, - ZodUndefined: ZodUndefined, - ZodUnion: ZodUnion, - ZodUnknown: ZodUnknown, - ZodVoid: ZodVoid, - ZodXID: ZodXID, - ZodXor: ZodXor, - _ZodString: _ZodString, - _default: _default, - _function: _function, - any: any, - array: array, - base64: base64, - base64url: base64url, - bigint: bigint$1, - boolean: boolean$1, - catch: _catch, - check: check, - cidrv4: cidrv4, - cidrv6: cidrv6, - clone: clone, - codec: codec, - coerce: coerce, - config: config, - core: index, - cuid: cuid, - cuid2: cuid2, - custom: custom, - date: date$1, - decode: decode, - decodeAsync: decodeAsync, - describe: describe, - discriminatedUnion: discriminatedUnion, - e164: e164, - email: email, - emoji: emoji, - encode: encode, - encodeAsync: encodeAsync, - endsWith: _endsWith, - enum: _enum$1, - exactOptional: exactOptional, - file: file, - flattenError: flattenError, - float32: float32, - float64: float64, - formatError: formatError, - fromJSONSchema: fromJSONSchema, - function: _function, - getErrorMap: getErrorMap, - globalRegistry: globalRegistry, - gt: _gt, - gte: _gte, - guid: guid, - hash: hash, - hex: hex, - hostname: hostname, - httpUrl: httpUrl, - includes: _includes, - instanceof: _instanceof, - int: int, - int32: int32, - int64: int64, - intersection: intersection, - ipv4: ipv4, - ipv6: ipv6, - iso: _iso, - json: json, - jwt: jwt, - keyof: keyof, - ksuid: ksuid, - lazy: lazy, - length: _length, - literal: literal, - locales: index$1, - looseObject: looseObject, - looseRecord: looseRecord, - lowercase: _lowercase, - lt: _lt, - lte: _lte, - mac: mac, - map: map, - maxLength: _maxLength, - maxSize: _maxSize, - meta: meta, - mime: _mime, - minLength: _minLength, - minSize: _minSize, - multipleOf: _multipleOf, - nan: nan, - nanoid: nanoid, - nativeEnum: nativeEnum, - negative: _negative, - never: never, - nonnegative: _nonnegative, - nonoptional: nonoptional, - nonpositive: _nonpositive, - normalize: _normalize, - null: _null, - nullable: nullable, - nullish: nullish, - number: number$1, - object: object, - optional: optional, - overwrite: _overwrite, - parse: parse, - parseAsync: parseAsync, - partialRecord: partialRecord, - pipe: pipe, - positive: _positive, - prefault: prefault, - preprocess: preprocess, - prettifyError: prettifyError, - promise: promise, - property: _property, - readonly: readonly, - record: record, - refine: refine, - regex: _regex, - regexes: regexes, - registry: registry, - safeDecode: safeDecode, - safeDecodeAsync: safeDecodeAsync, - safeEncode: safeEncode, - safeEncodeAsync: safeEncodeAsync, - safeParse: safeParse, - safeParseAsync: safeParseAsync, - set: set, - setErrorMap: setErrorMap, - size: _size, - slugify: _slugify, - startsWith: _startsWith, - strictObject: strictObject, - string: string$1, - stringFormat: stringFormat, - stringbool: stringbool, - success: success, - superRefine: superRefine, - symbol: symbol, - templateLiteral: templateLiteral, - toJSONSchema: toJSONSchema, - toLowerCase: _toLowerCase, - toUpperCase: _toUpperCase, - transform: transform, - treeifyError: treeifyError, - trim: _trim, - tuple: tuple, - uint32: uint32, - uint64: uint64, - ulid: ulid, - undefined: _undefined, - union: union, - unknown: unknown, - uppercase: _uppercase, - url: url, - util: util$1, - uuid: uuid, - uuidv4: uuidv4, - uuidv6: uuidv6, - uuidv7: uuidv7, - void: _void, - xid: xid, - xor: xor -}); - -const LATEST_PROTOCOL_VERSION = '2025-11-25'; -const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; -const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; -const JSONRPC_VERSION = '2.0'; -const AssertObjectSchema = custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); -const ProgressTokenSchema = union([string$1(), number$1().int()]); -const CursorSchema = string$1(); -looseObject({ - ttl: union([number$1(), _null()]).optional(), - pollInterval: number$1().optional() -}); -const TaskMetadataSchema = object({ - ttl: number$1().optional() -}); -const RelatedTaskMetadataSchema = object({ - taskId: string$1() -}); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -const BaseRequestParamsSchema = object({ - _meta: RequestMetaSchema.optional() -}); -const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ - task: TaskMetadataSchema.optional() -}); -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const RequestSchema = object({ - method: string$1(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = object({ - _meta: RequestMetaSchema.optional() -}); -const NotificationSchema = object({ - method: string$1(), - params: NotificationsParamsSchema.loose().optional() -}); -const ResultSchema = looseObject({ - _meta: RequestMetaSchema.optional() -}); -const RequestIdSchema = union([string$1(), number$1().int()]); -const JSONRPCRequestSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}) - .strict(); -const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const JSONRPCNotificationSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}) - .strict(); -const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -const JSONRPCResultResponseSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}) - .strict(); -const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -var ErrorCode; -(function (ErrorCode) { - ErrorCode[ErrorCode["ConnectionClosed"] = -32e3] = "ConnectionClosed"; - ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; - ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; - ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; - ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; - ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; - ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; - ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; -})(ErrorCode || (ErrorCode = {})); -const JSONRPCErrorResponseSchema = object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: object({ - code: number$1().int(), - message: string$1(), - data: unknown().optional() - }) -}) - .strict(); -const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -const JSONRPCMessageSchema = union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: string$1().optional() -}); -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/cancelled'), - params: CancelledNotificationParamsSchema -}); -const IconSchema = object({ - src: string$1(), - mimeType: string$1().optional(), - sizes: array(string$1()).optional(), - theme: _enum$1(['light', 'dark']).optional() -}); -const IconsSchema = object({ - icons: array(IconSchema).optional() -}); -const BaseMetadataSchema = object({ - name: string$1(), - title: string$1().optional() -}); -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: string$1(), - websiteUrl: string$1().optional(), - description: string$1().optional() -}); -const FormElicitationCapabilitySchema = intersection(object({ - applyDefaults: boolean$1().optional() -}), record(string$1(), unknown())); -const ElicitationCapabilitySchema = preprocess(value => { - if (value && typeof value === 'object' && !Array.isArray(value)) { - if (Object.keys(value).length === 0) { - return { form: {} }; - } - } - return value; -}, intersection(object({ - form: FormElicitationCapabilitySchema.optional(), - url: AssertObjectSchema.optional() -}), record(string$1(), unknown()).optional())); -const ClientTasksCapabilitySchema = looseObject({ - list: AssertObjectSchema.optional(), - cancel: AssertObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ - createMessage: AssertObjectSchema.optional() - }) - .optional(), - elicitation: looseObject({ - create: AssertObjectSchema.optional() - }) - .optional() - }) - .optional() -}); -const ServerTasksCapabilitySchema = looseObject({ - list: AssertObjectSchema.optional(), - cancel: AssertObjectSchema.optional(), - requests: looseObject({ - tools: looseObject({ - call: AssertObjectSchema.optional() - }) - .optional() - }) - .optional() -}); -const ClientCapabilitiesSchema = object({ - experimental: record(string$1(), AssertObjectSchema).optional(), - sampling: object({ - context: AssertObjectSchema.optional(), - tools: AssertObjectSchema.optional() - }) - .optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: object({ - listChanged: boolean$1().optional() - }) - .optional(), - tasks: ClientTasksCapabilitySchema.optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: string$1(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -const InitializeRequestSchema = RequestSchema.extend({ - method: literal('initialize'), - params: InitializeRequestParamsSchema -}); -const ServerCapabilitiesSchema = object({ - experimental: record(string$1(), AssertObjectSchema).optional(), - logging: AssertObjectSchema.optional(), - completions: AssertObjectSchema.optional(), - prompts: object({ - listChanged: boolean$1().optional() - }) - .optional(), - resources: object({ - subscribe: boolean$1().optional(), - listChanged: boolean$1().optional() - }) - .optional(), - tools: object({ - listChanged: boolean$1().optional() - }) - .optional(), - tasks: ServerTasksCapabilitySchema.optional() -}); -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: string$1(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: string$1().optional() -}); -const InitializedNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/initialized'), - params: NotificationsParamsSchema.optional() -}); -const PingRequestSchema = RequestSchema.extend({ - method: literal('ping'), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = object({ - progress: number$1(), - total: optional(number$1()), - message: optional(string$1()) -}); -const ProgressNotificationParamsSchema = object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/progress'), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ - cursor: CursorSchema.optional() -}); -const PaginatedRequestSchema = RequestSchema.extend({ - params: PaginatedRequestParamsSchema.optional() -}); -const PaginatedResultSchema = ResultSchema.extend({ - nextCursor: CursorSchema.optional() -}); -const TaskStatusSchema = _enum$1(['working', 'input_required', 'completed', 'failed', 'cancelled']); -const TaskSchema = object({ - taskId: string$1(), - status: TaskStatusSchema, - ttl: union([number$1(), _null()]), - createdAt: string$1(), - lastUpdatedAt: string$1(), - pollInterval: optional(number$1()), - statusMessage: optional(string$1()) -}); -const CreateTaskResultSchema = ResultSchema.extend({ - task: TaskSchema -}); -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/tasks/status'), - params: TaskStatusNotificationParamsSchema -}); -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal('tasks/get'), - params: BaseRequestParamsSchema.extend({ - taskId: string$1() - }) -}); -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal('tasks/result'), - params: BaseRequestParamsSchema.extend({ - taskId: string$1() - }) -}); -ResultSchema.loose(); -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ - method: literal('tasks/list') -}); -const ListTasksResultSchema = PaginatedResultSchema.extend({ - tasks: array(TaskSchema) -}); -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal('tasks/cancel'), - params: BaseRequestParamsSchema.extend({ - taskId: string$1() - }) -}); -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ResourceContentsSchema = object({ - uri: string$1(), - mimeType: optional(string$1()), - _meta: record(string$1(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ - text: string$1() -}); -const Base64Schema = string$1().refine(val => { - try { - atob(val); - return true; - } - catch { - return false; - } -}, { message: 'Invalid Base64 string' }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ - blob: Base64Schema -}); -const RoleSchema = _enum$1(['user', 'assistant']); -const AnnotationsSchema = object({ - audience: array(RoleSchema).optional(), - priority: number$1().min(0).max(1).optional(), - lastModified: datetime({ offset: true }).optional() -}); -const ResourceSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: string$1(), - description: optional(string$1()), - mimeType: optional(string$1()), - annotations: AnnotationsSchema.optional(), - _meta: optional(looseObject({})) -}); -const ResourceTemplateSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: string$1(), - description: optional(string$1()), - mimeType: optional(string$1()), - annotations: AnnotationsSchema.optional(), - _meta: optional(looseObject({})) -}); -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: literal('resources/list') -}); -const ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: array(ResourceSchema) -}); -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: literal('resources/templates/list') -}); -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: array(ResourceTemplateSchema) -}); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - uri: string$1() -}); -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal('resources/read'), - params: ReadResourceRequestParamsSchema -}); -const ReadResourceResultSchema = ResultSchema.extend({ - contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/resources/list_changed'), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal('resources/subscribe'), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal('resources/unsubscribe'), - params: UnsubscribeRequestParamsSchema -}); -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - uri: string$1() -}); -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/resources/updated'), - params: ResourceUpdatedNotificationParamsSchema -}); -const PromptArgumentSchema = object({ - name: string$1(), - description: optional(string$1()), - required: optional(boolean$1()) -}); -const PromptSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: optional(string$1()), - arguments: optional(array(PromptArgumentSchema)), - _meta: optional(looseObject({})) -}); -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: literal('prompts/list') -}); -const ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: array(PromptSchema) -}); -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: string$1(), - arguments: record(string$1(), string$1()).optional() -}); -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal('prompts/get'), - params: GetPromptRequestParamsSchema -}); -const TextContentSchema = object({ - type: literal('text'), - text: string$1(), - annotations: AnnotationsSchema.optional(), - _meta: record(string$1(), unknown()).optional() -}); -const ImageContentSchema = object({ - type: literal('image'), - data: Base64Schema, - mimeType: string$1(), - annotations: AnnotationsSchema.optional(), - _meta: record(string$1(), unknown()).optional() -}); -const AudioContentSchema = object({ - type: literal('audio'), - data: Base64Schema, - mimeType: string$1(), - annotations: AnnotationsSchema.optional(), - _meta: record(string$1(), unknown()).optional() -}); -const ToolUseContentSchema = object({ - type: literal('tool_use'), - name: string$1(), - id: string$1(), - input: record(string$1(), unknown()), - _meta: record(string$1(), unknown()).optional() -}); -const EmbeddedResourceSchema = object({ - type: literal('resource'), - resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: record(string$1(), unknown()).optional() -}); -const ResourceLinkSchema = ResourceSchema.extend({ - type: literal('resource_link') -}); -const ContentBlockSchema = union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -const PromptMessageSchema = object({ - role: RoleSchema, - content: ContentBlockSchema -}); -const GetPromptResultSchema = ResultSchema.extend({ - description: string$1().optional(), - messages: array(PromptMessageSchema) -}); -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/prompts/list_changed'), - params: NotificationsParamsSchema.optional() -}); -const ToolAnnotationsSchema = object({ - title: string$1().optional(), - readOnlyHint: boolean$1().optional(), - destructiveHint: boolean$1().optional(), - idempotentHint: boolean$1().optional(), - openWorldHint: boolean$1().optional() -}); -const ToolExecutionSchema = object({ - taskSupport: _enum$1(['required', 'optional', 'forbidden']).optional() -}); -const ToolSchema = object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: string$1().optional(), - inputSchema: object({ - type: literal('object'), - properties: record(string$1(), AssertObjectSchema).optional(), - required: array(string$1()).optional() - }) - .catchall(unknown()), - outputSchema: object({ - type: literal('object'), - properties: record(string$1(), AssertObjectSchema).optional(), - required: array(string$1()).optional() - }) - .catchall(unknown()) - .optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: record(string$1(), unknown()).optional() -}); -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: literal('tools/list') -}); -const ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: array(ToolSchema) -}); -const CallToolResultSchema = ResultSchema.extend({ - content: array(ContentBlockSchema).default([]), - structuredContent: record(string$1(), unknown()).optional(), - isError: boolean$1().optional() -}); -CallToolResultSchema.or(ResultSchema.extend({ - toolResult: unknown() -})); -const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - name: string$1(), - arguments: record(string$1(), unknown()).optional() -}); -const CallToolRequestSchema = RequestSchema.extend({ - method: literal('tools/call'), - params: CallToolRequestParamsSchema -}); -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/tools/list_changed'), - params: NotificationsParamsSchema.optional() -}); -object({ - autoRefresh: boolean$1().default(true), - debounceMs: number$1().int().nonnegative().default(300) -}); -const LoggingLevelSchema = _enum$1(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ - level: LoggingLevelSchema -}); -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal('logging/setLevel'), - params: SetLevelRequestParamsSchema -}); -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: string$1().optional(), - data: unknown() -}); -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/message'), - params: LoggingMessageNotificationParamsSchema -}); -const ModelHintSchema = object({ - name: string$1().optional() -}); -const ModelPreferencesSchema = object({ - hints: array(ModelHintSchema).optional(), - costPriority: number$1().min(0).max(1).optional(), - speedPriority: number$1().min(0).max(1).optional(), - intelligencePriority: number$1().min(0).max(1).optional() -}); -const ToolChoiceSchema = object({ - mode: _enum$1(['auto', 'required', 'none']).optional() -}); -const ToolResultContentSchema = object({ - type: literal('tool_result'), - toolUseId: string$1().describe('The unique identifier for the corresponding tool call.'), - content: array(ContentBlockSchema).default([]), - structuredContent: object({}).loose().optional(), - isError: boolean$1().optional(), - _meta: record(string$1(), unknown()).optional() -}); -const SamplingContentSchema = discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); -const SamplingMessageContentBlockSchema = discriminatedUnion('type', [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -const SamplingMessageSchema = object({ - role: RoleSchema, - content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), - _meta: record(string$1(), unknown()).optional() -}); -const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - messages: array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: string$1().optional(), - includeContext: _enum$1(['none', 'thisServer', 'allServers']).optional(), - temperature: number$1().optional(), - maxTokens: number$1().int(), - stopSequences: array(string$1()).optional(), - metadata: AssertObjectSchema.optional(), - tools: array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal('sampling/createMessage'), - params: CreateMessageRequestParamsSchema -}); -const CreateMessageResultSchema = ResultSchema.extend({ - model: string$1(), - stopReason: optional(_enum$1(['endTurn', 'stopSequence', 'maxTokens']).or(string$1())), - role: RoleSchema, - content: SamplingContentSchema -}); -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: string$1(), - stopReason: optional(_enum$1(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(string$1())), - role: RoleSchema, - content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) -}); -const BooleanSchemaSchema = object({ - type: literal('boolean'), - title: string$1().optional(), - description: string$1().optional(), - default: boolean$1().optional() -}); -const StringSchemaSchema = object({ - type: literal('string'), - title: string$1().optional(), - description: string$1().optional(), - minLength: number$1().optional(), - maxLength: number$1().optional(), - format: _enum$1(['email', 'uri', 'date', 'date-time']).optional(), - default: string$1().optional() -}); -const NumberSchemaSchema = object({ - type: _enum$1(['number', 'integer']), - title: string$1().optional(), - description: string$1().optional(), - minimum: number$1().optional(), - maximum: number$1().optional(), - default: number$1().optional() -}); -const UntitledSingleSelectEnumSchemaSchema = object({ - type: literal('string'), - title: string$1().optional(), - description: string$1().optional(), - enum: array(string$1()), - default: string$1().optional() -}); -const TitledSingleSelectEnumSchemaSchema = object({ - type: literal('string'), - title: string$1().optional(), - description: string$1().optional(), - oneOf: array(object({ - const: string$1(), - title: string$1() - })), - default: string$1().optional() -}); -const LegacyTitledEnumSchemaSchema = object({ - type: literal('string'), - title: string$1().optional(), - description: string$1().optional(), - enum: array(string$1()), - enumNames: array(string$1()).optional(), - default: string$1().optional() -}); -const SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -const UntitledMultiSelectEnumSchemaSchema = object({ - type: literal('array'), - title: string$1().optional(), - description: string$1().optional(), - minItems: number$1().optional(), - maxItems: number$1().optional(), - items: object({ - type: literal('string'), - enum: array(string$1()) - }), - default: array(string$1()).optional() -}); -const TitledMultiSelectEnumSchemaSchema = object({ - type: literal('array'), - title: string$1().optional(), - description: string$1().optional(), - minItems: number$1().optional(), - maxItems: number$1().optional(), - items: object({ - anyOf: array(object({ - const: string$1(), - title: string$1() - })) - }), - default: array(string$1()).optional() -}); -const MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -const EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); -const PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); -const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - mode: literal('form').optional(), - message: string$1(), - requestedSchema: object({ - type: literal('object'), - properties: record(string$1(), PrimitiveSchemaDefinitionSchema), - required: array(string$1()).optional() - }) -}); -const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - mode: literal('url'), - message: string$1(), - elicitationId: string$1(), - url: string$1().url() -}); -const ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -const ElicitRequestSchema = RequestSchema.extend({ - method: literal('elicitation/create'), - params: ElicitRequestParamsSchema -}); -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - elicitationId: string$1() -}); -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/elicitation/complete'), - params: ElicitationCompleteNotificationParamsSchema -}); -const ElicitResultSchema = ResultSchema.extend({ - action: _enum$1(['accept', 'decline', 'cancel']), - content: preprocess(val => (val === null ? undefined : val), record(string$1(), union([string$1(), number$1(), boolean$1(), array(string$1())])).optional()) -}); -const ResourceTemplateReferenceSchema = object({ - type: literal('ref/resource'), - uri: string$1() -}); -const PromptReferenceSchema = object({ - type: literal('ref/prompt'), - name: string$1() -}); -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: object({ - name: string$1(), - value: string$1() - }), - context: object({ - arguments: record(string$1(), string$1()).optional() - }) - .optional() -}); -const CompleteRequestSchema = RequestSchema.extend({ - method: literal('completion/complete'), - params: CompleteRequestParamsSchema -}); -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== 'ref/prompt') { - throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); - } -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== 'ref/resource') { - throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); - } -} -const CompleteResultSchema = ResultSchema.extend({ - completion: looseObject({ - values: array(string$1()).max(100), - total: optional(number$1().int()), - hasMore: optional(boolean$1()) - }) -}); -const RootSchema = object({ - uri: string$1().startsWith('file://'), - name: string$1().optional(), - _meta: record(string$1(), unknown()).optional() -}); -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal('roots/list'), - params: BaseRequestParamsSchema.optional() -}); -const ListRootsResultSchema = ResultSchema.extend({ - roots: array(RootSchema) -}); -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal('notifications/roots/list_changed'), - params: NotificationsParamsSchema.optional() -}); -union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); -union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema, - TaskStatusNotificationSchema -]); -union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); -union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); -union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - TaskStatusNotificationSchema, - ElicitationCompleteNotificationSchema -]); -union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); -class McpError extends Error { - constructor(code, message, data) { - super(`MCP error ${code}: ${message}`); - this.code = code; - this.data = data; - this.name = 'McpError'; - } - static fromError(code, message, data) { - if (code === ErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) { - return new UrlElicitationRequiredError(errorData.elicitations, message); - } - } - return new McpError(code, message, data); - } -} -class UrlElicitationRequiredError extends McpError { - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { - super(ErrorCode.UrlElicitationRequired, message, { - elicitations: elicitations - }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -} - -function isTerminal(status) { - return status === 'completed' || status === 'failed' || status === 'cancelled'; -} - -const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); -const defaultOptions = { - name: undefined, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", - openAiAnyTypeName: "OpenAiAnyType" -}; -const getDefaultOptions = (options) => (typeof options === "string" - ? { - ...defaultOptions, - name: options, - } - : { - ...defaultOptions, - ...options, - }); - -const getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== undefined - ? [..._options.basePath, _options.definitionPath, _options.name] - : _options.basePath; - return { - ..._options, - flags: { hasReferencedOpenAiAnyType: false }, - currentPath: currentPath, - propertyPath: undefined, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - def._def, - { - def: def._def, - path: [..._options.basePath, _options.definitionPath, name], - jsonSchema: undefined, - }, - ])), - }; -}; - -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage, - }; - } -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); -} - -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; - -function parseAnyDef(refs) { - if (refs.target !== "openAi") { - return {}; - } - const anyDefinitionPath = [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName, - ]; - refs.flags.hasReferencedOpenAiAnyType = true; - return { - $ref: refs.$refStrategy === "relative" - ? getRelativePath(anyDefinitionPath, refs.currentPath) - : anyDefinitionPath.join("/"), - }; -} - -function parseArrayDef(def, refs) { - const res = { - type: "array", - }; - if (def.type?._def && - def.type?._def?.typeName !== ZodFirstPartyTypeKind$1.ZodAny) { - res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"], - }); - } - if (def.minLength) { - setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); - } - if (def.maxLength) { - setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - } - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; -} - -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64", - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} - -function parseBooleanDef() { - return { - type: "boolean", - }; -} - -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); -} - -const parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), - }; - } - switch (strategy) { - case "string": - case "format:date-time": - return { - type: "string", - format: "date-time", - }; - case "format:date": - return { - type: "string", - format: "date", - }; - case "integer": - return integerDateParser(def, refs); - } -} -const integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time", - }; - if (refs.target === "openApi3") { - return res; - } - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minimum", check.value, - check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maximum", check.value, - check.message, refs); - break; - } - } - return res; -}; - -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue(), - }; -} - -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" - ? parseDef(_def.schema._def, refs) - : parseAnyDef(refs); -} - -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values), - }; -} - -const isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") - return false; - return "allOf" in type; -}; -function parseIntersectionDef(def, refs) { - const allOf = [ - parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"], - }), - parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "1"], - }), - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" - ? { unevaluatedProperties: false } - : undefined; - const mergedAllOf = []; - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === undefined) { - unevaluatedProperties = undefined; - } - } - else { - let nestedSchema = schema; - if ("additionalProperties" in schema && - schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; - } - else { - unevaluatedProperties = undefined; - } - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length - ? { - allOf: mergedAllOf, - ...unevaluatedProperties, - } - : undefined; -} - -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && - parsedType !== "number" && - parsedType !== "boolean" && - parsedType !== "string") { - return { - type: Array.isArray(def.value) ? "array" : "object", - }; - } - if (refs.target === "openApi3") { - return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value], - }; - } - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value, - }; -} - -let emojiRegex$1 = undefined; -const zodPatterns = { - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - emoji: () => { - if (emojiRegex$1 === undefined) { - emojiRegex$1 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - } - return emojiRegex$1; - }, - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, -}; -function parseStringDef(def, refs) { - const res = { - type: "string", - }; - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" - ? Math.max(res.minLength, check.value) - : check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" - ? Math.min(res.maxLength, check.value) - : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex, check.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "date": - addFormat(res, "date", check.message, refs); - break; - case "time": - addFormat(res, "time", check.message, refs); - break; - case "duration": - addFormat(res, "duration", check.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" - ? Math.max(res.minLength, check.value) - : check.value, check.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" - ? Math.min(res.maxLength, check.value) - : check.value, check.message, refs); - break; - case "includes": { - addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); - break; - } - case "ip": { - if (check.version !== "v6") { - addFormat(res, "ipv4", check.message, refs); - } - if (check.version !== "v4") { - addFormat(res, "ipv6", check.message, refs); - } - break; - } - case "base64url": - addPattern(res, zodPatterns.base64url, check.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check.message, refs); - break; - case "cidr": { - if (check.version !== "v6") { - addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); - } - if (check.version !== "v4") { - addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); - } - break; - } - case "emoji": - addPattern(res, zodPatterns.emoji(), check.message, refs); - break; - case "ulid": { - addPattern(res, zodPatterns.ulid, check.message, refs); - break; - } - case "base64": { - switch (refs.base64Strategy) { - case "format:binary": { - addFormat(res, "binary", check.message, refs); - break; - } - case "contentEncoding:base64": { - setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); - break; - } - case "pattern:zod": { - addPattern(res, zodPatterns.base64, check.message, refs); - break; - } - } - break; - } - case "nanoid": { - addPattern(res, zodPatterns.nanoid, check.message, refs); - } - } - } - } - return res; -} -function escapeLiteralCheckValue(literal, refs) { - return refs.patternStrategy === "escape" - ? escapeNonAlphaNumeric(literal) - : literal; -} -const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i = 0; i < source.length; i++) { - if (!ALPHA_NUMERIC.has(source[i])) { - result += "\\"; - } - result += source[i]; - } - return result; -} -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) { - schema.anyOf = []; - } - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format }, - }), - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.anyOf.push({ - format: value, - ...(message && - refs.errorMessages && { errorMessage: { format: message } }), - }); - } - else { - setResponseValueAndErrors(schema, "format", value, message, refs); - } -} -function addPattern(schema, regex, message, refs) { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) { - schema.allOf = []; - } - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern }, - }), - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...(message && - refs.errorMessages && { errorMessage: { pattern: message } }), - }); - } - else { - setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); - } -} -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) { - return regex.source; - } - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s"), - }; - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } - else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } - else { - pattern += `${source[i]}${source[i].toUpperCase()}`; - } - continue; - } - } - else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i] === "^") { - pattern += `(^|(?<=[\r\n]))`; - continue; - } - else if (source[i] === "$") { - pattern += `($|(?=[\r\n]))`; - continue; - } - } - if (flags.s && source[i] === ".") { - pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; - continue; - } - pattern += source[i]; - if (source[i] === "\\") { - isEscaped = true; - } - else if (inCharGroup && source[i] === "]") { - inCharGroup = false; - } - else if (!inCharGroup && source[i] === "[") { - inCharGroup = true; - } - } - try { - new RegExp(pattern); - } - catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -} - -function parseRecordDef(def, refs) { - if (refs.target === "openAi") { - console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - } - if (refs.target === "openApi3" && - def.keyType?._def.typeName === ZodFirstPartyTypeKind$1.ZodEnum) { - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", key], - }) ?? parseAnyDef(refs), - }), {}), - additionalProperties: refs.rejectedAdditionalProperties, - }; - } - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"], - }) ?? refs.allowedAdditionalProperties, - }; - if (refs.target === "openApi3") { - return schema; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind$1.ZodString && - def.keyType._def.checks?.length) { - const { type, ...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType, - }; - } - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind$1.ZodEnum) { - return { - ...schema, - propertyNames: { - enum: def.keyType._def.values, - }, - }; - } - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind$1.ZodBranded && - def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind$1.ZodString && - def.keyType._def.type._def.checks?.length) { - const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType, - }; - } - return schema; -} - -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") { - return parseRecordDef(def, refs); - } - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "0"], - }) || parseAnyDef(refs); - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "1"], - }) || parseAnyDef(refs); - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2, - }, - }; -} - -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 - ? parsedTypes[0] === "string" - ? "string" - : "number" - : ["string", "number"], - enum: actualValues, - }; -} - -function parseNeverDef(refs) { - return refs.target === "openAi" - ? undefined - : { - not: parseAnyDef({ - ...refs, - currentPath: [...refs.currentPath, "not"], - }), - }; -} - -function parseNullDef(refs) { - return refs.target === "openApi3" - ? { - enum: ["null"], - nullable: true, - } - : { - type: "null", - }; -} - -const primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null", -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x) => x._def.typeName in primitiveMappings && - (!x._def.checks || !x._def.checks.length))) { - const types = options.reduce((types, x) => { - const type = primitiveMappings[x._def.typeName]; - return type && !types.includes(type) ? [...types, type] : types; - }, []); - return { - type: types.length > 1 ? types : types[0], - }; - } - else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": - return [...acc, type]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x._def.value === null) - return [...acc, "null"]; - case "symbol": - case "undefined": - case "function": - default: - return acc; - } - }, []); - if (types.length === options.length) { - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []), - }; - } - } - else if (options.every((x) => x._def.typeName === "ZodEnum")) { - return { - type: "string", - enum: options.reduce((acc, x) => [ - ...acc, - ...x._def.values.filter((x) => !acc.includes(x)), - ], []), - }; - } - return asAnyOf(def, refs); -} -const asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map - ? Array.from(def.options.values()) - : def.options) - .map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", `${i}`], - })) - .filter((x) => !!x && - (!refs.strictUnions || - (typeof x === "object" && Object.keys(x).length > 0))); - return anyOf.length ? { anyOf } : undefined; -}; - -function parseNullableDef(def, refs) { - if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && - (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") { - return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true, - }; - } - return { - type: [ - primitiveMappings[def.innerType._def.typeName], - "null", - ], - }; - } - if (refs.target === "openApi3") { - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath], - }); - if (base && "$ref" in base) - return { allOf: [base], nullable: true }; - return base && { ...base, nullable: true }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "0"], - }); - return base && { anyOf: [base, { type: "null" }] }; -} - -function parseNumberDef(def, refs) { - const res = { - type: "number", - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} - -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {}, - }; - const required = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === undefined || propDef._def === undefined) { - continue; - } - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef._def.typeName === "ZodOptional") { - propDef = propDef._def.innerType; - } - if (!propDef.isNullable()) { - propDef = propDef.nullable(); - } - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", propName], - propertyPath: [...refs.currentPath, "properties", propName], - }); - if (parsedDef === undefined) { - continue; - } - result.properties[propName] = parsedDef; - if (!propOptional) { - required.push(propName); - } - } - if (required.length) { - result.required = required; - } - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== undefined) { - result.additionalProperties = additionalProperties; - } - return result; -} -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") { - return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"], - }); - } - switch (def.unknownKeys) { - case "passthrough": - return refs.allowedAdditionalProperties; - case "strict": - return refs.rejectedAdditionalProperties; - case "strip": - return refs.removeAdditionalStrategy === "strict" - ? refs.allowedAdditionalProperties - : refs.rejectedAdditionalProperties; - } -} -function safeIsOptional(schema) { - try { - return schema.isOptional(); - } - catch { - return true; - } -} - -const parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) { - return parseDef(def.innerType._def, refs); - } - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "1"], - }); - return innerSchema - ? { - anyOf: [ - { - not: parseAnyDef(refs), - }, - innerSchema, - ], - } - : parseAnyDef(refs); -}; - -const parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") { - return parseDef(def.in._def, refs); - } - else if (refs.pipeStrategy === "output") { - return parseDef(def.out._def, refs); - } - const a = parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"], - }); - const b = parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"], - }); - return { - allOf: [a, b].filter((x) => x !== undefined), - }; -}; - -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); -} - -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"], - }); - const schema = { - type: "array", - uniqueItems: true, - items, - }; - if (def.minSize) { - setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} - -function parseTupleDef(def, refs) { - if (def.rest) { - return { - type: "array", - minItems: def.items.length, - items: def.items - .map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"], - }), - }; - } - else { - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items - .map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - }; - } -} - -function parseUndefinedDef(refs) { - return { - not: parseAnyDef(refs), - }; -} - -function parseUnknownDef(refs) { - return parseAnyDef(refs); -} - -const parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -const selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind$1.ZodString: - return parseStringDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodNumber: - return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodObject: - return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodBigInt: - return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodBoolean: - return parseBooleanDef(); - case ZodFirstPartyTypeKind$1.ZodDate: - return parseDateDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodUndefined: - return parseUndefinedDef(refs); - case ZodFirstPartyTypeKind$1.ZodNull: - return parseNullDef(refs); - case ZodFirstPartyTypeKind$1.ZodArray: - return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodUnion: - case ZodFirstPartyTypeKind$1.ZodDiscriminatedUnion: - return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodIntersection: - return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodTuple: - return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodRecord: - return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodLiteral: - return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind$1.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind$1.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodLazy: - return () => def.getter()._def; - case ZodFirstPartyTypeKind$1.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodNaN: - case ZodFirstPartyTypeKind$1.ZodNever: - return parseNeverDef(refs); - case ZodFirstPartyTypeKind$1.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodAny: - return parseAnyDef(refs); - case ZodFirstPartyTypeKind$1.ZodUnknown: - return parseUnknownDef(refs); - case ZodFirstPartyTypeKind$1.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind$1.ZodFunction: - case ZodFirstPartyTypeKind$1.ZodVoid: - case ZodFirstPartyTypeKind$1.ZodSymbol: - return undefined; - default: - return ((_) => undefined)(); - } -}; - -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== undefined) { - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - const jsonSchema = typeof jsonSchemaOrGetter === "function" - ? parseDef(jsonSchemaOrGetter(), refs) - : jsonSchemaOrGetter; - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -const get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return parseAnyDef(refs); - } - return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; - } - } -}; -const addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; - -const zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - let definitions = typeof options === "object" && options.definitions - ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ - ...acc, - [name]: parseDef(schema._def, { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }, true) ?? parseAnyDef(refs), - }), {}) - : undefined; - const name = typeof options === "string" - ? options - : options?.nameStrategy === "title" - ? undefined - : options?.name; - const main = parseDef(schema._def, name === undefined - ? refs - : { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }, false) ?? parseAnyDef(refs); - const title = typeof options === "object" && - options.name !== undefined && - options.nameStrategy === "title" - ? options.name - : undefined; - if (title !== undefined) { - main.title = title; - } - if (refs.flags.hasReferencedOpenAiAnyType) { - if (!definitions) { - definitions = {}; - } - if (!definitions[refs.openAiAnyTypeName]) { - definitions[refs.openAiAnyTypeName] = { - type: ["string", "number", "integer", "boolean", "array", "null"], - items: { - $ref: refs.$refStrategy === "relative" - ? "1" - : [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName, - ].join("/"), - }, - }; - } - } - const combined = name === undefined - ? definitions - ? { - ...main, - [refs.definitionPath]: definitions, - } - : main - : { - $ref: [ - ...(refs.$refStrategy === "relative" ? [] : refs.basePath), - refs.definitionPath, - name, - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main, - }, - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - } - if (refs.target === "openAi" && - ("anyOf" in combined || - "oneOf" in combined || - "allOf" in combined || - ("type" in combined && Array.isArray(combined.type)))) { - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - } - return combined; -}; - -function mapMiniTarget(t) { - if (!t) - return 'draft-7'; - if (t === 'jsonSchema7' || t === 'draft-7') - return 'draft-7'; - if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') - return 'draft-2020-12'; - return 'draft-7'; -} -function toJsonSchemaCompat(schema, opts) { - if (isZ4Schema(schema)) { - return toJSONSchema(schema, { - target: mapMiniTarget(opts?.target), - io: opts?.pipeStrategy ?? 'input' - }); - } - return zodToJsonSchema(schema, { - strictUnions: opts?.strictUnions ?? true, - pipeStrategy: opts?.pipeStrategy ?? 'input' - }); -} -function getMethodLiteral(schema) { - const shape = getObjectShape(schema); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - const value = getLiteralValue(methodSchema); - if (typeof value !== 'string') { - throw new Error('Schema method literal must be a string'); - } - return value; -} -function parseWithCompat(schema, data) { - const result = safeParse$1(schema, data); - if (!result.success) { - throw result.error; - } - return result.data; -} - -const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; -class Protocol { - constructor(_options) { - this._options = _options; - this._requestMessageId = 0; - this._requestHandlers = new Map(); - this._requestHandlerAbortControllers = new Map(); - this._notificationHandlers = new Map(); - this._responseHandlers = new Map(); - this._progressHandlers = new Map(); - this._timeoutInfo = new Map(); - this._pendingDebouncedNotifications = new Set(); - this._taskProgressTokens = new Map(); - this._requestResolvers = new Map(); - this.setNotificationHandler(CancelledNotificationSchema, notification => { - this._oncancel(notification); - }); - this.setNotificationHandler(ProgressNotificationSchema, notification => { - this._onprogress(notification); - }); - this.setRequestHandler(PingRequestSchema, - _request => ({})); - this._taskStore = _options?.taskStore; - this._taskMessageQueue = _options?.taskMessageQueue; - if (this._taskStore) { - this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { - const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); - } - return { - ...task - }; - }); - this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { - const handleTaskResult = async () => { - const taskId = request.params.taskId; - if (this._taskMessageQueue) { - let queuedMessage; - while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) { - if (queuedMessage.type === 'response' || queuedMessage.type === 'error') { - const message = queuedMessage.message; - const requestId = message.id; - const resolver = this._requestResolvers.get(requestId); - if (resolver) { - this._requestResolvers.delete(requestId); - if (queuedMessage.type === 'response') { - resolver(message); - } - else { - const errorMessage = message; - const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); - resolver(error); - } - } - else { - const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error'; - this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); - } - continue; - } - await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); - } - } - const task = await this._taskStore.getTask(taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); - } - if (!isTerminal(task.status)) { - await this._waitForTaskUpdate(taskId, extra.signal); - return await handleTaskResult(); - } - if (isTerminal(task.status)) { - const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); - this._clearTaskQueue(taskId); - return { - ...result, - _meta: { - ...result._meta, - [RELATED_TASK_META_KEY]: { - taskId: taskId - } - } - }; - } - return await handleTaskResult(); - }; - return await handleTaskResult(); - }); - this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { - try { - const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); - return { - tasks, - nextCursor, - _meta: {} - }; - } - catch (error) { - throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); - } - }); - this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { - try { - const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); - } - if (isTerminal(task.status)) { - throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); - } - await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId); - this._clearTaskQueue(request.params.taskId); - const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!cancelledTask) { - throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); - } - return { - _meta: {}, - ...cancelledTask - }; - } - catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); - } - }); - } - } - async _oncancel(notification) { - if (!notification.params.requestId) { - return; - } - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) - return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - async connect(transport) { - if (this._transport) { - throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.'); - } - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - _onclose?.(); - this._onclose(); - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._onresponse(message); - } - else if (isJSONRPCRequest(message)) { - this._onrequest(message, extra); - } - else if (isJSONRPCNotification(message)) { - this._onnotification(message); - } - else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); - } - }; - await this._transport.start(); - } - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = new Map(); - this._progressHandlers.clear(); - this._taskProgressTokens.clear(); - this._pendingDebouncedNotifications.clear(); - for (const controller of this._requestHandlerAbortControllers.values()) { - controller.abort(); - } - this._requestHandlerAbortControllers.clear(); - const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); - this._transport = undefined; - this.onclose?.(); - for (const handler of responseHandlers.values()) { - handler(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - _onnotification(notification) { - const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; - if (handler === undefined) { - return; - } - Promise.resolve() - .then(() => handler(notification)) - .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(request, extra) { - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - const capturedTransport = this._transport; - const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; - if (handler === undefined) { - const errorResponse = { - jsonrpc: '2.0', - id: request.id, - error: { - code: ErrorCode.MethodNotFound, - message: 'Method not found' - } - }; - if (relatedTaskId && this._taskMessageQueue) { - this._enqueueTaskMessage(relatedTaskId, { - type: 'error', - message: errorResponse, - timestamp: Date.now() - }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`))); - } - else { - capturedTransport - ?.send(errorResponse) - .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); - } - return; - } - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined; - const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; - const fullExtra = { - signal: abortController.signal, - sessionId: capturedTransport?.sessionId, - _meta: request.params?._meta, - sendNotification: async (notification) => { - if (abortController.signal.aborted) - return; - const notificationOptions = { relatedRequestId: request.id }; - if (relatedTaskId) { - notificationOptions.relatedTask = { taskId: relatedTaskId }; - } - await this.notification(notification, notificationOptions); - }, - sendRequest: async (r, resultSchema, options) => { - if (abortController.signal.aborted) { - throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled'); - } - const requestOptions = { ...options, relatedRequestId: request.id }; - if (relatedTaskId && !requestOptions.relatedTask) { - requestOptions.relatedTask = { taskId: relatedTaskId }; - } - const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; - if (effectiveTaskId && taskStore) { - await taskStore.updateTaskStatus(effectiveTaskId, 'input_required'); - } - return await this.request(r, resultSchema, requestOptions); - }, - authInfo: extra?.authInfo, - requestId: request.id, - requestInfo: extra?.requestInfo, - taskId: relatedTaskId, - taskStore: taskStore, - taskRequestedTtl: taskCreationParams?.ttl, - closeSSEStream: extra?.closeSSEStream, - closeStandaloneSSEStream: extra?.closeStandaloneSSEStream - }; - Promise.resolve() - .then(() => { - if (taskCreationParams) { - this.assertTaskHandlerCapability(request.method); - } - }) - .then(() => handler(request, fullExtra)) - .then(async (result) => { - if (abortController.signal.aborted) { - return; - } - const response = { - result, - jsonrpc: '2.0', - id: request.id - }; - if (relatedTaskId && this._taskMessageQueue) { - await this._enqueueTaskMessage(relatedTaskId, { - type: 'response', - message: response, - timestamp: Date.now() - }, capturedTransport?.sessionId); - } - else { - await capturedTransport?.send(response); - } - }, async (error) => { - if (abortController.signal.aborted) { - return; - } - const errorResponse = { - jsonrpc: '2.0', - id: request.id, - error: { - code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, - message: error.message ?? 'Internal error', - ...(error['data'] !== undefined && { data: error['data'] }) - } - }; - if (relatedTaskId && this._taskMessageQueue) { - await this._enqueueTaskMessage(relatedTaskId, { - type: 'error', - message: errorResponse, - timestamp: Date.now() - }, capturedTransport?.sessionId); - } - else { - await capturedTransport?.send(errorResponse); - } - }) - .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) - .finally(() => { - this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { - try { - this._resetTimeout(messageId); - } - catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - } - handler(params); - } - _onresponse(response) { - const messageId = Number(response.id); - const resolver = this._requestResolvers.get(messageId); - if (resolver) { - this._requestResolvers.delete(messageId); - if (isJSONRPCResultResponse(response)) { - resolver(response); - } - else { - const error = new McpError(response.error.code, response.error.message, response.error.data); - resolver(error); - } - return; - } - const handler = this._responseHandlers.get(messageId); - if (handler === undefined) { - this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - let isTaskResponse = false; - if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') { - const result = response.result; - if (result.task && typeof result.task === 'object') { - const task = result.task; - if (typeof task.taskId === 'string') { - isTaskResponse = true; - this._taskProgressTokens.set(task.taskId, messageId); - } - } - } - if (!isTaskResponse) { - this._progressHandlers.delete(messageId); - } - if (isJSONRPCResultResponse(response)) { - handler(response); - } - else { - const error = McpError.fromError(response.error.code, response.error.message, response.error.data); - handler(error); - } - } - get transport() { - return this._transport; - } - async close() { - await this._transport?.close(); - } - async *requestStream(request, resultSchema, options) { - const { task } = options ?? {}; - if (!task) { - try { - const result = await this.request(request, resultSchema, options); - yield { type: 'result', result }; - } - catch (error) { - yield { - type: 'error', - error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) - }; - } - return; - } - let taskId; - try { - const createResult = await this.request(request, CreateTaskResultSchema, options); - if (createResult.task) { - taskId = createResult.task.taskId; - yield { type: 'taskCreated', task: createResult.task }; - } - else { - throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task'); - } - while (true) { - const task = await this.getTask({ taskId }, options); - yield { type: 'taskStatus', task }; - if (isTerminal(task.status)) { - if (task.status === 'completed') { - const result = await this.getTaskResult({ taskId }, resultSchema, options); - yield { type: 'result', result }; - } - else if (task.status === 'failed') { - yield { - type: 'error', - error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) - }; - } - else if (task.status === 'cancelled') { - yield { - type: 'error', - error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) - }; - } - return; - } - if (task.status === 'input_required') { - const result = await this.getTaskResult({ taskId }, resultSchema, options); - yield { type: 'result', result }; - return; - } - const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000; - await new Promise(resolve => setTimeout(resolve, pollInterval)); - options?.signal?.throwIfAborted(); - } - } - catch (error) { - yield { - type: 'error', - error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) - }; - } - } - request(request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(new Error('Not connected')); - return; - } - if (this._options?.enforceStrictCapabilities === true) { - try { - this.assertCapabilityForMethod(request.method); - if (task) { - this.assertTaskCapability(request.method); - } - } - catch (e) { - earlyReject(e); - return; - } - } - options?.signal?.throwIfAborted(); - const messageId = this._requestMessageId++; - const jsonrpcRequest = { - ...request, - jsonrpc: '2.0', - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...(request.params?._meta || {}), - progressToken: messageId - } - }; - } - if (task) { - jsonrpcRequest.params = { - ...jsonrpcRequest.params, - task: task - }; - } - if (relatedTask) { - jsonrpcRequest.params = { - ...jsonrpcRequest.params, - _meta: { - ...(jsonrpcRequest.params?._meta || {}), - [RELATED_TASK_META_KEY]: relatedTask - } - }; - } - const cancel = (reason) => { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._transport - ?.send({ - jsonrpc: '2.0', - method: 'notifications/cancelled', - params: { - requestId: messageId, - reason: String(reason) - } - }, { relatedRequestId, resumptionToken, onresumptiontoken }) - .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); - const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); - reject(error); - }; - this._responseHandlers.set(messageId, response => { - if (options?.signal?.aborted) { - return; - } - if (response instanceof Error) { - return reject(response); - } - try { - const parseResult = safeParse$1(resultSchema, response.result); - if (!parseResult.success) { - reject(parseResult.error); - } - else { - resolve(parseResult.data); - } - } - catch (error) { - reject(error); - } - }); - options?.signal?.addEventListener('abort', () => { - cancel(options?.signal?.reason); - }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - const relatedTaskId = relatedTask?.taskId; - if (relatedTaskId) { - const responseResolver = (response) => { - const handler = this._responseHandlers.get(messageId); - if (handler) { - handler(response); - } - else { - this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); - } - }; - this._requestResolvers.set(messageId, responseResolver); - this._enqueueTaskMessage(relatedTaskId, { - type: 'request', - message: jsonrpcRequest, - timestamp: Date.now() - }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - } - else { - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - } - }); - } - async getTask(params, options) { - return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options); - } - async getTaskResult(params, resultSchema, options) { - return this.request({ method: 'tasks/result', params }, resultSchema, options); - } - async listTasks(params, options) { - return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options); - } - async cancelTask(params, options) { - return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options); - } - async notification(notification, options) { - if (!this._transport) { - throw new Error('Not connected'); - } - this.assertNotificationCapability(notification.method); - const relatedTaskId = options?.relatedTask?.taskId; - if (relatedTaskId) { - const jsonrpcNotification = { - ...notification, - jsonrpc: '2.0', - params: { - ...notification.params, - _meta: { - ...(notification.params?._meta || {}), - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - await this._enqueueTaskMessage(relatedTaskId, { - type: 'notification', - message: jsonrpcNotification, - timestamp: Date.now() - }); - return; - } - const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; - const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; - if (canDebounce) { - if (this._pendingDebouncedNotifications.has(notification.method)) { - return; - } - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) { - return; - } - let jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - if (options?.relatedTask) { - jsonrpcNotification = { - ...jsonrpcNotification, - params: { - ...jsonrpcNotification.params, - _meta: { - ...(jsonrpcNotification.params?._meta || {}), - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - } - this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); - }); - return; - } - let jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - if (options?.relatedTask) { - jsonrpcNotification = { - ...jsonrpcNotification, - params: { - ...jsonrpcNotification.params, - _meta: { - ...(jsonrpcNotification.params?._meta || {}), - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(requestSchema, handler) { - const method = getMethodLiteral(requestSchema); - this.assertRequestHandlerCapability(method); - this._requestHandlers.set(method, (request, extra) => { - const parsed = parseWithCompat(requestSchema, request); - return Promise.resolve(handler(parsed, extra)); - }); - } - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) { - throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - } - setNotificationHandler(notificationSchema, handler) { - const method = getMethodLiteral(notificationSchema); - this._notificationHandlers.set(method, notification => { - const parsed = parseWithCompat(notificationSchema, notification); - return Promise.resolve(handler(parsed)); - }); - } - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } - _cleanupTaskProgressHandler(taskId) { - const progressToken = this._taskProgressTokens.get(taskId); - if (progressToken !== undefined) { - this._progressHandlers.delete(progressToken); - this._taskProgressTokens.delete(taskId); - } - } - async _enqueueTaskMessage(taskId, message, sessionId) { - if (!this._taskStore || !this._taskMessageQueue) { - throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured'); - } - const maxQueueSize = this._options?.maxTaskQueueSize; - await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); - } - async _clearTaskQueue(taskId, sessionId) { - if (this._taskMessageQueue) { - const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); - for (const message of messages) { - if (message.type === 'request' && isJSONRPCRequest(message.message)) { - const requestId = message.message.id; - const resolver = this._requestResolvers.get(requestId); - if (resolver) { - resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed')); - this._requestResolvers.delete(requestId); - } - else { - this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); - } - } - } - } - } - async _waitForTaskUpdate(taskId, signal) { - let interval = this._options?.defaultTaskPollInterval ?? 1000; - try { - const task = await this._taskStore?.getTask(taskId); - if (task?.pollInterval) { - interval = task.pollInterval; - } - } - catch { - } - return new Promise((resolve, reject) => { - if (signal.aborted) { - reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); - return; - } - const timeoutId = setTimeout(resolve, interval); - signal.addEventListener('abort', () => { - clearTimeout(timeoutId); - reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); - }, { once: true }); - }); - } - requestTaskStore(request, sessionId) { - const taskStore = this._taskStore; - if (!taskStore) { - throw new Error('No task store configured'); - } - return { - createTask: async (taskParams) => { - if (!request) { - throw new Error('No request provided'); - } - return await taskStore.createTask(taskParams, request.id, { - method: request.method, - params: request.params - }, sessionId); - }, - getTask: async (taskId) => { - const task = await taskStore.getTask(taskId, sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); - } - return task; - }, - storeTaskResult: async (taskId, status, result) => { - await taskStore.storeTaskResult(taskId, status, result, sessionId); - const task = await taskStore.getTask(taskId, sessionId); - if (task) { - const notification = TaskStatusNotificationSchema.parse({ - method: 'notifications/tasks/status', - params: task - }); - await this.notification(notification); - if (isTerminal(task.status)) { - this._cleanupTaskProgressHandler(taskId); - } - } - }, - getTaskResult: taskId => { - return taskStore.getTaskResult(taskId, sessionId); - }, - updateTaskStatus: async (taskId, status, statusMessage) => { - const task = await taskStore.getTask(taskId, sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); - } - if (isTerminal(task.status)) { - throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); - } - await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); - const updatedTask = await taskStore.getTask(taskId, sessionId); - if (updatedTask) { - const notification = TaskStatusNotificationSchema.parse({ - method: 'notifications/tasks/status', - params: updatedTask - }); - await this.notification(notification); - if (isTerminal(updatedTask.status)) { - this._cleanupTaskProgressHandler(taskId); - } - } - }, - listTasks: cursor => { - return taskStore.listTasks(cursor, sessionId); - } - }; - } -} -function isPlainObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === undefined) - continue; - const baseValue = result[k]; - if (isPlainObject(baseValue) && isPlainObject(addValue)) { - result[k] = { ...baseValue, ...addValue }; - } - else { - result[k] = addValue; - } - } - return result; -} - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var ajv = {exports: {}}; - -var core$1 = {}; - -var validate$1 = {}; - -var boolSchema = {}; - -var errors = {}; - -var codegen = {}; - -var code$1 = {}; - -var hasRequiredCode$1; - -function requireCode$1 () { - if (hasRequiredCode$1) return code$1; - hasRequiredCode$1 = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.regexpCode = exports$1.getEsmExportName = exports$1.getProperty = exports$1.safeStringify = exports$1.stringify = exports$1.strConcat = exports$1.addCodeArg = exports$1.str = exports$1._ = exports$1.nil = exports$1._Code = exports$1.Name = exports$1.IDENTIFIER = exports$1._CodeOrName = void 0; - class _CodeOrName { - } - exports$1._CodeOrName = _CodeOrName; - exports$1.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - class Name extends _CodeOrName { - constructor(s) { - super(); - if (!exports$1.IDENTIFIER.test(s)) - throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - } - exports$1.Name = Name; - class _Code extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) - return false; - const item = this._items[0]; - return item === "" || item === '""'; - } - get str() { - var _a; - return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, ""))); - } - get names() { - var _a; - return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => { - if (c instanceof Name) - names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}))); - } - } - exports$1._Code = _Code; - exports$1.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports$1._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports$1.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) - code.push(...arg._items); - else if (arg instanceof Name) - code.push(arg); - else - code.push(interpolate(arg)); - } - exports$1.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== undefined) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === '""') - return a; - if (a === '""') - return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== '"') - return; - if (typeof b != "string") - return `${a.slice(0, -1)}${b}"`; - if (b[0] === '"') - return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) - return `"${a}${b.slice(1)}`; - return; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`; - } - exports$1.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null - ? x - : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports$1.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x) - .replace(/\u2028/g, "\\u2028") - .replace(/\u2029/g, "\\u2029"); - } - exports$1.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports$1.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`; - } - exports$1.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports$1.IDENTIFIER.test(key)) { - return new _Code(`${key}`); - } - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports$1.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports$1.regexpCode = regexpCode; - } (code$1)); - return code$1; -} - -var scope = {}; - -var hasRequiredScope; - -function requireScope () { - if (hasRequiredScope) return scope; - hasRequiredScope = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.ValueScope = exports$1.ValueScopeName = exports$1.Scope = exports$1.varKinds = exports$1.UsedValueState = void 0; - const code_1 = /*@__PURE__*/ requireCode$1(); - class ValueError extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - } - var UsedValueState; - (function (UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports$1.UsedValueState = UsedValueState = {})); - exports$1.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var"), - }; - class Scope { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) { - throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - } - return (this._names[prefix] = { prefix, index: 0 }); - } - } - exports$1.Scope = Scope; - class ValueScopeName extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`; - } - } - exports$1.ValueScopeName = ValueScopeName; - const line = (0, code_1._) `\n`; - class ValueScope extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === undefined) - throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) - return _name; - } - else { - vs = this._values[prefix] = new Map(); - } - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { property: prefix, itemIndex }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) - return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === undefined) - throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._) `${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === undefined) - throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) - continue; - const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map()); - vs.forEach((name) => { - if (nameSet.has(name)) - return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports$1.varKinds.var : exports$1.varKinds.const; - code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`; - } - else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) { - code = (0, code_1._) `${code}${c}${this.opts._n}`; - } - else { - throw new ValueError(name); - } - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - } - exports$1.ValueScope = ValueScope; - } (scope)); - return scope; -} - -var hasRequiredCodegen; - -function requireCodegen () { - if (hasRequiredCodegen) return codegen; - hasRequiredCodegen = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.or = exports$1.and = exports$1.not = exports$1.CodeGen = exports$1.operators = exports$1.varKinds = exports$1.ValueScopeName = exports$1.ValueScope = exports$1.Scope = exports$1.Name = exports$1.regexpCode = exports$1.stringify = exports$1.getProperty = exports$1.nil = exports$1.strConcat = exports$1.str = exports$1._ = void 0; - const code_1 = /*@__PURE__*/ requireCode$1(); - const scope_1 = /*@__PURE__*/ requireScope(); - var code_2 = /*@__PURE__*/ requireCode$1(); - Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return code_2._; } }); - Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return code_2.str; } }); - Object.defineProperty(exports$1, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } }); - Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return code_2.nil; } }); - Object.defineProperty(exports$1, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } }); - Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return code_2.stringify; } }); - Object.defineProperty(exports$1, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } }); - Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return code_2.Name; } }); - var scope_2 = /*@__PURE__*/ requireScope(); - Object.defineProperty(exports$1, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } }); - Object.defineProperty(exports$1, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } }); - Object.defineProperty(exports$1, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } }); - Object.defineProperty(exports$1, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } }); - exports$1.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+"), - }; - class Node { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - } - class Def extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) - return; - if (this.rhs) - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - } - class Assign extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) - return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; - return addExprNames(names, this.rhs); - } - } - class AssignOp extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - } - class Label extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - } - class Break extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - const label = this.label ? ` ${this.label}` : ""; - return `break${label};` + _n; - } - } - class Throw extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - } - class AnyCode extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : undefined; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - } - class ParentNode extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) - nodes.splice(i, 1, ...n); - else if (n) - nodes[i] = n; - else - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : undefined; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) - continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : undefined; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - } - class BlockNode extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - } - class Root extends ParentNode { - } - class Else extends BlockNode { - } - Else.kind = "else"; - class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) - code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) - return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) - return e instanceof If ? e : e.nodes; - if (this.nodes.length) - return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) - return undefined; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) - return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) - addNames(names, this.else.names); - return names; - } - } - If.kind = "if"; - class For extends BlockNode { - } - For.kind = "for"; - class ForLoop extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - } - class ForRange extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - const names = addExprNames(super.names, this.from); - return addExprNames(names, this.to); - } - } - class ForIter extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - } - class Func extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - const _async = this.async ? "async " : ""; - return `${_async}function ${this.name}(${this.args})` + super.render(opts); - } - } - Func.kind = "func"; - class Return extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - } - Return.kind = "return"; - class Try extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) - code += this.catch.render(opts); - if (this.finally) - code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) - addNames(names, this.catch.names); - if (this.finally) - addNames(names, this.finally.names); - return names; - } - } - class Catch extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - } - Catch.kind = "catch"; - class Finally extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - } - Finally.kind = "finally"; - class CodeGen { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()); - vs.add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== undefined && constant) - this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports$1.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") - c(); - else if (c !== code_1.nil) - this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) - code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) { - this.code(thenBody).else().code(elseBody).endIf(); - } - else if (thenBody) { - this.code(thenBody).endIf(); - } - else if (elseBody) { - throw new Error('CodeGen: "else" body without "then" body'); - } - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) - this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => { - this.var(name, (0, code_1._) `${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) { - return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody); - } - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) - throw new Error('CodeGen: "return" should have one node'); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) - throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) - this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === undefined) - throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { - throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - } - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) - this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || (N2 && n instanceof N2)) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) { - throw new Error('CodeGen: "else" without "if"'); - } - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - } - exports$1.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) - return replaceName(expr); - if (!canOptimize(expr)) - return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) - c = replaceName(c); - if (c instanceof code_1._Code) - items.push(...c._items); - else - items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === undefined || names[n.str] !== 1) - return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return (e instanceof code_1._Code && - e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined)); - } - } - function subtractNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`; - } - exports$1.not = not; - const andCode = mappend(exports$1.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports$1.and = and; - const orCode = mappend(exports$1.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports$1.or = or; - function mappend(op) { - return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`); - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`; - } - } (codegen)); - return codegen; -} - -var util = {}; - -var hasRequiredUtil; - -function requireUtil () { - if (hasRequiredUtil) return util; - hasRequiredUtil = 1; - Object.defineProperty(util, "__esModule", { value: true }); - util.checkStrictMode = util.getErrorPath = util.Type = util.useFunc = util.setEvaluated = util.evaluatedPropsToName = util.mergeEvaluated = util.eachItem = util.unescapeJsonPointer = util.escapeJsonPointer = util.escapeFragment = util.unescapeFragment = util.schemaRefOrVal = util.schemaHasRulesButRef = util.schemaHasRules = util.checkUnknownRules = util.alwaysValidSchema = util.toHash = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const code_1 = /*@__PURE__*/ requireCode$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) - hash[item] = true; - return hash; - } - util.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") - return schema; - if (Object.keys(schema).length === 0) - return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - util.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) - return; - if (typeof schema === "boolean") - return; - const rules = self.RULES.keywords; - for (const key in schema) { - if (!rules[key]) - checkStrictMode(it, `unknown keyword: "${key}"`); - } - } - util.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (rules[key]) - return true; - return false; - } - util.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (key !== "$ref" && RULES.all[key]) - return true; - return false; - } - util.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") - return schema; - if (typeof schema == "string") - return (0, codegen_1._) `${schema}`; - } - return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - util.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - util.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - util.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") - return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - util.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - util.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) { - for (const x of xs) - f(x); - } - else { - f(xs); - } - } - util.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) { - return (gen, from, to, toName) => { - const res = to === undefined - ? from - : to instanceof codegen_1.Name - ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) - : from instanceof codegen_1.Name - ? (mergeToName(gen, to, from), from) - : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - util.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => { - if (from === true) { - gen.assign(to, true); - } - else { - gen.assign(to, (0, codegen_1._) `${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => (from === true ? true : { ...from, ...to }), - resultToName: evaluatedPropsToName, - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => (from === true ? true : Math.max(from, to)), - resultToName: (gen, items) => gen.var("items", items), - }), - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) - return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._) `{}`); - if (ps !== undefined) - setEvaluated(gen, props, ps); - return props; - } - util.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - util.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)), - }); - } - util.useFunc = useFunc; - var Type; - (function (Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (util.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax - ? isNumber - ? (0, codegen_1._) `"[" + ${dataProp} + "]"` - : (0, codegen_1._) `"['" + ${dataProp} + "']"` - : isNumber - ? (0, codegen_1._) `"/" + ${dataProp}` - : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - util.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) - return; - msg = `strict mode: ${msg}`; - if (mode === true) - throw new Error(msg); - it.self.logger.warn(msg); - } - util.checkStrictMode = checkStrictMode; - return util; -} - -var names = {}; - -var hasRequiredNames; - -function requireNames () { - if (hasRequiredNames) return names; - hasRequiredNames = 1; - Object.defineProperty(names, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const names$1 = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart"), - }; - names.default = names$1; - return names; -} - -var hasRequiredErrors; - -function requireErrors () { - if (hasRequiredErrors) return errors; - hasRequiredErrors = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.extendErrors = exports$1.resetErrorsCount = exports$1.reportExtraError = exports$1.reportError = exports$1.keyword$DataError = exports$1.keywordError = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const names_1 = /*@__PURE__*/ requireNames(); - exports$1.keywordError = { - message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`, - }; - exports$1.keyword$DataError = { - message: ({ keyword, schemaType }) => schemaType - ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)` - : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`, - }; - function reportError(cxt, error = exports$1.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) { - addError(gen, errObj); - } - else { - returnErrors(it, (0, codegen_1._) `[${errObj}]`); - } - } - exports$1.reportError = reportError; - function reportExtraError(cxt, error = exports$1.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - addError(gen, errObj); - if (!(compositeRule || allErrors)) { - returnErrors(it, names_1.default.vErrors); - } - } - exports$1.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports$1.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) { - if (errsCount === undefined) - throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._) `${err}.schema`, schemaValue); - gen.assign((0, codegen_1._) `${err}.data`, data); - } - }); - } - exports$1.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._) `${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) { - gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`); - } - else { - gen.assign((0, codegen_1._) `${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema"), - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) - return (0, codegen_1._) `{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [ - errorInstancePath(it, errorPaths), - errorSchemaPath(cxt, errorPaths), - ]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath - ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` - : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`; - if (schemaPath) { - schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - } - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]); - if (opts.messages) { - keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - } - if (opts.verbose) { - keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - } - if (propertyName) - keyValues.push([E.propertyName, propertyName]); - } - } (errors)); - return errors; -} - -var hasRequiredBoolSchema; - -function requireBoolSchema () { - if (hasRequiredBoolSchema) return boolSchema; - hasRequiredBoolSchema = 1; - Object.defineProperty(boolSchema, "__esModule", { value: true }); - boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0; - const errors_1 = /*@__PURE__*/ requireErrors(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const names_1 = /*@__PURE__*/ requireNames(); - const boolError = { - message: "boolean schema is false", - }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) { - falseSchemaError(it, false); - } - else if (typeof schema == "object" && schema.$async === true) { - gen.return(names_1.default.data); - } - else { - gen.assign((0, codegen_1._) `${validateName}.errors`, null); - gen.return(true); - } - } - boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } - else { - gen.var(valid, true); - } - } - boolSchema.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it, - }; - (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors); - } - return boolSchema; -} - -var dataType = {}; - -var rules = {}; - -var hasRequiredRules; - -function requireRules () { - if (hasRequiredRules) return rules; - hasRequiredRules = 1; - Object.defineProperty(rules, "__esModule", { value: true }); - rules.getRules = rules.isJSONType = void 0; - const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; - const jsonTypes = new Set(_jsonTypes); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - rules.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { type: "number", rules: [] }, - string: { type: "string", rules: [] }, - array: { type: "array", rules: [] }, - object: { type: "object", rules: [] }, - }; - return { - types: { ...groups, integer: true, boolean: true, null: true }, - rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], - post: { rules: [] }, - all: {}, - keywords: {}, - }; - } - rules.getRules = getRules; - return rules; -} - -var applicability = {}; - -var hasRequiredApplicability; - -function requireApplicability () { - if (hasRequiredApplicability) return applicability; - hasRequiredApplicability = 1; - Object.defineProperty(applicability, "__esModule", { value: true }); - applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - applicability.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - applicability.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return (schema[rule.keyword] !== undefined || - ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined))); - } - applicability.shouldUseRule = shouldUseRule; - return applicability; -} - -var hasRequiredDataType; - -function requireDataType () { - if (hasRequiredDataType) return dataType; - hasRequiredDataType = 1; - Object.defineProperty(dataType, "__esModule", { value: true }); - dataType.reportTypeError = dataType.checkDataTypes = dataType.checkDataType = dataType.coerceAndCheckDataType = dataType.getJSONTypes = dataType.getSchemaTypes = dataType.DataType = void 0; - const rules_1 = /*@__PURE__*/ requireRules(); - const applicability_1 = /*@__PURE__*/ requireApplicability(); - const errors_1 = /*@__PURE__*/ requireErrors(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - var DataType; - (function (DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (dataType.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - const hasNull = types.includes("null"); - if (hasNull) { - if (schema.nullable === false) - throw new Error("type: null contradicts nullable: false"); - } - else { - if (!types.length && schema.nullable !== undefined) { - throw new Error('"nullable" cannot be used without "type"'); - } - if (schema.nullable === true) - types.push("null"); - } - return types; - } - dataType.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) - return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - dataType.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && - !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) - coerceData(it, types, coerceTo); - else - reportTypeError(it); - }); - } - return checkTypes; - } - dataType.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes - ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array")) - : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._) `undefined`); - if (opts.coerceTypes === "array") { - gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen - .assign(data, (0, codegen_1._) `${data}[0]`) - .assign(dataType, (0, codegen_1._) `typeof ${data}`) - .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - } - gen.if((0, codegen_1._) `${coerced} !== undefined`); - for (const t of coerceTo) { - if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) { - coerceSpecificType(t); - } - } - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._) `${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen - .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`) - .assign(coerced, (0, codegen_1._) `"" + ${data}`) - .elseIf((0, codegen_1._) `${data} === null`) - .assign(coerced, (0, codegen_1._) `""`); - return; - case "number": - gen - .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`) - .assign(coerced, (0, codegen_1._) `+${data}`); - return; - case "integer": - gen - .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`) - .assign(coerced, (0, codegen_1._) `+${data}`); - return; - case "boolean": - gen - .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`) - .assign(coerced, false) - .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`) - .assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": - gen - .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`) - .assign(coerced, (0, codegen_1._) `[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": - return (0, codegen_1._) `${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._) `Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: - return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil); - } - } - dataType.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) { - return checkDataType(dataTypes[0], data, strictNums, correct); - } - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._) `typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } - else { - cond = codegen_1.nil; - } - if (types.number) - delete types.integer; - for (const t in types) - cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - dataType.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`, - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - dataType.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it, - }; - } - return dataType; -} - -var defaults = {}; - -var hasRequiredDefaults; - -function requireDefaults () { - if (hasRequiredDefaults) return defaults; - hasRequiredDefaults = 1; - Object.defineProperty(defaults, "__esModule", { value: true }); - defaults.assignDefaults = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) { - for (const key in properties) { - assignDefault(it, key, properties[key].default); - } - } - else if (ty === "array" && Array.isArray(items)) { - items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - } - defaults.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === undefined) - return; - const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._) `${childData} === undefined`; - if (opts.useDefaults === "empty") { - condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`; - } - gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } - return defaults; -} - -var keyword = {}; - -var code = {}; - -var hasRequiredCode; - -function requireCode () { - if (hasRequiredCode) return code; - hasRequiredCode = 1; - Object.defineProperty(code, "__esModule", { value: true }); - code.validateUnion = code.validateArray = code.usePattern = code.callValidateCode = code.schemaProperties = code.allSchemaProperties = code.noPropertyInData = code.propertyInData = code.isOwnProperty = code.hasPropFunc = code.reportMissingProp = code.checkMissingProp = code.checkReportMissingProp = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const names_1 = /*@__PURE__*/ requireNames(); - const util_2 = /*@__PURE__*/ requireUtil(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true); - cxt.error(); - }); - } - code.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`))); - } - code.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - code.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._) `Object.prototype.hasOwnProperty`, - }); - } - code.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`; - } - code.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - code.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - code.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - code.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - code.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData], - ]; - if (it.opts.dynamicRef) - valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`; - } - code.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._) `new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`, - }); - } - code.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._) `${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num, - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - code.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); - if (alwaysValid && !it.opts.unevaluated) - return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true, - }, schValid); - gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`); - const merged = cxt.mergeValidEvaluated(schCxt, schValid); - if (!merged) - gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - code.validateUnion = validateUnion; - return code; -} - -var hasRequiredKeyword; - -function requireKeyword () { - if (hasRequiredKeyword) return keyword; - hasRequiredKeyword = 1; - Object.defineProperty(keyword, "__esModule", { value: true }); - keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const names_1 = /*@__PURE__*/ requireNames(); - const code_1 = /*@__PURE__*/ requireCode(); - const errors_1 = /*@__PURE__*/ requireErrors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) - it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true, - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - keyword.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => cxt.error()); - } - else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._) `${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !(("compile" in def && !$data) || def.schema === false); - gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a; - gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors); - } - } - keyword.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => { - gen - .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`) - .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) - throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === undefined) - throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return (!schemaType.length || - schemaType.some((st) => st === "array" - ? Array.isArray(schema) - : st === "object" - ? schema && typeof schema == "object" && !Array.isArray(schema) - : typeof schema == st || (allowUndefined && typeof schema == "undefined"))); - } - keyword.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { - throw new Error("ajv implementation error"); - } - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { - throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - } - if (def.validateSchema) { - const valid = def.validateSchema(schema[keyword]); - if (!valid) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + - self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") - self.logger.error(msg); - else - throw new Error(msg); - } - } - } - keyword.validateKeywordUsage = validateKeywordUsage; - return keyword; -} - -var subschema = {}; - -var hasRequiredSubschema; - -function requireSubschema () { - if (hasRequiredSubschema) return subschema; - hasRequiredSubschema = 1; - Object.defineProperty(subschema, "__esModule", { value: true }); - subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== undefined && schema !== undefined) { - throw new Error('both "keyword" and "schema" passed, only one allowed'); - } - if (keyword !== undefined) { - const sch = it.schema[keyword]; - return schemaProp === undefined - ? { - schema: sch, - schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - } - : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`, - }; - } - if (schema !== undefined) { - if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) { - throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); - } - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath, - }; - } - throw new Error('either "keyword" or "schema" must be passed'); - } - subschema.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== undefined && dataProp !== undefined) { - throw new Error('both "data" and "dataProp" passed, only one allowed'); - } - const { gen } = it; - if (dataProp !== undefined) { - const { errorPath, dataPathArr, opts } = it; - const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); - dataContextProps(nextData); - subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== undefined) { - const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); - dataContextProps(nextData); - if (propertyName !== undefined) - subschema.propertyName = propertyName; - } - if (dataTypes) - subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - subschema.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== undefined) - subschema.compositeRule = compositeRule; - if (createErrors !== undefined) - subschema.createErrors = createErrors; - if (allErrors !== undefined) - subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - subschema.extendSubschemaMode = extendSubschemaMode; - return subschema; -} - -var resolve = {}; - -var fastDeepEqual; -var hasRequiredFastDeepEqual; - -function requireFastDeepEqual () { - if (hasRequiredFastDeepEqual) return fastDeepEqual; - hasRequiredFastDeepEqual = 1; - fastDeepEqual = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == 'object' && typeof b == 'object') { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a!==a && b!==b; - }; - return fastDeepEqual; -} - -var jsonSchemaTraverse = {exports: {}}; - -var hasRequiredJsonSchemaTraverse; - -function requireJsonSchemaTraverse () { - if (hasRequiredJsonSchemaTraverse) return jsonSchemaTraverse.exports; - hasRequiredJsonSchemaTraverse = 1; - var traverse = jsonSchemaTraverse.exports = function (schema, opts, cb) { - if (typeof opts == 'function') { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = (typeof cb == 'function') ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, '', schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == 'object' && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i=0; i (count += countKeys(sch))); - } - if (count === Infinity) - return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) - id = normalizeId(id); - const p = resolver.parse(id); - return _getFullPath(resolver, p); - } - resolve.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - const serialized = resolver.serialize(p); - return serialized.split("#")[0] + "#"; - } - resolve._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - resolve.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - resolve.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") - return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === undefined) - return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") - innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) - throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") - schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") { - checkAmbiguosRef(sch, schOrRef.schema, ref); - } - else if (ref !== normalizeId(fullPath)) { - if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } - else { - this.refs[ref] = fullPath; - } - } - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== undefined && !equal(sch1, sch2)) - throw ambiguos(ref); - } - function ambiguos(ref) { - return new Error(`reference "${ref}" resolves to more than one schema`); - } - } - resolve.getSchemaRefs = getSchemaRefs; - return resolve; -} - -var hasRequiredValidate; - -function requireValidate () { - if (hasRequiredValidate) return validate$1; - hasRequiredValidate = 1; - Object.defineProperty(validate$1, "__esModule", { value: true }); - validate$1.getData = validate$1.KeywordCxt = validate$1.validateFunctionCode = void 0; - const boolSchema_1 = /*@__PURE__*/ requireBoolSchema(); - const dataType_1 = /*@__PURE__*/ requireDataType(); - const applicability_1 = /*@__PURE__*/ requireApplicability(); - const dataType_2 = /*@__PURE__*/ requireDataType(); - const defaults_1 = /*@__PURE__*/ requireDefaults(); - const keyword_1 = /*@__PURE__*/ requireKeyword(); - const subschema_1 = /*@__PURE__*/ requireSubschema(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const names_1 = /*@__PURE__*/ requireNames(); - const resolve_1 = /*@__PURE__*/ requireResolve(); - const util_1 = /*@__PURE__*/ requireUtil(); - const errors_1 = /*@__PURE__*/ requireErrors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - validate$1.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) { - gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - } - else { - gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - } - function destructureValCxt(opts) { - return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._) `""`); - gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) - commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) - resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - return; - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`); - gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`)); - gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (self.RULES.all[key]) - return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) - commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) - return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); - schemaKeywords(it, types, !checkedTypes, errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { - self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) { - (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) - it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) - throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) { - gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`); - } - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) { - gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`)); - } - else { - gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) - assignEvaluated(it); - gen.return((0, codegen_1._) `${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) - gen.assign((0, codegen_1._) `${evaluated}.props`, props); - if (items instanceof codegen_1.Name) - gen.assign((0, codegen_1._) `${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) - checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) - groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) - return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } - else { - iterateKeywords(it, group); - } - if (!allErrors) - gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults }, } = it; - if (useDefaults) - (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) { - if ((0, applicability_1.shouldUseRule)(schema, rule)) { - keywordCode(it, rule.keyword, rule.definition, group.type); - } - } - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) - return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) - checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) - return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) { - strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - } - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { - strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) { - strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer")); - } - function includesType(ts, t) { - return ts.includes(t) || (t === "integer" && ts.includes("number")); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) { - if (includesType(withTypes, t)) - ts.push(t); - else if (withTypes.includes("integer") && t === "number") - ts.push("integer"); - } - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - class KeywordCxt { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) { - this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - } - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { - throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - } - if ("code" in def ? def.trackErrors : def.errors !== false) { - this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) - failAction(); - else - this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) - this.gen.endIf(); - } - else { - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), undefined, failAction); - } - fail(condition) { - if (condition === undefined) { - this.error(); - if (!this.allErrors) - this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - fail$data(condition) { - if (!this.$data) - return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === undefined) - throw new Error('add "trackErrors" to keyword definition'); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) - this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) - Object.assign(this.params, obj); - else - this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) - return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) - gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) - gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - if (!(schemaCode instanceof codegen_1.Name)) - throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) - return; - if (it.props !== true && schemaCxt.props !== undefined) { - it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - } - if (it.items !== true && schemaCxt.items !== undefined) { - it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - } - validate$1.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) { - def.code(cxt, ruleType); - } - else if (cxt.$data && def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } - else if ("macro" in def) { - (0, keyword_1.macroKeywordCode)(cxt, def); - } - else if (def.compile || def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") - return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) - throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } - else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) - throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) - throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) - throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) - return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) { - if (segment) { - data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._) `${expr} && ${data}`; - } - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - validate$1.getData = getData; - return validate$1; -} - -var validation_error = {}; - -var hasRequiredValidation_error; - -function requireValidation_error () { - if (hasRequiredValidation_error) return validation_error; - hasRequiredValidation_error = 1; - Object.defineProperty(validation_error, "__esModule", { value: true }); - class ValidationError extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - } - validation_error.default = ValidationError; - return validation_error; -} - -var ref_error = {}; - -var hasRequiredRef_error; - -function requireRef_error () { - if (hasRequiredRef_error) return ref_error; - hasRequiredRef_error = 1; - Object.defineProperty(ref_error, "__esModule", { value: true }); - const resolve_1 = /*@__PURE__*/ requireResolve(); - class MissingRefError extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - } - ref_error.default = MissingRefError; - return ref_error; -} - -var compile = {}; - -var hasRequiredCompile; - -function requireCompile () { - if (hasRequiredCompile) return compile; - hasRequiredCompile = 1; - Object.defineProperty(compile, "__esModule", { value: true }); - compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const validation_error_1 = /*@__PURE__*/ requireValidation_error(); - const names_1 = /*@__PURE__*/ requireNames(); - const resolve_1 = /*@__PURE__*/ requireResolve(); - const util_1 = /*@__PURE__*/ requireUtil(); - const validate_1 = /*@__PURE__*/ requireValidate(); - class SchemaEnv { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - } - compile.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) - return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); - let _ValidationError; - if (sch.$async) { - _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`, - }); - } - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true - ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } - : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._) `""`, - opts: this.opts, - self: this, - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) - sourceCode = this.opts.code.process(sourceCode, sch); - const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) - validate.$async = true; - if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; - } - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? undefined : props, - items: items instanceof codegen_1.Name ? undefined : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name, - }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } - catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) - this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } - finally { - this._compilations.delete(sch); - } - } - compile.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) - return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === undefined) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) - _sch = new SchemaEnv({ schema, schemaId, root, baseId }); - } - if (_sch === undefined) - return; - return (root.refs[ref] = inlineOrCompile.call(this, _sch)); - } - compile.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) - return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) { - if (sameSchemaEnv(sch, schEnv)) - return sch; - } - } - compile.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, - ref - ) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") - ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, - ref - ) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined); - if (Object.keys(root.schema).length > 0 && refPath === baseId) { - return getJsonPointer.call(this, p, root); - } - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") - return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") - return; - if (!schOrRef.validate) - compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ schema, schemaId, root, baseId }); - } - return getJsonPointer.call(this, p, schOrRef); - } - compile.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions", - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") - return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") - return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === undefined) - return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; - return undefined; - } - return compile; -} - -var $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"; -var description = "Meta-schema for $data reference (JSON AnySchema extension proposal)"; -var type$1 = "object"; -var required$1 = [ - "$data" -]; -var properties$2 = { - $data: { - type: "string", - anyOf: [ - { - format: "relative-json-pointer" - }, - { - format: "json-pointer" - } - ] - } -}; -var additionalProperties$1 = false; -var require$$9 = { - $id: $id$1, - description: description, - type: type$1, - required: required$1, - properties: properties$2, - additionalProperties: additionalProperties$1 -}; - -var uri = {}; - -var fastUri = {exports: {}}; - -var utils; -var hasRequiredUtils; - -function requireUtils () { - if (hasRequiredUtils) return utils; - hasRequiredUtils = 1; - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); - function stringArrayToHexStripped (input) { - let acc = ''; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) { - continue - } - if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) { - return '' - } - acc += input[i]; - break - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!((code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102))) { - return '' - } - acc += input[i]; - } - return acc - } - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - function consumeIsZone (buffer) { - buffer.length = 0; - return true - } - function consumeHextets (buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== '') { - address.push(hex); - } else { - output.error = true; - return false - } - buffer.length = 0; - } - return true - } - function getIPV6 (input) { - let tokenCount = 0; - const output = { error: false, address: '', zone: '' }; - const address = []; - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === '[' || cursor === ']') { continue } - if (cursor === ':') { - if (endipv6Encountered === true) { - endIpv6 = true; - } - if (!consume(buffer, address, output)) { break } - if (++tokenCount > 7) { - output.error = true; - break - } - if (i > 0 && input[i - 1] === ':') { - endipv6Encountered = true; - } - address.push(':'); - continue - } else if (cursor === '%') { - if (!consume(buffer, address, output)) { break } - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue - } - } - if (buffer.length) { - if (consume === consumeIsZone) { - output.zone = buffer.join(''); - } else if (endIpv6) { - address.push(buffer.join('')); - } else { - address.push(stringArrayToHexStripped(buffer)); - } - } - output.address = address.join(''); - return output - } - function normalizeIPv6 (host) { - if (findToken(host, ':') < 2) { return { host, isIPV6: false } } - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += '%' + ipv6.zone; - escapedHost += '%25' + ipv6.zone; - } - return { host: newHost, isIPV6: true, escapedHost } - } else { - return { host, isIPV6: false } - } - } - function findToken (str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === token) ind++; - } - return ind - } - function removeDotSegments (path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) { - if (input === '.') { - break - } else if (input === '/') { - output.push('/'); - break - } else { - output.push(input); - break - } - } else if (len === 2) { - if (input[0] === '.') { - if (input[1] === '.') { - break - } else if (input[1] === '/') { - input = input.slice(2); - continue - } - } else if (input[0] === '/') { - if (input[1] === '.' || input[1] === '/') { - output.push('/'); - break - } - } - } else if (len === 3) { - if (input === '/..') { - if (output.length !== 0) { - output.pop(); - } - output.push('/'); - break - } - } - if (input[0] === '.') { - if (input[1] === '.') { - if (input[2] === '/') { - input = input.slice(3); - continue - } - } else if (input[1] === '/') { - input = input.slice(2); - continue - } - } else if (input[0] === '/') { - if (input[1] === '.') { - if (input[2] === '/') { - input = input.slice(2); - continue - } else if (input[2] === '.') { - if (input[3] === '/') { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); - } - continue - } - } - } - } - if ((nextSlash = input.indexOf('/', 1)) === -1) { - output.push(input); - break - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join('') - } - function normalizeComponentEncoding (component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== undefined) { - component.scheme = func(component.scheme); - } - if (component.userinfo !== undefined) { - component.userinfo = func(component.userinfo); - } - if (component.host !== undefined) { - component.host = func(component.host); - } - if (component.path !== undefined) { - component.path = func(component.path); - } - if (component.query !== undefined) { - component.query = func(component.query); - } - if (component.fragment !== undefined) { - component.fragment = func(component.fragment); - } - return component - } - function recomposeAuthority (component) { - const uriTokens = []; - if (component.userinfo !== undefined) { - uriTokens.push(component.userinfo); - uriTokens.push('@'); - } - if (component.host !== undefined) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) { - host = `[${ipV6res.escapedHost}]`; - } else { - host = component.host; - } - } - uriTokens.push(host); - } - if (typeof component.port === 'number' || typeof component.port === 'string') { - uriTokens.push(':'); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join('') : undefined - } utils = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; - return utils; -} - -var schemes; -var hasRequiredSchemes; - -function requireSchemes () { - if (hasRequiredSchemes) return schemes; - hasRequiredSchemes = 1; - const { isUUID } = requireUtils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = (['http', 'https', 'ws', - 'wss', 'urn', 'urn:uuid']); - function isValidSchemeName (name) { - return supportedSchemeNames.indexOf( (name)) !== -1 - } - function wsIsSecure (wsComponent) { - if (wsComponent.secure === true) { - return true - } else if (wsComponent.secure === false) { - return false - } else if (wsComponent.scheme) { - return ( - wsComponent.scheme.length === 3 && - (wsComponent.scheme[0] === 'w' || wsComponent.scheme[0] === 'W') && - (wsComponent.scheme[1] === 's' || wsComponent.scheme[1] === 'S') && - (wsComponent.scheme[2] === 's' || wsComponent.scheme[2] === 'S') - ) - } else { - return false - } - } - function httpParse (component) { - if (!component.host) { - component.error = component.error || 'HTTP URIs must have a host.'; - } - return component - } - function httpSerialize (component) { - const secure = String(component.scheme).toLowerCase() === 'https'; - if (component.port === (secure ? 443 : 80) || component.port === '') { - component.port = undefined; - } - if (!component.path) { - component.path = '/'; - } - return component - } - function wsParse (wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || '/') + (wsComponent.query ? '?' + wsComponent.query : ''); - wsComponent.path = undefined; - wsComponent.query = undefined; - return wsComponent - } - function wsSerialize (wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === '') { - wsComponent.port = undefined; - } - if (typeof wsComponent.secure === 'boolean') { - wsComponent.scheme = (wsComponent.secure ? 'wss' : 'ws'); - wsComponent.secure = undefined; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split('?'); - wsComponent.path = (path && path !== '/' ? path : undefined); - wsComponent.query = query; - wsComponent.resourceName = undefined; - } - wsComponent.fragment = undefined; - return wsComponent - } - function urnParse (urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = 'URN can not be parsed'; - return urnComponent - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || 'urn'; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; - const schemeHandler = getSchemeHandler(urnScheme); - urnComponent.path = undefined; - if (schemeHandler) { - urnComponent = schemeHandler.parse(urnComponent, options); - } - } else { - urnComponent.error = urnComponent.error || 'URN can not be parsed.'; - } - return urnComponent - } - function urnSerialize (urnComponent, options) { - if (urnComponent.nid === undefined) { - throw new Error('URN without nid cannot be serialized') - } - const scheme = options.scheme || urnComponent.scheme || 'urn'; - const nid = urnComponent.nid.toLowerCase(); - const urnScheme = `${scheme}:${options.nid || nid}`; - const schemeHandler = getSchemeHandler(urnScheme); - if (schemeHandler) { - urnComponent = schemeHandler.serialize(urnComponent, options); - } - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent - } - function urnuuidParse (urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = undefined; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { - uuidComponent.error = uuidComponent.error || 'UUID is not valid.'; - } - return uuidComponent - } - function urnuuidSerialize (uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || '').toLowerCase(); - return urnComponent - } - const http = ({ - scheme: 'http', - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }); - const https = ({ - scheme: 'https', - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }); - const ws = ({ - scheme: 'ws', - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }); - const wss = ({ - scheme: 'wss', - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }); - const urn = ({ - scheme: 'urn', - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }); - const urnuuid = ({ - scheme: 'urn:uuid', - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }); - const SCHEMES = ({ - http, - https, - ws, - wss, - urn, - 'urn:uuid': urnuuid - }); - Object.setPrototypeOf(SCHEMES, null); - function getSchemeHandler (scheme) { - return ( - scheme && ( - SCHEMES[ (scheme)] || - SCHEMES[(scheme.toLowerCase())]) - ) || - undefined - } - schemes = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler, - }; - return schemes; -} - -var hasRequiredFastUri; - -function requireFastUri () { - if (hasRequiredFastUri) return fastUri.exports; - hasRequiredFastUri = 1; - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = requireUtils(); - const { SCHEMES, getSchemeHandler } = requireSchemes(); - function normalize (uri, options) { - if (typeof uri === 'string') { - uri = (serialize(parse(uri, options), options)); - } else if (typeof uri === 'object') { - uri = (parse(serialize(uri, options), options)); - } - return uri - } - function resolve (baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: 'null' }, options) : { scheme: 'null' }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions) - } - function resolveComponent (base, relative, options, skipNormalization) { - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ''); - target.query = relative.query; - } else { - if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ''); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== undefined) { - target.query = relative.query; - } else { - target.query = base.query; - } - } else { - if (relative.path[0] === '/') { - target.path = removeDotSegments(relative.path); - } else { - if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { - target.path = '/' + relative.path; - } else if (!base.path) { - target.path = relative.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target - } - function equal (uriA, uriB, options) { - if (typeof uriA === 'string') { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true }); - } else if (typeof uriA === 'object') { - uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); - } - if (typeof uriB === 'string') { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true }); - } else if (typeof uriB === 'object') { - uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); - } - return uriA.toLowerCase() === uriB.toLowerCase() - } - function serialize (cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: '' - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== undefined) { - if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== undefined) { - component.path = component.path.split('%3A').join(':'); - } - } else { - component.path = unescape(component.path); - } - } - if (options.reference !== 'suffix' && component.scheme) { - uriTokens.push(component.scheme, ':'); - } - const authority = recomposeAuthority(component); - if (authority !== undefined) { - if (options.reference !== 'suffix') { - uriTokens.push('//'); - } - uriTokens.push(authority); - if (component.path && component.path[0] !== '/') { - uriTokens.push('/'); - } - } - if (component.path !== undefined) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if ( - authority === undefined && - s[0] === '/' && - s[1] === '/' - ) { - s = '/%2F' + s.slice(2); - } - uriTokens.push(s); - } - if (component.query !== undefined) { - uriTokens.push('?', component.query); - } - if (component.fragment !== undefined) { - uriTokens.push('#', component.fragment); - } - return uriTokens.join('') - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - function parse (uri, opts) { - const options = Object.assign({}, opts); - const parsed = { - scheme: undefined, - userinfo: undefined, - host: '', - port: undefined, - path: '', - query: undefined, - fragment: undefined - }; - let isIP = false; - if (options.reference === 'suffix') { - if (options.scheme) { - uri = options.scheme + ':' + uri; - } else { - uri = '//' + uri; - } - } - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ''; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) { - parsed.port = matches[5]; - } - if (parsed.host) { - const ipv4result = isIPv4(parsed.host); - if (ipv4result === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else { - isIP = true; - } - } - if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) { - parsed.reference = 'same-document'; - } else if (parsed.scheme === undefined) { - parsed.reference = 'relative'; - } else if (parsed.fragment === undefined) { - parsed.reference = 'absolute'; - } else { - parsed.reference = 'uri'; - } - if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) { - parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'; - } - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) { - try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - } - if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) { - if (uri.indexOf('%') !== -1) { - if (parsed.scheme !== undefined) { - parsed.scheme = unescape(parsed.scheme); - } - if (parsed.host !== undefined) { - parsed.host = unescape(parsed.host); - } - } - if (parsed.path) { - parsed.path = escape(unescape(parsed.path)); - } - if (parsed.fragment) { - parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - } - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(parsed, options); - } - } else { - parsed.error = parsed.error || 'URI can not be parsed.'; - } - return parsed - } - const fastUri$1 = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - fastUri.exports = fastUri$1; - fastUri.exports.default = fastUri$1; - fastUri.exports.fastUri = fastUri$1; - return fastUri.exports; -} - -var hasRequiredUri; - -function requireUri () { - if (hasRequiredUri) return uri; - hasRequiredUri = 1; - Object.defineProperty(uri, "__esModule", { value: true }); - const uri$1 = requireFastUri(); - uri$1.code = 'require("ajv/dist/runtime/uri").default'; - uri.default = uri$1; - return uri; -} - -var hasRequiredCore$1; - -function requireCore$1 () { - if (hasRequiredCore$1) return core$1; - hasRequiredCore$1 = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = void 0; - var validate_1 = /*@__PURE__*/ requireValidate(); - Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); - var codegen_1 = /*@__PURE__*/ requireCodegen(); - Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } }); - Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } }); - Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); - Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); - Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); - Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); - const validation_error_1 = /*@__PURE__*/ requireValidation_error(); - const ref_error_1 = /*@__PURE__*/ requireRef_error(); - const rules_1 = /*@__PURE__*/ requireRules(); - const compile_1 = /*@__PURE__*/ requireCompile(); - const codegen_2 = /*@__PURE__*/ requireCodegen(); - const resolve_1 = /*@__PURE__*/ requireResolve(); - const dataType_1 = /*@__PURE__*/ requireDataType(); - const util_1 = /*@__PURE__*/ requireUtil(); - const $dataRefSchema = require$$9; - const uri_1 = /*@__PURE__*/ requireUri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error", - ]); - const removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: '"nullable" keyword is supported by default.', - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: '"uniqueItems" keyword is always validated.', - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now.", - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: '"minLength"/"maxLength" account for unicode characters by default.', - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver: uriResolver, - }; - } - class Ajv { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = new Set(); - this._loading = {}; - this._cache = new Map(); - opts = this.opts = { ...opts, ...requiredOptions(opts) }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) - addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) - addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") - this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) - this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined); - } - validate(schemaKeyRef, - data - ) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) - throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } - else { - v = this.compile(schemaKeyRef); - } - const valid = v(data); - if (!("$async" in v)) - this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return (sch.validate || this._compileSchemaEnv(sch)); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") { - throw new Error("options.loadSchema should be a function"); - } - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) { - await runCompileAsync.call(this, { $ref }, true); - } - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } - catch (e) { - if (!(e instanceof ref_error_1.default)) - throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) { - throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) - await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) - this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) - return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } - finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, - key, - _meta, - _validateSchema = this.opts.validateSchema - ) { - if (Array.isArray(schema)) { - for (const sch of schema) - this.addSchema(sch, undefined, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== undefined && typeof id != "string") { - throw new Error(`schema ${schemaId} must be string`); - } - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, - _validateSchema = this.opts.validateSchema - ) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") - return true; - let $schema; - $schema = schema.$schema; - if ($schema !== undefined && typeof $schema != "string") { - throw new Error("$schema must be a string"); - } - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") - this.logger.error(message); - else - throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") - keyRef = sch; - if (sch === undefined) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) - return; - this.refs[keyRef] = sch; - } - return (sch.validate || this._compileSchemaEnv(sch)); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") - this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: - throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) - this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def - ) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } - else if (typeof kwdOrDef == "object" && def === undefined) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) { - throw new Error("addKeywords: keyword must be string or non-empty array"); - } - } - else { - throw new Error("invalid addKeywords parameters"); - } - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType), - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 - ? (k) => addRule.call(this, k, definition) - : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) - group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") - format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, - { separator = ", ", dataVar = "data" } = {} - ) { - if (!errors || errors.length === 0) - return "No errors"; - return errors - .map((e) => `${dataVar}${e.instancePath} ${e.message}`) - .reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) - keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") - continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) - keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") { - delete schemas[keyRef]; - } - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") { - id = schema[schemaId]; - } - else { - if (this.opts.jtd) - throw new Error("schema must be object"); - else if (typeof schema != "boolean") - throw new Error("schema must be object or boolean"); - } - let sch = this._cache.get(schema); - if (sch !== undefined) - return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) - this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) - this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) { - throw new Error(`schema with key or id "${id}" already exists`); - } - } - _compileSchemaEnv(sch) { - if (sch.meta) - this._compileMetaSchema(sch); - else - compile_1.compileSchema.call(this, sch); - if (!sch.validate) - throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } - finally { - this.opts = currentOpts; - } - } - } - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports$1.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) - this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) - return; - if (Array.isArray(optsSchemas)) - this.addSchema(optsSchemas); - else - for (const key in optsSchemas) - this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) - this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) - def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) - delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { log() { }, warn() { }, error() { } }; - function getLogger(logger) { - if (logger === false) - return noLogs; - if (logger === undefined) - return console; - if (logger.log && logger.warn && logger.error) - return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) - throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) - throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) - return; - if (def.$data && !("code" in def || "validate" in def)) { - throw new Error('$data keyword must have "code" or "validate" function'); - } - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) - throw new Error('keyword with "post" flag cannot have "type"'); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) - return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType), - }, - }; - if (definition.before) - addBeforeRule.call(this, ruleGroup, rule, definition.before); - else - ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) { - ruleGroup.rules.splice(i, 0, rule); - } - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === undefined) - return; - if (def.$data && this.opts.$data) - metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { - $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } - } (core$1)); - return core$1; -} - -var draft7 = {}; - -var core = {}; - -var id = {}; - -var hasRequiredId; - -function requireId () { - if (hasRequiredId) return id; - hasRequiredId = 1; - Object.defineProperty(id, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); - }, - }; - id.default = def; - return id; -} - -var ref = {}; - -var hasRequiredRef; - -function requireRef () { - if (hasRequiredRef) return ref; - hasRequiredRef = 1; - Object.defineProperty(ref, "__esModule", { value: true }); - ref.callRef = ref.getValidate = void 0; - const ref_error_1 = /*@__PURE__*/ requireRef_error(); - const code_1 = /*@__PURE__*/ requireCode(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const names_1 = /*@__PURE__*/ requireNames(); - const compile_1 = /*@__PURE__*/ requireCompile(); - const util_1 = /*@__PURE__*/ requireUtil(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) - return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === undefined) - throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) - return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - const v = getValidate(cxt, sch); - callRef(cxt, v, sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref, - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - }, - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate - ? gen.scopeValue("validate", { ref: sch.validate }) - : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - ref.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) - callAsyncRef(); - else - callSyncRef(); - function callAsyncRef() { - if (!env.$async) - throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) - gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) - gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._) `${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) - return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) { - if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== undefined) { - it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } - } - else { - const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - } - if (it.items !== true) { - if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== undefined) { - it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } - } - else { - const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - } - ref.callRef = callRef; - ref.default = def; - return ref; -} - -var hasRequiredCore; - -function requireCore () { - if (hasRequiredCore) return core; - hasRequiredCore = 1; - Object.defineProperty(core, "__esModule", { value: true }); - const id_1 = /*@__PURE__*/ requireId(); - const ref_1 = /*@__PURE__*/ requireRef(); - const core$1 = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default, - ]; - core.default = core$1; - return core; -} - -var validation$2 = {}; - -var limitNumber = {}; - -var hasRequiredLimitNumber; - -function requireLimitNumber () { - if (hasRequiredLimitNumber) return limitNumber; - hasRequiredLimitNumber = 1; - Object.defineProperty(limitNumber, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - }, - }; - limitNumber.default = def; - return limitNumber; -} - -var multipleOf = {}; - -var hasRequiredMultipleOf; - -function requireMultipleOf () { - if (hasRequiredMultipleOf) return multipleOf; - hasRequiredMultipleOf = 1; - Object.defineProperty(multipleOf, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const error = { - message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`, - }; - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec - ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` - : (0, codegen_1._) `${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - }, - }; - multipleOf.default = def; - return multipleOf; -} - -var limitLength = {}; - -var ucs2length = {}; - -var hasRequiredUcs2length; - -function requireUcs2length () { - if (hasRequiredUcs2length) return ucs2length; - hasRequiredUcs2length = 1; - Object.defineProperty(ucs2length, "__esModule", { value: true }); - function ucs2length$1(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 0xd800 && value <= 0xdbff && pos < len) { - value = str.charCodeAt(pos); - if ((value & 0xfc00) === 0xdc00) - pos++; - } - } - return length; - } - ucs2length.default = ucs2length$1; - ucs2length$1.code = 'require("ajv/dist/runtime/ucs2length").default'; - return ucs2length; -} - -var hasRequiredLimitLength; - -function requireLimitLength () { - if (hasRequiredLimitLength) return limitLength; - hasRequiredLimitLength = 1; - Object.defineProperty(limitLength, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const ucs2length_1 = /*@__PURE__*/ requireUcs2length(); - const error = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, - }; - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`); - }, - }; - limitLength.default = def; - return limitLength; -} - -var pattern = {}; - -var hasRequiredPattern; - -function requirePattern () { - if (hasRequiredPattern) return pattern; - hasRequiredPattern = 1; - Object.defineProperty(pattern, "__esModule", { value: true }); - const code_1 = /*@__PURE__*/ requireCode(); - const util_1 = /*@__PURE__*/ requireUtil(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const error = { - message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`, - }; - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._) `!${valid}`); - } - else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`); - } - }, - }; - pattern.default = def; - return pattern; -} - -var limitProperties = {}; - -var hasRequiredLimitProperties; - -function requireLimitProperties () { - if (hasRequiredLimitProperties) return limitProperties; - hasRequiredLimitProperties = 1; - Object.defineProperty(limitProperties, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const error = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, - }; - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`); - }, - }; - limitProperties.default = def; - return limitProperties; -} - -var required = {}; - -var hasRequiredRequired; - -function requireRequired () { - if (hasRequiredRequired) return required; - hasRequiredRequired = 1; - Object.defineProperty(required, "__esModule", { value: true }); - const code_1 = /*@__PURE__*/ requireCode(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`, - }; - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) - return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) - allErrorsMode(); - else - exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) { - if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - } - function allErrorsMode() { - if (useLoop || $data) { - cxt.block$data(codegen_1.nil, loopAllRequired); - } - else { - for (const prop of schema) { - (0, code_1.checkReportMissingProp)(cxt, prop); - } - } - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } - else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - }, - }; - required.default = def; - return required; -} - -var limitItems = {}; - -var hasRequiredLimitItems; - -function requireLimitItems () { - if (hasRequiredLimitItems) return limitItems; - hasRequiredLimitItems = 1; - Object.defineProperty(limitItems, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const error = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`, - }; - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`); - }, - }; - limitItems.default = def; - return limitItems; -} - -var uniqueItems = {}; - -var equal = {}; - -var hasRequiredEqual; - -function requireEqual () { - if (hasRequiredEqual) return equal; - hasRequiredEqual = 1; - Object.defineProperty(equal, "__esModule", { value: true }); - const equal$1 = requireFastDeepEqual(); - equal$1.code = 'require("ajv/dist/runtime/equal").default'; - equal.default = equal$1; - return equal; -} - -var hasRequiredUniqueItems; - -function requireUniqueItems () { - if (hasRequiredUniqueItems) return uniqueItems; - hasRequiredUniqueItems = 1; - Object.defineProperty(uniqueItems, "__esModule", { value: true }); - const dataType_1 = /*@__PURE__*/ requireDataType(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const equal_1 = /*@__PURE__*/ requireEqual(); - const error = { - message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`, - }; - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) - return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._) `${data}.length`); - const j = gen.let("j"); - cxt.setParams({ i, j }); - gen.assign(valid, true); - gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._) `{}`); - gen.for((0, codegen_1._) `;${i}--;`, () => { - gen.let(item, (0, codegen_1._) `${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._) `continue`); - if (itemTypes.length > 1) - gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`); - gen - .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._) `${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }) - .code((0, codegen_1._) `${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - }, - }; - uniqueItems.default = def; - return uniqueItems; -} - -var _const = {}; - -var hasRequired_const; - -function require_const () { - if (hasRequired_const) return _const; - hasRequired_const = 1; - Object.defineProperty(_const, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const equal_1 = /*@__PURE__*/ requireEqual(); - const error = { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`, - }; - const def = { - keyword: "const", - $data: true, - error, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || (schema && typeof schema == "object")) { - cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - } - else { - cxt.fail((0, codegen_1._) `${schema} !== ${data}`); - } - }, - }; - _const.default = def; - return _const; -} - -var _enum = {}; - -var hasRequired_enum; - -function require_enum () { - if (hasRequired_enum) return _enum; - hasRequired_enum = 1; - Object.defineProperty(_enum, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const equal_1 = /*@__PURE__*/ requireEqual(); - const error = { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`, - }; - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) - throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default))); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } - else { - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null - ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])` - : (0, codegen_1._) `${data} === ${sch}`; - } - }, - }; - _enum.default = def; - return _enum; -} - -var hasRequiredValidation$1; - -function requireValidation$1 () { - if (hasRequiredValidation$1) return validation$2; - hasRequiredValidation$1 = 1; - Object.defineProperty(validation$2, "__esModule", { value: true }); - const limitNumber_1 = /*@__PURE__*/ requireLimitNumber(); - const multipleOf_1 = /*@__PURE__*/ requireMultipleOf(); - const limitLength_1 = /*@__PURE__*/ requireLimitLength(); - const pattern_1 = /*@__PURE__*/ requirePattern(); - const limitProperties_1 = /*@__PURE__*/ requireLimitProperties(); - const required_1 = /*@__PURE__*/ requireRequired(); - const limitItems_1 = /*@__PURE__*/ requireLimitItems(); - const uniqueItems_1 = /*@__PURE__*/ requireUniqueItems(); - const const_1 = /*@__PURE__*/ require_const(); - const enum_1 = /*@__PURE__*/ require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { keyword: "type", schemaType: ["string", "array"] }, - { keyword: "nullable", schemaType: "boolean" }, - const_1.default, - enum_1.default, - ]; - validation$2.default = validation; - return validation$2; -} - -var applicator = {}; - -var additionalItems = {}; - -var hasRequiredAdditionalItems; - -function requireAdditionalItems () { - if (hasRequiredAdditionalItems) return additionalItems; - hasRequiredAdditionalItems = 1; - Object.defineProperty(additionalItems, "__esModule", { value: true }); - additionalItems.validateAdditionalItems = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, - }; - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); - return; - } - validateAdditionalItems(cxt, items); - }, - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._) `${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._) `${len} <= ${items.length}`); - } - else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); - if (!it.allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - additionalItems.validateAdditionalItems = validateAdditionalItems; - additionalItems.default = def; - return additionalItems; -} - -var prefixItems = {}; - -var items = {}; - -var hasRequiredItems; - -function requireItems () { - if (hasRequiredItems) return items; - hasRequiredItems = 1; - Object.defineProperty(items, "__esModule", { value: true }); - items.validateTuple = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const code_1 = /*@__PURE__*/ requireCode(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "array", "boolean"], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) - return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - cxt.ok((0, code_1.validateArray)(cxt)); - }, - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) { - it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - } - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._) `${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i, - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - items.validateTuple = validateTuple; - items.default = def; - return items; -} - -var hasRequiredPrefixItems; - -function requirePrefixItems () { - if (hasRequiredPrefixItems) return prefixItems; - hasRequiredPrefixItems = 1; - Object.defineProperty(prefixItems, "__esModule", { value: true }); - const items_1 = /*@__PURE__*/ requireItems(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items"), - }; - prefixItems.default = def; - return prefixItems; -} - -var items2020 = {}; - -var hasRequiredItems2020; - -function requireItems2020 () { - if (hasRequiredItems2020) return items2020; - hasRequiredItems2020 = 1; - Object.defineProperty(items2020, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const code_1 = /*@__PURE__*/ requireCode(); - const additionalItems_1 = /*@__PURE__*/ requireAdditionalItems(); - const error = { - message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`, - }; - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - if (prefixItems) - (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else - cxt.ok((0, code_1.validateArray)(cxt)); - }, - }; - items2020.default = def; - return items2020; -} - -var contains = {}; - -var hasRequiredContains; - -function requireContains () { - if (hasRequiredContains) return contains; - hasRequiredContains = 1; - Object.defineProperty(contains, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: ({ params: { min, max } }) => max === undefined - ? (0, codegen_1.str) `must contain at least ${min} valid item(s)` - : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`, - }; - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === undefined ? 1 : minContains; - max = maxContains; - } - else { - min = 1; - } - const len = gen.const("len", (0, codegen_1._) `${data}.length`); - cxt.setParams({ min, max }); - if (max === undefined && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== undefined && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._) `${len} >= ${min}`; - if (max !== undefined) - cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === undefined && min === 1) { - validateItems(valid, () => gen.if(valid, () => gen.break())); - } - else if (min === 0) { - gen.let(valid, true); - if (max !== undefined) - gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount); - } - else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true, - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._) `${count}++`); - if (max === undefined) { - gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break()); - } - else { - gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) - gen.assign(valid, true); - else - gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - }, - }; - contains.default = def; - return contains; -} - -var dependencies = {}; - -var hasRequiredDependencies; - -function requireDependencies () { - if (hasRequiredDependencies) return dependencies; - hasRequiredDependencies = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.validateSchemaDeps = exports$1.validatePropertyDeps = exports$1.error = void 0; - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const code_1 = /*@__PURE__*/ requireCode(); - exports$1.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}`, - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports$1.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - }, - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") - continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) - return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) - continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", "), - }); - if (it.allErrors) { - gen.if(hasProperty, () => { - for (const depProp of deps) { - (0, code_1.checkReportMissingProp)(cxt, depProp); - } - }); - } - else { - gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports$1.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) - continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true) - ); - cxt.ok(valid); - } - } - exports$1.validateSchemaDeps = validateSchemaDeps; - exports$1.default = def; - } (dependencies)); - return dependencies; -} - -var propertyNames = {}; - -var hasRequiredPropertyNames; - -function requirePropertyNames () { - if (hasRequiredPropertyNames) return propertyNames; - hasRequiredPropertyNames = 1; - Object.defineProperty(propertyNames, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`, - }; - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true, - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) - gen.break(); - }); - }); - cxt.ok(valid); - }, - }; - propertyNames.default = def; - return propertyNames; -} - -var additionalProperties = {}; - -var hasRequiredAdditionalProperties; - -function requireAdditionalProperties () { - if (hasRequiredAdditionalProperties) return additionalProperties; - hasRequiredAdditionalProperties = 1; - Object.defineProperty(additionalProperties, "__esModule", { value: true }); - const code_1 = /*@__PURE__*/ requireCode(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const names_1 = /*@__PURE__*/ requireNames(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`, - }; - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - if (!errsCount) - throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) - return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) - additionalPropertyCode(key); - else - gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } - else if (props.length) { - definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`)); - } - else { - definedProp = codegen_1.nil; - } - if (patProps.length) { - definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - } - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._) `delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) - gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } - else { - applyAdditionalSchema(key, valid); - if (!allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str, - }; - if (errors === false) { - Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false, - }); - } - cxt.subschema(subschema, valid); - } - }, - }; - additionalProperties.default = def; - return additionalProperties; -} - -var properties$1 = {}; - -var hasRequiredProperties; - -function requireProperties () { - if (hasRequiredProperties) return properties$1; - hasRequiredProperties = 1; - Object.defineProperty(properties$1, "__esModule", { value: true }); - const validate_1 = /*@__PURE__*/ requireValidate(); - const code_1 = /*@__PURE__*/ requireCode(); - const util_1 = /*@__PURE__*/ requireUtil(); - const additionalProperties_1 = /*@__PURE__*/ requireAdditionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { - additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - } - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) { - it.definedProperties.add(prop); - } - if (it.opts.unevaluated && allProps.length && it.props !== true) { - it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - } - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) - return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) { - applyPropertySchema(prop); - } - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) - gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop, - }, valid); - } - }, - }; - properties$1.default = def; - return properties$1; -} - -var patternProperties = {}; - -var hasRequiredPatternProperties; - -function requirePatternProperties () { - if (hasRequiredPatternProperties) return patternProperties; - hasRequiredPatternProperties = 1; - Object.defineProperty(patternProperties, "__esModule", { value: true }); - const code_1 = /*@__PURE__*/ requireCode(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const util_2 = /*@__PURE__*/ requireUtil(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || - (alwaysValidPatterns.length === patterns.length && - (!it.opts.unevaluated || it.props === true))) { - return; - } - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) { - it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - } - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) - checkMatchingProperties(pat); - if (it.allErrors) { - validateProperties(pat); - } - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) { - if (new RegExp(pat).test(prop)) { - (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - } - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) { - cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str, - }, valid); - } - if (it.opts.unevaluated && props !== true) { - gen.assign((0, codegen_1._) `${props}[${key}]`, true); - } - else if (!alwaysValid && !it.allErrors) { - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - }); - }); - } - }, - }; - patternProperties.default = def; - return patternProperties; -} - -var not = {}; - -var hasRequiredNot; - -function requireNot () { - if (hasRequiredNot) return not; - hasRequiredNot = 1; - Object.defineProperty(not, "__esModule", { value: true }); - const util_1 = /*@__PURE__*/ requireUtil(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false, - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" }, - }; - not.default = def; - return not; -} - -var anyOf = {}; - -var hasRequiredAnyOf; - -function requireAnyOf () { - if (hasRequiredAnyOf) return anyOf; - hasRequiredAnyOf = 1; - Object.defineProperty(anyOf, "__esModule", { value: true }); - const code_1 = /*@__PURE__*/ requireCode(); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: code_1.validateUnion, - error: { message: "must match a schema in anyOf" }, - }; - anyOf.default = def; - return anyOf; -} - -var oneOf = {}; - -var hasRequiredOneOf; - -function requireOneOf () { - if (hasRequiredOneOf) return oneOf; - hasRequiredOneOf = 1; - Object.defineProperty(oneOf, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`, - }; - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) - return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) { - gen.var(schValid, true); - } - else { - schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true, - }, schValid); - } - if (i > 0) { - gen - .if((0, codegen_1._) `${schValid} && ${valid}`) - .assign(valid, false) - .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`) - .else(); - } - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) - cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - }, - }; - oneOf.default = def; - return oneOf; -} - -var allOf = {}; - -var hasRequiredAllOf; - -function requireAllOf () { - if (hasRequiredAllOf) return allOf; - hasRequiredAllOf = 1; - Object.defineProperty(allOf, "__esModule", { value: true }); - const util_1 = /*@__PURE__*/ requireUtil(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - }, - }; - allOf.default = def; - return allOf; -} - -var _if = {}; - -var hasRequired_if; - -function require_if () { - if (hasRequired_if) return _if; - hasRequired_if = 1; - Object.defineProperty(_if, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`, - }; - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === undefined && parentSchema.else === undefined) { - (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); - } - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) - return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } - else if (hasThen) { - gen.if(schValid, validateClause("then")); - } - else { - gen.if((0, codegen_1.not)(schValid), validateClause("else")); - } - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false, - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) - gen.assign(ifClause, (0, codegen_1._) `${keyword}`); - else - cxt.setParams({ ifClause: keyword }); - }; - } - }, - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema); - } - _if.default = def; - return _if; -} - -var thenElse = {}; - -var hasRequiredThenElse; - -function requireThenElse () { - if (hasRequiredThenElse) return thenElse; - hasRequiredThenElse = 1; - Object.defineProperty(thenElse, "__esModule", { value: true }); - const util_1 = /*@__PURE__*/ requireUtil(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === undefined) - (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - }, - }; - thenElse.default = def; - return thenElse; -} - -var hasRequiredApplicator; - -function requireApplicator () { - if (hasRequiredApplicator) return applicator; - hasRequiredApplicator = 1; - Object.defineProperty(applicator, "__esModule", { value: true }); - const additionalItems_1 = /*@__PURE__*/ requireAdditionalItems(); - const prefixItems_1 = /*@__PURE__*/ requirePrefixItems(); - const items_1 = /*@__PURE__*/ requireItems(); - const items2020_1 = /*@__PURE__*/ requireItems2020(); - const contains_1 = /*@__PURE__*/ requireContains(); - const dependencies_1 = /*@__PURE__*/ requireDependencies(); - const propertyNames_1 = /*@__PURE__*/ requirePropertyNames(); - const additionalProperties_1 = /*@__PURE__*/ requireAdditionalProperties(); - const properties_1 = /*@__PURE__*/ requireProperties(); - const patternProperties_1 = /*@__PURE__*/ requirePatternProperties(); - const not_1 = /*@__PURE__*/ requireNot(); - const anyOf_1 = /*@__PURE__*/ requireAnyOf(); - const oneOf_1 = /*@__PURE__*/ requireOneOf(); - const allOf_1 = /*@__PURE__*/ requireAllOf(); - const if_1 = /*@__PURE__*/ require_if(); - const thenElse_1 = /*@__PURE__*/ requireThenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default, - ]; - if (draft2020) - applicator.push(prefixItems_1.default, items2020_1.default); - else - applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - applicator.default = getApplicator; - return applicator; -} - -var format$1 = {}; - -var format = {}; - -var hasRequiredFormat$1; - -function requireFormat$1 () { - if (hasRequiredFormat$1) return format; - hasRequiredFormat$1 = 1; - Object.defineProperty(format, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const error = { - message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`, - }; - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) - return; - if ($data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats, - }); - const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) - return codegen_1.nil; - return (0, codegen_1._) `${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async - ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` - : (0, codegen_1._) `${format}(${data})`; - const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) - return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) - cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp - ? (0, codegen_1.regexpCode)(fmtDef) - : opts.code.formats - ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` - : undefined; - const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { - return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`]; - } - return ["string", fmtDef, fmt]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) - throw new Error("async format in sync schema"); - return (0, codegen_1._) `await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`; - } - } - }, - }; - format.default = def; - return format; -} - -var hasRequiredFormat; - -function requireFormat () { - if (hasRequiredFormat) return format$1; - hasRequiredFormat = 1; - Object.defineProperty(format$1, "__esModule", { value: true }); - const format_1 = /*@__PURE__*/ requireFormat$1(); - const format = [format_1.default]; - format$1.default = format; - return format$1; -} - -var metadata = {}; - -var hasRequiredMetadata; - -function requireMetadata () { - if (hasRequiredMetadata) return metadata; - hasRequiredMetadata = 1; - Object.defineProperty(metadata, "__esModule", { value: true }); - metadata.contentVocabulary = metadata.metadataVocabulary = void 0; - metadata.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples", - ]; - metadata.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema", - ]; - return metadata; -} - -var hasRequiredDraft7; - -function requireDraft7 () { - if (hasRequiredDraft7) return draft7; - hasRequiredDraft7 = 1; - Object.defineProperty(draft7, "__esModule", { value: true }); - const core_1 = /*@__PURE__*/ requireCore(); - const validation_1 = /*@__PURE__*/ requireValidation$1(); - const applicator_1 = /*@__PURE__*/ requireApplicator(); - const format_1 = /*@__PURE__*/ requireFormat(); - const metadata_1 = /*@__PURE__*/ requireMetadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - ]; - draft7.default = draft7Vocabularies; - return draft7; -} - -var discriminator = {}; - -var types = {}; - -var hasRequiredTypes; - -function requireTypes () { - if (hasRequiredTypes) return types; - hasRequiredTypes = 1; - Object.defineProperty(types, "__esModule", { value: true }); - types.DiscrError = void 0; - var DiscrError; - (function (DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (types.DiscrError = DiscrError = {})); - return types; -} - -var hasRequiredDiscriminator; - -function requireDiscriminator () { - if (hasRequiredDiscriminator) return discriminator; - hasRequiredDiscriminator = 1; - Object.defineProperty(discriminator, "__esModule", { value: true }); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const types_1 = /*@__PURE__*/ requireTypes(); - const compile_1 = /*@__PURE__*/ requireCompile(); - const ref_error_1 = /*@__PURE__*/ requireRef_error(); - const util_1 = /*@__PURE__*/ requireUtil(); - const error = { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag - ? `tag "${tagName}" must be string` - : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`, - }; - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) { - throw new Error("discriminator: requires discriminator option"); - } - const tagName = schema.propertyName; - if (typeof tagName != "string") - throw new Error("discriminator: requires propertyName"); - if (schema.mapping) - throw new Error("discriminator: mapping is not supported"); - if (!oneOf) - throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) - sch = sch.schema; - if (sch === undefined) - throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") { - throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - } - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) - throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) { - addMapping(sch.const, i); - } - else if (sch.enum) { - for (const tagValue of sch.enum) { - addMapping(tagValue, i); - } - } - else { - throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) { - throw new Error(`discriminator: "${tagName}" values must be unique strings`); - } - oneOfMapping[tagValue] = i; - } - } - }, - }; - discriminator.default = def; - return discriminator; -} - -var $schema = "http://json-schema.org/draft-07/schema#"; -var $id = "http://json-schema.org/draft-07/schema#"; -var title = "Core schema meta-schema"; -var definitions = { - schemaArray: { - type: "array", - minItems: 1, - items: { - $ref: "#" - } - }, - nonNegativeInteger: { - type: "integer", - minimum: 0 - }, - nonNegativeIntegerDefault0: { - allOf: [ - { - $ref: "#/definitions/nonNegativeInteger" - }, - { - "default": 0 - } - ] - }, - simpleTypes: { - "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] - }, - stringArray: { - type: "array", - items: { - type: "string" - }, - uniqueItems: true, - "default": [ - ] - } -}; -var type = [ - "object", - "boolean" -]; -var properties = { - $id: { - type: "string", - format: "uri-reference" - }, - $schema: { - type: "string", - format: "uri" - }, - $ref: { - type: "string", - format: "uri-reference" - }, - $comment: { - type: "string" - }, - title: { - type: "string" - }, - description: { - type: "string" - }, - "default": true, - readOnly: { - type: "boolean", - "default": false - }, - examples: { - type: "array", - items: true - }, - multipleOf: { - type: "number", - exclusiveMinimum: 0 - }, - maximum: { - type: "number" - }, - exclusiveMaximum: { - type: "number" - }, - minimum: { - type: "number" - }, - exclusiveMinimum: { - type: "number" - }, - maxLength: { - $ref: "#/definitions/nonNegativeInteger" - }, - minLength: { - $ref: "#/definitions/nonNegativeIntegerDefault0" - }, - pattern: { - type: "string", - format: "regex" - }, - additionalItems: { - $ref: "#" - }, - items: { - anyOf: [ - { - $ref: "#" - }, - { - $ref: "#/definitions/schemaArray" - } - ], - "default": true - }, - maxItems: { - $ref: "#/definitions/nonNegativeInteger" - }, - minItems: { - $ref: "#/definitions/nonNegativeIntegerDefault0" - }, - uniqueItems: { - type: "boolean", - "default": false - }, - contains: { - $ref: "#" - }, - maxProperties: { - $ref: "#/definitions/nonNegativeInteger" - }, - minProperties: { - $ref: "#/definitions/nonNegativeIntegerDefault0" - }, - required: { - $ref: "#/definitions/stringArray" - }, - additionalProperties: { - $ref: "#" - }, - definitions: { - type: "object", - additionalProperties: { - $ref: "#" - }, - "default": { - } - }, - properties: { - type: "object", - additionalProperties: { - $ref: "#" - }, - "default": { - } - }, - patternProperties: { - type: "object", - additionalProperties: { - $ref: "#" - }, - propertyNames: { - format: "regex" - }, - "default": { - } - }, - dependencies: { - type: "object", - additionalProperties: { - anyOf: [ - { - $ref: "#" - }, - { - $ref: "#/definitions/stringArray" - } - ] - } - }, - propertyNames: { - $ref: "#" - }, - "const": true, - "enum": { - type: "array", - items: true, - minItems: 1, - uniqueItems: true - }, - type: { - anyOf: [ - { - $ref: "#/definitions/simpleTypes" - }, - { - type: "array", - items: { - $ref: "#/definitions/simpleTypes" - }, - minItems: 1, - uniqueItems: true - } - ] - }, - format: { - type: "string" - }, - contentMediaType: { - type: "string" - }, - contentEncoding: { - type: "string" - }, - "if": { - $ref: "#" - }, - then: { - $ref: "#" - }, - "else": { - $ref: "#" - }, - allOf: { - $ref: "#/definitions/schemaArray" - }, - anyOf: { - $ref: "#/definitions/schemaArray" - }, - oneOf: { - $ref: "#/definitions/schemaArray" - }, - not: { - $ref: "#" - } -}; -var require$$3 = { - $schema: $schema, - $id: $id, - title: title, - definitions: definitions, - type: type, - properties: properties, - "default": true -}; - -var hasRequiredAjv; - -function requireAjv () { - if (hasRequiredAjv) return ajv.exports; - hasRequiredAjv = 1; - (function (module, exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.MissingRefError = exports$1.ValidationError = exports$1.CodeGen = exports$1.Name = exports$1.nil = exports$1.stringify = exports$1.str = exports$1._ = exports$1.KeywordCxt = exports$1.Ajv = void 0; - const core_1 = /*@__PURE__*/ requireCore$1(); - const draft7_1 = /*@__PURE__*/ requireDraft7(); - const discriminator_1 = /*@__PURE__*/ requireDiscriminator(); - const draft7MetaSchema = require$$3; - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - class Ajv extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) - this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) - return; - const metaSchema = this.opts.$data - ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) - : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return (this.opts.defaultMeta = - super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)); - } - } - exports$1.Ajv = Ajv; - module.exports = exports$1 = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.default = Ajv; - var validate_1 = /*@__PURE__*/ requireValidate(); - Object.defineProperty(exports$1, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } }); - var codegen_1 = /*@__PURE__*/ requireCodegen(); - Object.defineProperty(exports$1, "_", { enumerable: true, get: function () { return codegen_1._; } }); - Object.defineProperty(exports$1, "str", { enumerable: true, get: function () { return codegen_1.str; } }); - Object.defineProperty(exports$1, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } }); - Object.defineProperty(exports$1, "nil", { enumerable: true, get: function () { return codegen_1.nil; } }); - Object.defineProperty(exports$1, "Name", { enumerable: true, get: function () { return codegen_1.Name; } }); - Object.defineProperty(exports$1, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } }); - var validation_error_1 = /*@__PURE__*/ requireValidation_error(); - Object.defineProperty(exports$1, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } }); - var ref_error_1 = /*@__PURE__*/ requireRef_error(); - Object.defineProperty(exports$1, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } }); - } (ajv, ajv.exports)); - return ajv.exports; -} - -var ajvExports = /*@__PURE__*/ requireAjv(); -var Ajv = /*@__PURE__*/getDefaultExportFromCjs(ajvExports); - -var dist = {exports: {}}; - -var formats = {}; - -var hasRequiredFormats; - -function requireFormats () { - if (hasRequiredFormats) return formats; - hasRequiredFormats = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.formatNames = exports$1.fastFormats = exports$1.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; - } - exports$1.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - byte, - int32: { type: "number", validate: validateInt32 }, - int64: { type: "number", validate: validateInt64 }, - float: { type: "number", validate: validateNumber }, - double: { type: "number", validate: validateNumber }, - password: true, - binary: true, - }; - exports$1.fastFormats = { - ...exports$1.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, - }; - exports$1.formatNames = Object.keys(exports$1.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return (month >= 1 && - month <= 12 && - day >= 1 && - day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month])); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) - return undefined; - if (d1 > d2) - return 1; - if (d1 < d2) - return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) - return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || (strictTimeZone && !tz)) - return false; - if (hr <= 23 && min <= 59 && sec < 60) - return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) - return undefined; - const t1 = new Date("2020-01-01T" + s1).valueOf(); - const t2 = new Date("2020-01-01T" + s2).valueOf(); - if (!(t1 && t2)) - return undefined; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) - return undefined; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) - return undefined; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) - return 1; - if (t1 < t2) - return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return undefined; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) - return undefined; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return undefined; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === undefined) - return undefined; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -2147483648; - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str); - return true; - } - catch (e) { - return false; - } - } - } (formats)); - return formats; -} - -var limit = {}; - -var hasRequiredLimit; - -function requireLimit () { - if (hasRequiredLimit) return limit; - hasRequiredLimit = 1; - (function (exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.formatLimitDefinition = void 0; - const ajv_1 = /*@__PURE__*/ requireAjv(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }, - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str) `should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`, - }; - exports$1.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) - return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats, - }); - const fmt = gen.const("fmt", (0, codegen_1._) `${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._) `typeof ${fmt} != "object"`, (0, codegen_1._) `${fmt} instanceof RegExp`, (0, codegen_1._) `typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) - return; - if (typeof fmtDef != "object" || - fmtDef instanceof RegExp || - typeof fmtDef.compare != "function") { - throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - } - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined, - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._) `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"], - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports$1.formatLimitDefinition); - return ajv; - }; - exports$1.default = formatLimitPlugin; - } (limit)); - return limit; -} - -var hasRequiredDist; - -function requireDist () { - if (hasRequiredDist) return dist.exports; - hasRequiredDist = 1; - (function (module, exports$1) { - Object.defineProperty(exports$1, "__esModule", { value: true }); - const formats_1 = requireFormats(); - const limit_1 = requireLimit(); - const codegen_1 = /*@__PURE__*/ requireCodegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - const list = opts.formats || formats_1.formatNames; - addFormats(ajv, list, formats, exportName); - if (opts.keywords) - (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; - const f = formats[name]; - if (!f) - throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = (0, codegen_1._) `require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) - ajv.addFormat(f, fs[f]); - } - module.exports = exports$1 = formatsPlugin; - Object.defineProperty(exports$1, "__esModule", { value: true }); - exports$1.default = formatsPlugin; - } (dist, dist.exports)); - return dist.exports; -} - -var distExports = requireDist(); -var _addFormats = /*@__PURE__*/getDefaultExportFromCjs(distExports); - -function createDefaultAjvInstance() { - const ajv = new Ajv({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - const addFormats = _addFormats; - addFormats(ajv); - return ajv; -} -class AjvJsonSchemaValidator { - constructor(ajv) { - this._ajv = ajv ?? createDefaultAjvInstance(); - } - getValidator(schema) { - const ajvValidator = '$id' in schema && typeof schema.$id === 'string' - ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) - : this._ajv.compile(schema); - return (input) => { - const valid = ajvValidator(input); - if (valid) { - return { - valid: true, - data: input, - errorMessage: undefined - }; - } - else { - return { - valid: false, - data: undefined, - errorMessage: this._ajv.errorsText(ajvValidator.errors) - }; - } - }; - } -} - -class ExperimentalServerTasks { - constructor(_server) { - this._server = _server; - } - requestStream(request, resultSchema, options) { - return this._server.requestStream(request, resultSchema, options); - } - async getTask(taskId, options) { - return this._server.getTask({ taskId }, options); - } - async getTaskResult(taskId, resultSchema, options) { - return this._server.getTaskResult({ taskId }, resultSchema, options); - } - async listTasks(cursor, options) { - return this._server.listTasks(cursor ? { cursor } : undefined, options); - } - async cancelTask(taskId, options) { - return this._server.cancelTask({ taskId }, options); - } -} - -function assertToolsCallTaskCapability(requests, method, entityName) { - if (!requests) { - throw new Error(`${entityName} does not support task creation (required for ${method})`); - } - switch (method) { - case 'tools/call': - if (!requests.tools?.call) { - throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); - } - break; - } -} -function assertClientRequestTaskCapability(requests, method, entityName) { - if (!requests) { - throw new Error(`${entityName} does not support task creation (required for ${method})`); - } - switch (method) { - case 'sampling/createMessage': - if (!requests.sampling?.createMessage) { - throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); - } - break; - case 'elicitation/create': - if (!requests.elicitation?.create) { - throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); - } - break; - } -} - -class Server extends Protocol { - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._loggingLevels = new Map(); - this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - this.isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - this._capabilities = options?.capabilities ?? {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); - this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); - if (this._capabilities.logging) { - this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { - const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined; - const { level } = request.params; - const parseResult = LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - get experimental() { - if (!this._experimental) { - this._experimental = { - tasks: new ExperimentalServerTasks(this) - }; - } - return this._experimental; - } - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - setRequestHandler(requestSchema, handler) { - const shape = getObjectShape(requestSchema); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - let methodValue; - if (isZ4Schema(methodSchema)) { - const v4Schema = methodSchema; - const v4Def = v4Schema._zod?.def; - methodValue = v4Def?.value ?? v4Schema.value; - } - else { - const v3Schema = methodSchema; - const legacyDef = v3Schema._def; - methodValue = legacyDef?.value ?? v3Schema.value; - } - if (typeof methodValue !== 'string') { - throw new Error('Schema method literal must be a string'); - } - const method = methodValue; - if (method === 'tools/call') { - const wrappedHandler = async (request, extra) => { - const validatedRequest = safeParse$1(CallToolRequestSchema, request); - if (!validatedRequest.success) { - const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); - } - const { params } = validatedRequest.data; - const result = await Promise.resolve(handler(request, extra)); - if (params.task) { - const taskValidationResult = safeParse$1(CreateTaskResultSchema, result); - if (!taskValidationResult.success) { - const errorMessage = taskValidationResult.error instanceof Error - ? taskValidationResult.error.message - : String(taskValidationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); - } - return taskValidationResult.data; - } - const validationResult = safeParse$1(CallToolResultSchema, result); - if (!validationResult.success) { - const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); - } - return validationResult.data; - }; - return super.setRequestHandler(requestSchema, wrappedHandler); - } - return super.setRequestHandler(requestSchema, handler); - } - assertCapabilityForMethod(method) { - switch (method) { - case 'sampling/createMessage': - if (!this._clientCapabilities?.sampling) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case 'elicitation/create': - if (!this._clientCapabilities?.elicitation) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case 'roots/list': - if (!this._clientCapabilities?.roots) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - } - } - assertNotificationCapability(method) { - switch (method) { - case 'notifications/message': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'notifications/resources/updated': - case 'notifications/resources/list_changed': - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case 'notifications/tools/list_changed': - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case 'notifications/prompts/list_changed': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case 'notifications/elicitation/complete': - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error(`Client does not support URL elicitation (required for ${method})`); - } - break; - } - } - assertRequestHandlerCapability(method) { - if (!this._capabilities) { - return; - } - switch (method) { - case 'completion/complete': - if (!this._capabilities.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case 'logging/setLevel': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'prompts/get': - case 'prompts/list': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case 'tools/call': - case 'tools/list': - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case 'tasks/get': - case 'tasks/list': - case 'tasks/result': - case 'tasks/cancel': - if (!this._capabilities.tasks) { - throw new Error(`Server does not support tasks capability (required for ${method})`); - } - break; - } - } - assertTaskCapability(method) { - assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client'); - } - assertTaskHandlerCapability(method) { - if (!this._capabilities) { - return; - } - assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server'); - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...(this._instructions && { instructions: this._instructions }) - }; - } - getClientCapabilities() { - return this._clientCapabilities; - } - getClientVersion() { - return this._clientVersion; - } - getCapabilities() { - return this._capabilities; - } - async ping() { - return this.request({ method: 'ping' }, EmptyResultSchema); - } - async createMessage(params, options) { - if (params.tools || params.toolChoice) { - if (!this._clientCapabilities?.sampling?.tools) { - throw new Error('Client does not support sampling tools capability.'); - } - } - if (params.messages.length > 0) { - const lastMessage = params.messages[params.messages.length - 1]; - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some(c => c.type === 'tool_result'); - const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined; - const previousContent = previousMessage - ? Array.isArray(previousMessage.content) - ? previousMessage.content - : [previousMessage.content] - : []; - const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use'); - if (hasToolResults) { - if (lastContent.some(c => c.type !== 'tool_result')) { - throw new Error('The last message must contain only tool_result content if any is present'); - } - if (!hasPreviousToolUse) { - throw new Error('tool_result blocks are not matching any tool_use from the previous message'); - } - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id)); - const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) { - throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match'); - } - } - } - if (params.tools) { - return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options); - } - return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); - } - async elicitInput(params, options) { - const mode = (params.mode ?? 'form'); - switch (mode) { - case 'url': { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error('Client does not support url elicitation.'); - } - const urlParams = params; - return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); - } - case 'form': { - if (!this._clientCapabilities?.elicitation?.form) { - throw new Error('Client does not support form elicitation.'); - } - const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' }; - const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); - if (result.action === 'accept' && result.content && formParams.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); - const validationResult = validator(result.content); - if (!validationResult.valid) { - throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } - } - catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - } - return result; - } - } - } - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); - } - return () => this.notification({ - method: 'notifications/elicitation/complete', - params: { - elicitationId - } - }, options); - } - async listRoots(params, options) { - return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); - } - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: 'notifications/message', params }); - } - } - } - async sendResourceUpdated(params) { - return this.notification({ - method: 'notifications/resources/updated', - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: 'notifications/resources/list_changed' - }); - } - async sendToolListChanged() { - return this.notification({ method: 'notifications/tools/list_changed' }); - } - async sendPromptListChanged() { - return this.notification({ method: 'notifications/prompts/list_changed' }); - } -} - -const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); -function isCompletable(schema) { - return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema; -} -function getCompleter(schema) { - const meta = schema[COMPLETABLE_SYMBOL]; - return meta?.complete; -} -var McpZodTypeKind; -(function (McpZodTypeKind) { - McpZodTypeKind["Completable"] = "McpCompletable"; -})(McpZodTypeKind || (McpZodTypeKind = {})); - -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -function validateToolName(name) { - const warnings = []; - if (name.length === 0) { - return { - isValid: false, - warnings: ['Tool name cannot be empty'] - }; - } - if (name.length > 128) { - return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - } - if (name.includes(' ')) { - warnings.push('Tool name contains spaces, which may cause parsing issues'); - } - if (name.includes(',')) { - warnings.push('Tool name contains commas, which may cause parsing issues'); - } - if (name.startsWith('-') || name.endsWith('-')) { - warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); - } - if (name.startsWith('.') || name.endsWith('.')) { - warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); - } - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = name - .split('') - .filter(char => !/[A-Za-z0-9._-]/.test(char)) - .filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) { - console.warn(` - ${warning}`); - } - console.warn('Tool registration will proceed, but this may cause compatibility issues.'); - console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); - console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); - } -} -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -class ExperimentalMcpServerTasks { - constructor(_mcpServer) { - this._mcpServer = _mcpServer; - } - registerToolTask(name, config, handler) { - const execution = { taskSupport: 'required', ...config.execution }; - if (execution.taskSupport === 'forbidden') { - throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`); - } - const mcpServerInternal = this._mcpServer; - return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler); - } -} - -class McpServer { - constructor(serverInfo, options) { - this._registeredResources = {}; - this._registeredResourceTemplates = {}; - this._registeredTools = {}; - this._registeredPrompts = {}; - this._toolHandlersInitialized = false; - this._completionHandlerInitialized = false; - this._resourceHandlersInitialized = false; - this._promptHandlersInitialized = false; - this.server = new Server(serverInfo, options); - } - get experimental() { - if (!this._experimental) { - this._experimental = { - tasks: new ExperimentalMcpServerTasks(this) - }; - } - return this._experimental; - } - async connect(transport) { - return await this.server.connect(transport); - } - async close() { - await this.server.close(); - } - setToolRequestHandlers() { - if (this._toolHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); - this.server.registerCapabilities({ - tools: { - listChanged: true - } - }); - this.server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: Object.entries(this._registeredTools) - .filter(([, tool]) => tool.enabled) - .map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: (() => { - const obj = normalizeObjectSchema(tool.inputSchema); - return obj - ? toJsonSchemaCompat(obj, { - strictUnions: true, - pipeStrategy: 'input' - }) - : EMPTY_OBJECT_JSON_SCHEMA; - })(), - annotations: tool.annotations, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) { - const obj = normalizeObjectSchema(tool.outputSchema); - if (obj) { - toolDefinition.outputSchema = toJsonSchemaCompat(obj, { - strictUnions: true, - pipeStrategy: 'output' - }); - } - } - return toolDefinition; - }) - })); - this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { - try { - const tool = this._registeredTools[request.params.name]; - if (!tool) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - } - if (!tool.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - } - const isTaskRequest = !!request.params.task; - const taskSupport = tool.execution?.taskSupport; - const isTaskHandler = 'createTask' in tool.handler; - if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) { - throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); - } - if (taskSupport === 'required' && !isTaskRequest) { - throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); - } - if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) { - return await this.handleAutomaticTaskPolling(tool, request, extra); - } - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, extra); - if (isTaskRequest) { - return result; - } - await this.validateToolOutput(tool, result, request.params.name); - return result; - } - catch (error) { - if (error instanceof McpError) { - if (error.code === ErrorCode.UrlElicitationRequired) { - throw error; - } - } - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - createToolError(errorMessage) { - return { - content: [ - { - type: 'text', - text: errorMessage - } - ], - isError: true - }; - } - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) { - return undefined; - } - const inputObj = normalizeObjectSchema(tool.inputSchema); - const schemaToParse = inputObj ?? tool.inputSchema; - const parseResult = await safeParseAsync$1(schemaToParse, args); - if (!parseResult.success) { - const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; - const errorMessage = getParseErrorMessage(error); - throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`); - } - return parseResult.data; - } - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) { - return; - } - if (!('content' in result)) { - return; - } - if (result.isError) { - return; - } - if (!result.structuredContent) { - throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - } - const outputObj = normalizeObjectSchema(tool.outputSchema); - const parseResult = await safeParseAsync$1(outputObj, result.structuredContent); - if (!parseResult.success) { - const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; - const errorMessage = getParseErrorMessage(error); - throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`); - } - } - async executeToolHandler(tool, args, extra) { - const handler = tool.handler; - const isTaskHandler = 'createTask' in handler; - if (isTaskHandler) { - if (!extra.taskStore) { - throw new Error('No task store provided.'); - } - const taskExtra = { ...extra, taskStore: extra.taskStore }; - if (tool.inputSchema) { - const typedHandler = handler; - return await Promise.resolve(typedHandler.createTask(args, taskExtra)); - } - else { - const typedHandler = handler; - return await Promise.resolve(typedHandler.createTask(taskExtra)); - } - } - if (tool.inputSchema) { - const typedHandler = handler; - return await Promise.resolve(typedHandler(args, extra)); - } - else { - const typedHandler = handler; - return await Promise.resolve(typedHandler(extra)); - } - } - async handleAutomaticTaskPolling(tool, request, extra) { - if (!extra.taskStore) { - throw new Error('No task store provided for task-capable tool.'); - } - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const handler = tool.handler; - const taskExtra = { ...extra, taskStore: extra.taskStore }; - const createTaskResult = args - ? await Promise.resolve(handler.createTask(args, taskExtra)) - : - await Promise.resolve(handler.createTask(taskExtra)); - const taskId = createTaskResult.task.taskId; - let task = createTaskResult.task; - const pollInterval = task.pollInterval ?? 5000; - while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') { - await new Promise(resolve => setTimeout(resolve, pollInterval)); - const updatedTask = await extra.taskStore.getTask(taskId); - if (!updatedTask) { - throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`); - } - task = updatedTask; - } - return (await extra.taskStore.getTaskResult(taskId)); - } - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); - this.server.registerCapabilities({ - completions: {} - }); - this.server.setRequestHandler(CompleteRequestSchema, async (request) => { - switch (request.params.ref.type) { - case 'ref/prompt': - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case 'ref/resource': - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: - throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - } - if (!prompt.argsSchema) { - return EMPTY_COMPLETION_RESULT; - } - const promptShape = getObjectShape(prompt.argsSchema); - const field = promptShape?.[request.params.argument.name]; - if (!isCompletable(field)) { - return EMPTY_COMPLETION_RESULT; - } - const completer = getCompleter(field); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) { - return EMPTY_COMPLETION_RESULT; - } - throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); - this.server.registerCapabilities({ - resources: { - listChanged: true - } - }); - this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { - const resources = Object.entries(this._registeredResources) - .filter(([_, resource]) => resource.enabled) - .map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) { - continue; - } - const result = await template.resourceTemplate.listCallback(extra); - for (const resource of result.resources) { - templateResources.push({ - ...template.metadata, - ...resource - }); - } - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { - const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })); - return { resourceTemplates }; - }); - this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { - const uri = new URL(request.params.uri); - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); - } - return resource.readCallback(uri, extra); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) { - return template.readCallback(uri, variables, extra); - } - } - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); - }); - this._resourceHandlersInitialized = true; - } - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); - this.server.registerCapabilities({ - prompts: { - listChanged: true - } - }); - this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ - prompts: Object.entries(this._registeredPrompts) - .filter(([, prompt]) => prompt.enabled) - .map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined - }; - }) - })); - this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - } - if (prompt.argsSchema) { - const argsObj = normalizeObjectSchema(prompt.argsSchema); - const parseResult = await safeParseAsync$1(argsObj, request.params.arguments); - if (!parseResult.success) { - const error = 'error' in parseResult ? parseResult.error : 'Unknown error'; - const errorMessage = getParseErrorMessage(error); - throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`); - } - const args = parseResult.data; - const cb = prompt.callback; - return await Promise.resolve(cb(args, extra)); - } - else { - const cb = prompt.callback; - return await Promise.resolve(cb(extra)); - } - }); - this._promptHandlersInitialized = true; - } - resource(name, uriOrTemplate, ...rest) { - let metadata; - if (typeof rest[0] === 'object') { - metadata = rest.shift(); - } - const readCallback = rest[0]; - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } - else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - registerResource(name, uriOrTemplate, config, readCallback) { - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } - else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: updates => { - if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) - this._registeredResources[updates.uri] = registeredResource; - } - if (typeof updates.name !== 'undefined') - registeredResource.name = updates.name; - if (typeof updates.title !== 'undefined') - registeredResource.title = updates.title; - if (typeof updates.metadata !== 'undefined') - registeredResource.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') - registeredResource.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) - this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (typeof updates.title !== 'undefined') - registeredResourceTemplate.title = updates.title; - if (typeof updates.template !== 'undefined') - registeredResourceTemplate.resourceTemplate = updates.template; - if (typeof updates.metadata !== 'undefined') - registeredResourceTemplate.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') - registeredResourceTemplate.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v)); - if (hasCompleter) { - this.setCompletionRequestHandler(); - } - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback) { - const registeredPrompt = { - title, - description, - argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema), - callback, - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) - this._registeredPrompts[updates.name] = registeredPrompt; - } - if (typeof updates.title !== 'undefined') - registeredPrompt.title = updates.title; - if (typeof updates.description !== 'undefined') - registeredPrompt.description = updates.description; - if (typeof updates.argsSchema !== 'undefined') - registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); - if (typeof updates.callback !== 'undefined') - registeredPrompt.callback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const hasCompletable = Object.values(argsSchema).some(field => { - const inner = field instanceof ZodOptional ? field._def?.innerType : field; - return isCompletable(inner); - }); - if (hasCompletable) { - this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { - validateAndWarnToolName(name); - const registeredTool = { - title, - description, - inputSchema: getZodSchemaObject(inputSchema), - outputSchema: getZodSchemaObject(outputSchema), - annotations, - execution, - _meta, - handler: handler, - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - if (typeof updates.name === 'string') { - validateAndWarnToolName(updates.name); - } - delete this._registeredTools[name]; - if (updates.name) - this._registeredTools[updates.name] = registeredTool; - } - if (typeof updates.title !== 'undefined') - registeredTool.title = updates.title; - if (typeof updates.description !== 'undefined') - registeredTool.description = updates.description; - if (typeof updates.paramsSchema !== 'undefined') - registeredTool.inputSchema = objectFromShape(updates.paramsSchema); - if (typeof updates.outputSchema !== 'undefined') - registeredTool.outputSchema = objectFromShape(updates.outputSchema); - if (typeof updates.callback !== 'undefined') - registeredTool.handler = updates.callback; - if (typeof updates.annotations !== 'undefined') - registeredTool.annotations = updates.annotations; - if (typeof updates._meta !== 'undefined') - registeredTool._meta = updates._meta; - if (typeof updates.enabled !== 'undefined') - registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - tool(name, ...rest) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - let description; - let inputSchema; - let outputSchema; - let annotations; - if (typeof rest[0] === 'string') { - description = rest.shift(); - } - if (rest.length > 1) { - const firstArg = rest[0]; - if (isZodRawShapeCompat(firstArg)) { - inputSchema = rest.shift(); - if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { - annotations = rest.shift(); - } - } - else if (typeof firstArg === 'object' && firstArg !== null) { - annotations = rest.shift(); - } - } - const callback = rest[0]; - return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback); - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - const { title, description, inputSchema, outputSchema, annotations, _meta } = config; - return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb); - } - prompt(name, ...rest) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - let description; - if (typeof rest[0] === 'string') { - description = rest.shift(); - } - let argsSchema; - if (rest.length > 1) { - argsSchema = rest.shift(); - } - const cb = rest[0]; - const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - const { title, description, argsSchema } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - isConnected() { - return this.server.transport !== undefined; - } - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - sendResourceListChanged() { - if (this.isConnected()) { - this.server.sendResourceListChanged(); - } - } - sendToolListChanged() { - if (this.isConnected()) { - this.server.sendToolListChanged(); - } - } - sendPromptListChanged() { - if (this.isConnected()) { - this.server.sendPromptListChanged(); - } - } -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: 'object', - properties: {} -}; -function isZodTypeLike(value) { - return (value !== null && - typeof value === 'object' && - 'parse' in value && - typeof value.parse === 'function' && - 'safeParse' in value && - typeof value.safeParse === 'function'); -} -function isZodSchemaInstance(obj) { - return '_def' in obj || '_zod' in obj || isZodTypeLike(obj); -} -function isZodRawShapeCompat(obj) { - if (typeof obj !== 'object' || obj === null) { - return false; - } - if (isZodSchemaInstance(obj)) { - return false; - } - if (Object.keys(obj).length === 0) { - return true; - } - return Object.values(obj).some(isZodTypeLike); -} -function getZodSchemaObject(schema) { - if (!schema) { - return undefined; - } - if (isZodRawShapeCompat(schema)) { - return objectFromShape(schema); - } - return schema; -} -function promptArgumentsFromSchema(schema) { - const shape = getObjectShape(schema); - if (!shape) - return []; - return Object.entries(shape).map(([name, field]) => { - const description = getSchemaDescription(field); - const isOptional = isSchemaOptional(field); - return { - name, - description, - required: !isOptional - }; - }); -} -function getMethodValue(schema) { - const shape = getObjectShape(schema); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - const value = getLiteralValue(methodSchema); - if (typeof value === 'string') { - return value; - } - throw new Error('Schema method literal must be a string'); -} -function createCompletionResult(suggestions) { - return { - completion: { - values: suggestions.slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } - }; -} -const EMPTY_COMPLETION_RESULT = { - completion: { - values: [], - hasMore: false - } -}; - -class ReadBuffer { - append(chunk) { - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - if (!this._buffer) { - return null; - } - const index = this._buffer.indexOf('\n'); - if (index === -1) { - return null; - } - const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); - this._buffer = this._buffer.subarray(index + 1); - return deserializeMessage(line); - } - clear() { - this._buffer = undefined; - } -} -function deserializeMessage(line) { - return JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + '\n'; -} - -class StdioServerTransport { - constructor(_stdin = process$2.stdin, _stdout = process$2.stdout) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer(); - this._started = false; - this._ondata = (chunk) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - this._onerror = (error) => { - this.onerror?.(error); - }; - } - async start() { - if (this._started) { - throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - this._started = true; - this._stdin.on('data', this._ondata); - this._stdin.on('error', this._onerror); - } - processReadBuffer() { - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - this.onmessage?.(message); - } - catch (error) { - this.onerror?.(error); - } - } - } - async close() { - this._stdin.off('data', this._ondata); - this._stdin.off('error', this._onerror); - const remainingDataListeners = this._stdin.listenerCount('data'); - if (remainingDataListeners === 0) { - this._stdin.pause(); - } - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - return new Promise(resolve => { - const json = serializeMessage(message); - if (this._stdout.write(json)) { - resolve(); - } - else { - this._stdout.once('drain', resolve); - } - }); - } -} - -var bufferUtil = {exports: {}}; - -var constants; -var hasRequiredConstants; - -function requireConstants () { - if (hasRequiredConstants) return constants; - hasRequiredConstants = 1; - const BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; - const hasBlob = typeof Blob !== 'undefined'; - if (hasBlob) BINARY_TYPES.push('blob'); - constants = { - BINARY_TYPES, - CLOSE_TIMEOUT: 30000, - EMPTY_BUFFER: Buffer.alloc(0), - GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', - hasBlob, - kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), - kListener: Symbol('kListener'), - kStatusCode: Symbol('status-code'), - kWebSocket: Symbol('websocket'), - NOOP: () => {} - }; - return constants; -} - -var hasRequiredBufferUtil; - -function requireBufferUtil () { - if (hasRequiredBufferUtil) return bufferUtil.exports; - hasRequiredBufferUtil = 1; - const { EMPTY_BUFFER } = requireConstants(); - const FastBuffer = Buffer[Symbol.species]; - function concat(list, totalLength) { - if (list.length === 0) return EMPTY_BUFFER; - if (list.length === 1) return list[0]; - const target = Buffer.allocUnsafe(totalLength); - let offset = 0; - for (let i = 0; i < list.length; i++) { - const buf = list[i]; - target.set(buf, offset); - offset += buf.length; - } - if (offset < totalLength) { - return new FastBuffer(target.buffer, target.byteOffset, offset); - } - return target; - } - function _mask(source, mask, output, offset, length) { - for (let i = 0; i < length; i++) { - output[offset + i] = source[i] ^ mask[i & 3]; - } - } - function _unmask(buffer, mask) { - for (let i = 0; i < buffer.length; i++) { - buffer[i] ^= mask[i & 3]; - } - } - function toArrayBuffer(buf) { - if (buf.length === buf.buffer.byteLength) { - return buf.buffer; - } - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); - } - function toBuffer(data) { - toBuffer.readOnly = true; - if (Buffer.isBuffer(data)) return data; - let buf; - if (data instanceof ArrayBuffer) { - buf = new FastBuffer(data); - } else if (ArrayBuffer.isView(data)) { - buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); - } else { - buf = Buffer.from(data); - toBuffer.readOnly = false; - } - return buf; - } - bufferUtil.exports = { - concat, - mask: _mask, - toArrayBuffer, - toBuffer, - unmask: _unmask - }; - if (!process.env.WS_NO_BUFFER_UTIL) { - try { - const bufferUtil$1 = require('bufferutil'); - bufferUtil.exports.mask = function (source, mask, output, offset, length) { - if (length < 48) _mask(source, mask, output, offset, length); - else bufferUtil$1.mask(source, mask, output, offset, length); - }; - bufferUtil.exports.unmask = function (buffer, mask) { - if (buffer.length < 32) _unmask(buffer, mask); - else bufferUtil$1.unmask(buffer, mask); - }; - } catch (e) { - } - } - return bufferUtil.exports; -} - -var limiter; -var hasRequiredLimiter; - -function requireLimiter () { - if (hasRequiredLimiter) return limiter; - hasRequiredLimiter = 1; - const kDone = Symbol('kDone'); - const kRun = Symbol('kRun'); - class Limiter { - constructor(concurrency) { - this[kDone] = () => { - this.pending--; - this[kRun](); - }; - this.concurrency = concurrency || Infinity; - this.jobs = []; - this.pending = 0; - } - add(job) { - this.jobs.push(job); - this[kRun](); - } - [kRun]() { - if (this.pending === this.concurrency) return; - if (this.jobs.length) { - const job = this.jobs.shift(); - this.pending++; - job(this[kDone]); - } - } - } - limiter = Limiter; - return limiter; -} - -var permessageDeflate; -var hasRequiredPermessageDeflate; - -function requirePermessageDeflate () { - if (hasRequiredPermessageDeflate) return permessageDeflate; - hasRequiredPermessageDeflate = 1; - const zlib = require$$0; - const bufferUtil = requireBufferUtil(); - const Limiter = requireLimiter(); - const { kStatusCode } = requireConstants(); - const FastBuffer = Buffer[Symbol.species]; - const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); - const kPerMessageDeflate = Symbol('permessage-deflate'); - const kTotalLength = Symbol('total-length'); - const kCallback = Symbol('callback'); - const kBuffers = Symbol('buffers'); - const kError = Symbol('error'); - let zlibLimiter; - class PerMessageDeflate { - constructor(options, isServer, maxPayload) { - this._maxPayload = maxPayload | 0; - this._options = options || {}; - this._threshold = - this._options.threshold !== undefined ? this._options.threshold : 1024; - this._isServer = !!isServer; - this._deflate = null; - this._inflate = null; - this.params = null; - if (!zlibLimiter) { - const concurrency = - this._options.concurrencyLimit !== undefined - ? this._options.concurrencyLimit - : 10; - zlibLimiter = new Limiter(concurrency); - } - } - static get extensionName() { - return 'permessage-deflate'; - } - offer() { - const params = {}; - if (this._options.serverNoContextTakeover) { - params.server_no_context_takeover = true; - } - if (this._options.clientNoContextTakeover) { - params.client_no_context_takeover = true; - } - if (this._options.serverMaxWindowBits) { - params.server_max_window_bits = this._options.serverMaxWindowBits; - } - if (this._options.clientMaxWindowBits) { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } else if (this._options.clientMaxWindowBits == null) { - params.client_max_window_bits = true; - } - return params; - } - accept(configurations) { - configurations = this.normalizeParams(configurations); - this.params = this._isServer - ? this.acceptAsServer(configurations) - : this.acceptAsClient(configurations); - return this.params; - } - cleanup() { - if (this._inflate) { - this._inflate.close(); - this._inflate = null; - } - if (this._deflate) { - const callback = this._deflate[kCallback]; - this._deflate.close(); - this._deflate = null; - if (callback) { - callback( - new Error( - 'The deflate stream was closed while data was being processed' - ) - ); - } - } - } - acceptAsServer(offers) { - const opts = this._options; - const accepted = offers.find((params) => { - if ( - (opts.serverNoContextTakeover === false && - params.server_no_context_takeover) || - (params.server_max_window_bits && - (opts.serverMaxWindowBits === false || - (typeof opts.serverMaxWindowBits === 'number' && - opts.serverMaxWindowBits > params.server_max_window_bits))) || - (typeof opts.clientMaxWindowBits === 'number' && - !params.client_max_window_bits) - ) { - return false; - } - return true; - }); - if (!accepted) { - throw new Error('None of the extension offers can be accepted'); - } - if (opts.serverNoContextTakeover) { - accepted.server_no_context_takeover = true; - } - if (opts.clientNoContextTakeover) { - accepted.client_no_context_takeover = true; - } - if (typeof opts.serverMaxWindowBits === 'number') { - accepted.server_max_window_bits = opts.serverMaxWindowBits; - } - if (typeof opts.clientMaxWindowBits === 'number') { - accepted.client_max_window_bits = opts.clientMaxWindowBits; - } else if ( - accepted.client_max_window_bits === true || - opts.clientMaxWindowBits === false - ) { - delete accepted.client_max_window_bits; - } - return accepted; - } - acceptAsClient(response) { - const params = response[0]; - if ( - this._options.clientNoContextTakeover === false && - params.client_no_context_takeover - ) { - throw new Error('Unexpected parameter "client_no_context_takeover"'); - } - if (!params.client_max_window_bits) { - if (typeof this._options.clientMaxWindowBits === 'number') { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } - } else if ( - this._options.clientMaxWindowBits === false || - (typeof this._options.clientMaxWindowBits === 'number' && - params.client_max_window_bits > this._options.clientMaxWindowBits) - ) { - throw new Error( - 'Unexpected or invalid parameter "client_max_window_bits"' - ); - } - return params; - } - normalizeParams(configurations) { - configurations.forEach((params) => { - Object.keys(params).forEach((key) => { - let value = params[key]; - if (value.length > 1) { - throw new Error(`Parameter "${key}" must have only a single value`); - } - value = value[0]; - if (key === 'client_max_window_bits') { - if (value !== true) { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (!this._isServer) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else if (key === 'server_max_window_bits') { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if ( - key === 'client_no_context_takeover' || - key === 'server_no_context_takeover' - ) { - if (value !== true) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else { - throw new Error(`Unknown parameter "${key}"`); - } - params[key] = value; - }); - }); - return configurations; - } - decompress(data, fin, callback) { - zlibLimiter.add((done) => { - this._decompress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - compress(data, fin, callback) { - zlibLimiter.add((done) => { - this._compress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - _decompress(data, fin, callback) { - const endpoint = this._isServer ? 'client' : 'server'; - if (!this._inflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = - typeof this.params[key] !== 'number' - ? zlib.Z_DEFAULT_WINDOWBITS - : this.params[key]; - this._inflate = zlib.createInflateRaw({ - ...this._options.zlibInflateOptions, - windowBits - }); - this._inflate[kPerMessageDeflate] = this; - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - this._inflate.on('error', inflateOnError); - this._inflate.on('data', inflateOnData); - } - this._inflate[kCallback] = callback; - this._inflate.write(data); - if (fin) this._inflate.write(TRAILER); - this._inflate.flush(() => { - const err = this._inflate[kError]; - if (err) { - this._inflate.close(); - this._inflate = null; - callback(err); - return; - } - const data = bufferUtil.concat( - this._inflate[kBuffers], - this._inflate[kTotalLength] - ); - if (this._inflate._readableState.endEmitted) { - this._inflate.close(); - this._inflate = null; - } else { - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._inflate.reset(); - } - } - callback(null, data); - }); - } - _compress(data, fin, callback) { - const endpoint = this._isServer ? 'server' : 'client'; - if (!this._deflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = - typeof this.params[key] !== 'number' - ? zlib.Z_DEFAULT_WINDOWBITS - : this.params[key]; - this._deflate = zlib.createDeflateRaw({ - ...this._options.zlibDeflateOptions, - windowBits - }); - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - this._deflate.on('data', deflateOnData); - } - this._deflate[kCallback] = callback; - this._deflate.write(data); - this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { - if (!this._deflate) { - return; - } - let data = bufferUtil.concat( - this._deflate[kBuffers], - this._deflate[kTotalLength] - ); - if (fin) { - data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); - } - this._deflate[kCallback] = null; - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._deflate.reset(); - } - callback(null, data); - }); - } - } - permessageDeflate = PerMessageDeflate; - function deflateOnData(chunk) { - this[kBuffers].push(chunk); - this[kTotalLength] += chunk.length; - } - function inflateOnData(chunk) { - this[kTotalLength] += chunk.length; - if ( - this[kPerMessageDeflate]._maxPayload < 1 || - this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload - ) { - this[kBuffers].push(chunk); - return; - } - this[kError] = new RangeError('Max payload size exceeded'); - this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; - this[kError][kStatusCode] = 1009; - this.removeListener('data', inflateOnData); - this.reset(); - } - function inflateOnError(err) { - this[kPerMessageDeflate]._inflate = null; - if (this[kError]) { - this[kCallback](this[kError]); - return; - } - err[kStatusCode] = 1007; - this[kCallback](err); - } - return permessageDeflate; -} - -var validation$1 = {exports: {}}; - -var hasRequiredValidation; - -function requireValidation () { - if (hasRequiredValidation) return validation$1.exports; - hasRequiredValidation = 1; - const { isUtf8 } = require$$0$1; - const { hasBlob } = requireConstants(); - const tokenChars = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 - ]; - function isValidStatusCode(code) { - return ( - (code >= 1000 && - code <= 1014 && - code !== 1004 && - code !== 1005 && - code !== 1006) || - (code >= 3000 && code <= 4999) - ); - } - function _isValidUTF8(buf) { - const len = buf.length; - let i = 0; - while (i < len) { - if ((buf[i] & 0x80) === 0) { - i++; - } else if ((buf[i] & 0xe0) === 0xc0) { - if ( - i + 1 === len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i] & 0xfe) === 0xc0 - ) { - return false; - } - i += 2; - } else if ((buf[i] & 0xf0) === 0xe0) { - if ( - i + 2 >= len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i + 2] & 0xc0) !== 0x80 || - (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || - (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) - ) { - return false; - } - i += 3; - } else if ((buf[i] & 0xf8) === 0xf0) { - if ( - i + 3 >= len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i + 2] & 0xc0) !== 0x80 || - (buf[i + 3] & 0xc0) !== 0x80 || - (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || - (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || - buf[i] > 0xf4 - ) { - return false; - } - i += 4; - } else { - return false; - } - } - return true; - } - function isBlob(value) { - return ( - hasBlob && - typeof value === 'object' && - typeof value.arrayBuffer === 'function' && - typeof value.type === 'string' && - typeof value.stream === 'function' && - (value[Symbol.toStringTag] === 'Blob' || - value[Symbol.toStringTag] === 'File') - ); - } - validation$1.exports = { - isBlob, - isValidStatusCode, - isValidUTF8: _isValidUTF8, - tokenChars - }; - if (isUtf8) { - validation$1.exports.isValidUTF8 = function (buf) { - return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); - }; - } else if (!process.env.WS_NO_UTF_8_VALIDATE) { - try { - const isValidUTF8 = require('utf-8-validate'); - validation$1.exports.isValidUTF8 = function (buf) { - return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); - }; - } catch (e) { - } - } - return validation$1.exports; -} - -var receiver; -var hasRequiredReceiver; - -function requireReceiver () { - if (hasRequiredReceiver) return receiver; - hasRequiredReceiver = 1; - const { Writable } = require$$0$2; - const PerMessageDeflate = requirePermessageDeflate(); - const { - BINARY_TYPES, - EMPTY_BUFFER, - kStatusCode, - kWebSocket - } = requireConstants(); - const { concat, toArrayBuffer, unmask } = requireBufferUtil(); - const { isValidStatusCode, isValidUTF8 } = requireValidation(); - const FastBuffer = Buffer[Symbol.species]; - const GET_INFO = 0; - const GET_PAYLOAD_LENGTH_16 = 1; - const GET_PAYLOAD_LENGTH_64 = 2; - const GET_MASK = 3; - const GET_DATA = 4; - const INFLATING = 5; - const DEFER_EVENT = 6; - class Receiver extends Writable { - constructor(options = {}) { - super(); - this._allowSynchronousEvents = - options.allowSynchronousEvents !== undefined - ? options.allowSynchronousEvents - : true; - this._binaryType = options.binaryType || BINARY_TYPES[0]; - this._extensions = options.extensions || {}; - this._isServer = !!options.isServer; - this._maxPayload = options.maxPayload | 0; - this._skipUTF8Validation = !!options.skipUTF8Validation; - this[kWebSocket] = undefined; - this._bufferedBytes = 0; - this._buffers = []; - this._compressed = false; - this._payloadLength = 0; - this._mask = undefined; - this._fragmented = 0; - this._masked = false; - this._fin = false; - this._opcode = 0; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragments = []; - this._errored = false; - this._loop = false; - this._state = GET_INFO; - } - _write(chunk, encoding, cb) { - if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); - this._bufferedBytes += chunk.length; - this._buffers.push(chunk); - this.startLoop(cb); - } - consume(n) { - this._bufferedBytes -= n; - if (n === this._buffers[0].length) return this._buffers.shift(); - if (n < this._buffers[0].length) { - const buf = this._buffers[0]; - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - return new FastBuffer(buf.buffer, buf.byteOffset, n); - } - const dst = Buffer.allocUnsafe(n); - do { - const buf = this._buffers[0]; - const offset = dst.length - n; - if (n >= buf.length) { - dst.set(this._buffers.shift(), offset); - } else { - dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - } - n -= buf.length; - } while (n > 0); - return dst; - } - startLoop(cb) { - this._loop = true; - do { - switch (this._state) { - case GET_INFO: - this.getInfo(cb); - break; - case GET_PAYLOAD_LENGTH_16: - this.getPayloadLength16(cb); - break; - case GET_PAYLOAD_LENGTH_64: - this.getPayloadLength64(cb); - break; - case GET_MASK: - this.getMask(); - break; - case GET_DATA: - this.getData(cb); - break; - case INFLATING: - case DEFER_EVENT: - this._loop = false; - return; - } - } while (this._loop); - if (!this._errored) cb(); - } - getInfo(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - const buf = this.consume(2); - if ((buf[0] & 0x30) !== 0x00) { - const error = this.createError( - RangeError, - 'RSV2 and RSV3 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_2_3' - ); - cb(error); - return; - } - const compressed = (buf[0] & 0x40) === 0x40; - if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { - const error = this.createError( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - cb(error); - return; - } - this._fin = (buf[0] & 0x80) === 0x80; - this._opcode = buf[0] & 0x0f; - this._payloadLength = buf[1] & 0x7f; - if (this._opcode === 0x00) { - if (compressed) { - const error = this.createError( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - cb(error); - return; - } - if (!this._fragmented) { - const error = this.createError( - RangeError, - 'invalid opcode 0', - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - cb(error); - return; - } - this._opcode = this._fragmented; - } else if (this._opcode === 0x01 || this._opcode === 0x02) { - if (this._fragmented) { - const error = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - cb(error); - return; - } - this._compressed = compressed; - } else if (this._opcode > 0x07 && this._opcode < 0x0b) { - if (!this._fin) { - const error = this.createError( - RangeError, - 'FIN must be set', - true, - 1002, - 'WS_ERR_EXPECTED_FIN' - ); - cb(error); - return; - } - if (compressed) { - const error = this.createError( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - cb(error); - return; - } - if ( - this._payloadLength > 0x7d || - (this._opcode === 0x08 && this._payloadLength === 1) - ) { - const error = this.createError( - RangeError, - `invalid payload length ${this._payloadLength}`, - true, - 1002, - 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' - ); - cb(error); - return; - } - } else { - const error = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - cb(error); - return; - } - if (!this._fin && !this._fragmented) this._fragmented = this._opcode; - this._masked = (buf[1] & 0x80) === 0x80; - if (this._isServer) { - if (!this._masked) { - const error = this.createError( - RangeError, - 'MASK must be set', - true, - 1002, - 'WS_ERR_EXPECTED_MASK' - ); - cb(error); - return; - } - } else if (this._masked) { - const error = this.createError( - RangeError, - 'MASK must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_MASK' - ); - cb(error); - return; - } - if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; - else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; - else this.haveLength(cb); - } - getPayloadLength16(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - this._payloadLength = this.consume(2).readUInt16BE(0); - this.haveLength(cb); - } - getPayloadLength64(cb) { - if (this._bufferedBytes < 8) { - this._loop = false; - return; - } - const buf = this.consume(8); - const num = buf.readUInt32BE(0); - if (num > Math.pow(2, 53 - 32) - 1) { - const error = this.createError( - RangeError, - 'Unsupported WebSocket frame: payload length > 2^53 - 1', - false, - 1009, - 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' - ); - cb(error); - return; - } - this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); - this.haveLength(cb); - } - haveLength(cb) { - if (this._payloadLength && this._opcode < 0x08) { - this._totalPayloadLength += this._payloadLength; - if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { - const error = this.createError( - RangeError, - 'Max payload size exceeded', - false, - 1009, - 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' - ); - cb(error); - return; - } - } - if (this._masked) this._state = GET_MASK; - else this._state = GET_DATA; - } - getMask() { - if (this._bufferedBytes < 4) { - this._loop = false; - return; - } - this._mask = this.consume(4); - this._state = GET_DATA; - } - getData(cb) { - let data = EMPTY_BUFFER; - if (this._payloadLength) { - if (this._bufferedBytes < this._payloadLength) { - this._loop = false; - return; - } - data = this.consume(this._payloadLength); - if ( - this._masked && - (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 - ) { - unmask(data, this._mask); - } - } - if (this._opcode > 0x07) { - this.controlMessage(data, cb); - return; - } - if (this._compressed) { - this._state = INFLATING; - this.decompress(data, cb); - return; - } - if (data.length) { - this._messageLength = this._totalPayloadLength; - this._fragments.push(data); - } - this.dataMessage(cb); - } - decompress(data, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - perMessageDeflate.decompress(data, this._fin, (err, buf) => { - if (err) return cb(err); - if (buf.length) { - this._messageLength += buf.length; - if (this._messageLength > this._maxPayload && this._maxPayload > 0) { - const error = this.createError( - RangeError, - 'Max payload size exceeded', - false, - 1009, - 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' - ); - cb(error); - return; - } - this._fragments.push(buf); - } - this.dataMessage(cb); - if (this._state === GET_INFO) this.startLoop(cb); - }); - } - dataMessage(cb) { - if (!this._fin) { - this._state = GET_INFO; - return; - } - const messageLength = this._messageLength; - const fragments = this._fragments; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragmented = 0; - this._fragments = []; - if (this._opcode === 2) { - let data; - if (this._binaryType === 'nodebuffer') { - data = concat(fragments, messageLength); - } else if (this._binaryType === 'arraybuffer') { - data = toArrayBuffer(concat(fragments, messageLength)); - } else if (this._binaryType === 'blob') { - data = new Blob(fragments); - } else { - data = fragments; - } - if (this._allowSynchronousEvents) { - this.emit('message', data, true); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit('message', data, true); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } else { - const buf = concat(fragments, messageLength); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error = this.createError( - Error, - 'invalid UTF-8 sequence', - true, - 1007, - 'WS_ERR_INVALID_UTF8' - ); - cb(error); - return; - } - if (this._state === INFLATING || this._allowSynchronousEvents) { - this.emit('message', buf, false); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit('message', buf, false); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - } - controlMessage(data, cb) { - if (this._opcode === 0x08) { - if (data.length === 0) { - this._loop = false; - this.emit('conclude', 1005, EMPTY_BUFFER); - this.end(); - } else { - const code = data.readUInt16BE(0); - if (!isValidStatusCode(code)) { - const error = this.createError( - RangeError, - `invalid status code ${code}`, - true, - 1002, - 'WS_ERR_INVALID_CLOSE_CODE' - ); - cb(error); - return; - } - const buf = new FastBuffer( - data.buffer, - data.byteOffset + 2, - data.length - 2 - ); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error = this.createError( - Error, - 'invalid UTF-8 sequence', - true, - 1007, - 'WS_ERR_INVALID_UTF8' - ); - cb(error); - return; - } - this._loop = false; - this.emit('conclude', code, buf); - this.end(); - } - this._state = GET_INFO; - return; - } - if (this._allowSynchronousEvents) { - this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - createError(ErrorCtor, message, prefix, statusCode, errorCode) { - this._loop = false; - this._errored = true; - const err = new ErrorCtor( - prefix ? `Invalid WebSocket frame: ${message}` : message - ); - Error.captureStackTrace(err, this.createError); - err.code = errorCode; - err[kStatusCode] = statusCode; - return err; - } - } - receiver = Receiver; - return receiver; -} - -var sender; -var hasRequiredSender; - -function requireSender () { - if (hasRequiredSender) return sender; - hasRequiredSender = 1; - const { Duplex } = require$$0$2; - const { randomFillSync } = require$$1; - const PerMessageDeflate = requirePermessageDeflate(); - const { EMPTY_BUFFER, kWebSocket, NOOP } = requireConstants(); - const { isBlob, isValidStatusCode } = requireValidation(); - const { mask: applyMask, toBuffer } = requireBufferUtil(); - const kByteLength = Symbol('kByteLength'); - const maskBuffer = Buffer.alloc(4); - const RANDOM_POOL_SIZE = 8 * 1024; - let randomPool; - let randomPoolPointer = RANDOM_POOL_SIZE; - const DEFAULT = 0; - const DEFLATING = 1; - const GET_BLOB_DATA = 2; - class Sender { - constructor(socket, extensions, generateMask) { - this._extensions = extensions || {}; - if (generateMask) { - this._generateMask = generateMask; - this._maskBuffer = Buffer.alloc(4); - } - this._socket = socket; - this._firstFragment = true; - this._compress = false; - this._bufferedBytes = 0; - this._queue = []; - this._state = DEFAULT; - this.onerror = NOOP; - this[kWebSocket] = undefined; - } - static frame(data, options) { - let mask; - let merge = false; - let offset = 2; - let skipMasking = false; - if (options.mask) { - mask = options.maskBuffer || maskBuffer; - if (options.generateMask) { - options.generateMask(mask); - } else { - if (randomPoolPointer === RANDOM_POOL_SIZE) { - if (randomPool === undefined) { - randomPool = Buffer.alloc(RANDOM_POOL_SIZE); - } - randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); - randomPoolPointer = 0; - } - mask[0] = randomPool[randomPoolPointer++]; - mask[1] = randomPool[randomPoolPointer++]; - mask[2] = randomPool[randomPoolPointer++]; - mask[3] = randomPool[randomPoolPointer++]; - } - skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; - offset = 6; - } - let dataLength; - if (typeof data === 'string') { - if ( - (!options.mask || skipMasking) && - options[kByteLength] !== undefined - ) { - dataLength = options[kByteLength]; - } else { - data = Buffer.from(data); - dataLength = data.length; - } - } else { - dataLength = data.length; - merge = options.mask && options.readOnly && !skipMasking; - } - let payloadLength = dataLength; - if (dataLength >= 65536) { - offset += 8; - payloadLength = 127; - } else if (dataLength > 125) { - offset += 2; - payloadLength = 126; - } - const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); - target[0] = options.fin ? options.opcode | 0x80 : options.opcode; - if (options.rsv1) target[0] |= 0x40; - target[1] = payloadLength; - if (payloadLength === 126) { - target.writeUInt16BE(dataLength, 2); - } else if (payloadLength === 127) { - target[2] = target[3] = 0; - target.writeUIntBE(dataLength, 4, 6); - } - if (!options.mask) return [target, data]; - target[1] |= 0x80; - target[offset - 4] = mask[0]; - target[offset - 3] = mask[1]; - target[offset - 2] = mask[2]; - target[offset - 1] = mask[3]; - if (skipMasking) return [target, data]; - if (merge) { - applyMask(data, mask, target, offset, dataLength); - return [target]; - } - applyMask(data, mask, data, 0, dataLength); - return [target, data]; - } - close(code, data, mask, cb) { - let buf; - if (code === undefined) { - buf = EMPTY_BUFFER; - } else if (typeof code !== 'number' || !isValidStatusCode(code)) { - throw new TypeError('First argument must be a valid error code number'); - } else if (data === undefined || !data.length) { - buf = Buffer.allocUnsafe(2); - buf.writeUInt16BE(code, 0); - } else { - const length = Buffer.byteLength(data); - if (length > 123) { - throw new RangeError('The message must not be greater than 123 bytes'); - } - buf = Buffer.allocUnsafe(2 + length); - buf.writeUInt16BE(code, 0); - if (typeof data === 'string') { - buf.write(data, 2); - } else { - buf.set(data, 2); - } - } - const options = { - [kByteLength]: buf.length, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x08, - readOnly: false, - rsv1: false - }; - if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, buf, false, options, cb]); - } else { - this.sendFrame(Sender.frame(buf, options), cb); - } - } - ping(data, mask, cb) { - let byteLength; - let readOnly; - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError('The data size must not be greater than 125 bytes'); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x09, - readOnly, - rsv1: false - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } - } - pong(data, mask, cb) { - let byteLength; - let readOnly; - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError('The data size must not be greater than 125 bytes'); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x0a, - readOnly, - rsv1: false - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } - } - send(data, options, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - let opcode = options.binary ? 2 : 1; - let rsv1 = options.compress; - let byteLength; - let readOnly; - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (this._firstFragment) { - this._firstFragment = false; - if ( - rsv1 && - perMessageDeflate && - perMessageDeflate.params[ - perMessageDeflate._isServer - ? 'server_no_context_takeover' - : 'client_no_context_takeover' - ] - ) { - rsv1 = byteLength >= perMessageDeflate._threshold; - } - this._compress = rsv1; - } else { - rsv1 = false; - opcode = 0; - } - if (options.fin) this._firstFragment = true; - const opts = { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1 - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, this._compress, opts, cb]); - } else { - this.getBlobData(data, this._compress, opts, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, this._compress, opts, cb]); - } else { - this.dispatch(data, this._compress, opts, cb); - } - } - getBlobData(blob, compress, options, cb) { - this._bufferedBytes += options[kByteLength]; - this._state = GET_BLOB_DATA; - blob - .arrayBuffer() - .then((arrayBuffer) => { - if (this._socket.destroyed) { - const err = new Error( - 'The socket was closed while the blob was being read' - ); - process.nextTick(callCallbacks, this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - const data = toBuffer(arrayBuffer); - if (!compress) { - this._state = DEFAULT; - this.sendFrame(Sender.frame(data, options), cb); - this.dequeue(); - } else { - this.dispatch(data, compress, options, cb); - } - }) - .catch((err) => { - process.nextTick(onError, this, err, cb); - }); - } - dispatch(data, compress, options, cb) { - if (!compress) { - this.sendFrame(Sender.frame(data, options), cb); - return; - } - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - this._bufferedBytes += options[kByteLength]; - this._state = DEFLATING; - perMessageDeflate.compress(data, options.fin, (_, buf) => { - if (this._socket.destroyed) { - const err = new Error( - 'The socket was closed while data was being compressed' - ); - callCallbacks(this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - this._state = DEFAULT; - options.readOnly = false; - this.sendFrame(Sender.frame(buf, options), cb); - this.dequeue(); - }); - } - dequeue() { - while (this._state === DEFAULT && this._queue.length) { - const params = this._queue.shift(); - this._bufferedBytes -= params[3][kByteLength]; - Reflect.apply(params[0], this, params.slice(1)); - } - } - enqueue(params) { - this._bufferedBytes += params[3][kByteLength]; - this._queue.push(params); - } - sendFrame(list, cb) { - if (list.length === 2) { - this._socket.cork(); - this._socket.write(list[0]); - this._socket.write(list[1], cb); - this._socket.uncork(); - } else { - this._socket.write(list[0], cb); - } - } - } - sender = Sender; - function callCallbacks(sender, err, cb) { - if (typeof cb === 'function') cb(err); - for (let i = 0; i < sender._queue.length; i++) { - const params = sender._queue[i]; - const callback = params[params.length - 1]; - if (typeof callback === 'function') callback(err); - } - } - function onError(sender, err, cb) { - callCallbacks(sender, err, cb); - sender.onerror(err); - } - return sender; -} - -var eventTarget; -var hasRequiredEventTarget; - -function requireEventTarget () { - if (hasRequiredEventTarget) return eventTarget; - hasRequiredEventTarget = 1; - const { kForOnEventAttribute, kListener } = requireConstants(); - const kCode = Symbol('kCode'); - const kData = Symbol('kData'); - const kError = Symbol('kError'); - const kMessage = Symbol('kMessage'); - const kReason = Symbol('kReason'); - const kTarget = Symbol('kTarget'); - const kType = Symbol('kType'); - const kWasClean = Symbol('kWasClean'); - class Event { - constructor(type) { - this[kTarget] = null; - this[kType] = type; - } - get target() { - return this[kTarget]; - } - get type() { - return this[kType]; - } - } - Object.defineProperty(Event.prototype, 'target', { enumerable: true }); - Object.defineProperty(Event.prototype, 'type', { enumerable: true }); - class CloseEvent extends Event { - constructor(type, options = {}) { - super(type); - this[kCode] = options.code === undefined ? 0 : options.code; - this[kReason] = options.reason === undefined ? '' : options.reason; - this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; - } - get code() { - return this[kCode]; - } - get reason() { - return this[kReason]; - } - get wasClean() { - return this[kWasClean]; - } - } - Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); - class ErrorEvent extends Event { - constructor(type, options = {}) { - super(type); - this[kError] = options.error === undefined ? null : options.error; - this[kMessage] = options.message === undefined ? '' : options.message; - } - get error() { - return this[kError]; - } - get message() { - return this[kMessage]; - } - } - Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); - Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); - class MessageEvent extends Event { - constructor(type, options = {}) { - super(type); - this[kData] = options.data === undefined ? null : options.data; - } - get data() { - return this[kData]; - } - } - Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); - const EventTarget = { - addEventListener(type, handler, options = {}) { - for (const listener of this.listeners(type)) { - if ( - !options[kForOnEventAttribute] && - listener[kListener] === handler && - !listener[kForOnEventAttribute] - ) { - return; - } - } - let wrapper; - if (type === 'message') { - wrapper = function onMessage(data, isBinary) { - const event = new MessageEvent('message', { - data: isBinary ? data : data.toString() - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'close') { - wrapper = function onClose(code, message) { - const event = new CloseEvent('close', { - code, - reason: message.toString(), - wasClean: this._closeFrameReceived && this._closeFrameSent - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'error') { - wrapper = function onError(error) { - const event = new ErrorEvent('error', { - error, - message: error.message - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'open') { - wrapper = function onOpen() { - const event = new Event('open'); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else { - return; - } - wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; - wrapper[kListener] = handler; - if (options.once) { - this.once(type, wrapper); - } else { - this.on(type, wrapper); - } - }, - removeEventListener(type, handler) { - for (const listener of this.listeners(type)) { - if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { - this.removeListener(type, listener); - break; - } - } - } - }; - eventTarget = { - CloseEvent, - ErrorEvent, - Event, - EventTarget, - MessageEvent - }; - function callListener(listener, thisArg, event) { - if (typeof listener === 'object' && listener.handleEvent) { - listener.handleEvent.call(listener, event); - } else { - listener.call(thisArg, event); - } - } - return eventTarget; -} - -var extension; -var hasRequiredExtension; - -function requireExtension () { - if (hasRequiredExtension) return extension; - hasRequiredExtension = 1; - const { tokenChars } = requireValidation(); - function push(dest, name, elem) { - if (dest[name] === undefined) dest[name] = [elem]; - else dest[name].push(elem); - } - function parse(header) { - const offers = Object.create(null); - let params = Object.create(null); - let mustUnescape = false; - let isEscaping = false; - let inQuotes = false; - let extensionName; - let paramName; - let start = -1; - let code = -1; - let end = -1; - let i = 0; - for (; i < header.length; i++) { - code = header.charCodeAt(i); - if (extensionName === undefined) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if ( - i !== 0 && - (code === 0x20 || code === 0x09) - ) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x3b || code === 0x2c ) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - const name = header.slice(start, end); - if (code === 0x2c) { - push(offers, name, params); - params = Object.create(null); - } else { - extensionName = name; - } - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (paramName === undefined) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (code === 0x20 || code === 0x09) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x3b || code === 0x2c) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - push(params, header.slice(start, end), true); - if (code === 0x2c) { - push(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - start = end = -1; - } else if (code === 0x3d && start !== -1 && end === -1) { - paramName = header.slice(start, i); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else { - if (isEscaping) { - if (tokenChars[code] !== 1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (start === -1) start = i; - else if (!mustUnescape) mustUnescape = true; - isEscaping = false; - } else if (inQuotes) { - if (tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (code === 0x22 && start !== -1) { - inQuotes = false; - end = i; - } else if (code === 0x5c ) { - isEscaping = true; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { - inQuotes = true; - } else if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if (start !== -1 && (code === 0x20 || code === 0x09)) { - if (end === -1) end = i; - } else if (code === 0x3b || code === 0x2c) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - let value = header.slice(start, end); - if (mustUnescape) { - value = value.replace(/\\/g, ''); - mustUnescape = false; - } - push(params, paramName, value); - if (code === 0x2c) { - push(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - paramName = undefined; - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - } - if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { - throw new SyntaxError('Unexpected end of input'); - } - if (end === -1) end = i; - const token = header.slice(start, end); - if (extensionName === undefined) { - push(offers, token, params); - } else { - if (paramName === undefined) { - push(params, token, true); - } else if (mustUnescape) { - push(params, paramName, token.replace(/\\/g, '')); - } else { - push(params, paramName, token); - } - push(offers, extensionName, params); - } - return offers; - } - function format(extensions) { - return Object.keys(extensions) - .map((extension) => { - let configurations = extensions[extension]; - if (!Array.isArray(configurations)) configurations = [configurations]; - return configurations - .map((params) => { - return [extension] - .concat( - Object.keys(params).map((k) => { - let values = params[k]; - if (!Array.isArray(values)) values = [values]; - return values - .map((v) => (v === true ? k : `${k}=${v}`)) - .join('; '); - }) - ) - .join('; '); - }) - .join(', '); - }) - .join(', '); - } - extension = { format, parse }; - return extension; -} - -var websocket; -var hasRequiredWebsocket; - -function requireWebsocket () { - if (hasRequiredWebsocket) return websocket; - hasRequiredWebsocket = 1; - const EventEmitter = require$$0$3; - const https = require$$1$1; - const http = require$$2; - const net = require$$3$1; - const tls = require$$4; - const { randomBytes, createHash } = require$$1; - const { Duplex, Readable } = require$$0$2; - const { URL } = require$$7; - const PerMessageDeflate = requirePermessageDeflate(); - const Receiver = requireReceiver(); - const Sender = requireSender(); - const { isBlob } = requireValidation(); - const { - BINARY_TYPES, - CLOSE_TIMEOUT, - EMPTY_BUFFER, - GUID, - kForOnEventAttribute, - kListener, - kStatusCode, - kWebSocket, - NOOP - } = requireConstants(); - const { - EventTarget: { addEventListener, removeEventListener } - } = requireEventTarget(); - const { format, parse } = requireExtension(); - const { toBuffer } = requireBufferUtil(); - const kAborted = Symbol('kAborted'); - const protocolVersions = [8, 13]; - const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; - const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; - class WebSocket extends EventEmitter { - constructor(address, protocols, options) { - super(); - this._binaryType = BINARY_TYPES[0]; - this._closeCode = 1006; - this._closeFrameReceived = false; - this._closeFrameSent = false; - this._closeMessage = EMPTY_BUFFER; - this._closeTimer = null; - this._errorEmitted = false; - this._extensions = {}; - this._paused = false; - this._protocol = ''; - this._readyState = WebSocket.CONNECTING; - this._receiver = null; - this._sender = null; - this._socket = null; - if (address !== null) { - this._bufferedAmount = 0; - this._isServer = false; - this._redirects = 0; - if (protocols === undefined) { - protocols = []; - } else if (!Array.isArray(protocols)) { - if (typeof protocols === 'object' && protocols !== null) { - options = protocols; - protocols = []; - } else { - protocols = [protocols]; - } - } - initAsClient(this, address, protocols, options); - } else { - this._autoPong = options.autoPong; - this._closeTimeout = options.closeTimeout; - this._isServer = true; - } - } - get binaryType() { - return this._binaryType; - } - set binaryType(type) { - if (!BINARY_TYPES.includes(type)) return; - this._binaryType = type; - if (this._receiver) this._receiver._binaryType = type; - } - get bufferedAmount() { - if (!this._socket) return this._bufferedAmount; - return this._socket._writableState.length + this._sender._bufferedBytes; - } - get extensions() { - return Object.keys(this._extensions).join(); - } - get isPaused() { - return this._paused; - } - get onclose() { - return null; - } - get onerror() { - return null; - } - get onopen() { - return null; - } - get onmessage() { - return null; - } - get protocol() { - return this._protocol; - } - get readyState() { - return this._readyState; - } - get url() { - return this._url; - } - setSocket(socket, head, options) { - const receiver = new Receiver({ - allowSynchronousEvents: options.allowSynchronousEvents, - binaryType: this.binaryType, - extensions: this._extensions, - isServer: this._isServer, - maxPayload: options.maxPayload, - skipUTF8Validation: options.skipUTF8Validation - }); - const sender = new Sender(socket, this._extensions, options.generateMask); - this._receiver = receiver; - this._sender = sender; - this._socket = socket; - receiver[kWebSocket] = this; - sender[kWebSocket] = this; - socket[kWebSocket] = this; - receiver.on('conclude', receiverOnConclude); - receiver.on('drain', receiverOnDrain); - receiver.on('error', receiverOnError); - receiver.on('message', receiverOnMessage); - receiver.on('ping', receiverOnPing); - receiver.on('pong', receiverOnPong); - sender.onerror = senderOnError; - if (socket.setTimeout) socket.setTimeout(0); - if (socket.setNoDelay) socket.setNoDelay(); - if (head.length > 0) socket.unshift(head); - socket.on('close', socketOnClose); - socket.on('data', socketOnData); - socket.on('end', socketOnEnd); - socket.on('error', socketOnError); - this._readyState = WebSocket.OPEN; - this.emit('open'); - } - emitClose() { - if (!this._socket) { - this._readyState = WebSocket.CLOSED; - this.emit('close', this._closeCode, this._closeMessage); - return; - } - if (this._extensions[PerMessageDeflate.extensionName]) { - this._extensions[PerMessageDeflate.extensionName].cleanup(); - } - this._receiver.removeAllListeners(); - this._readyState = WebSocket.CLOSED; - this.emit('close', this._closeCode, this._closeMessage); - } - close(code, data) { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - abortHandshake(this, this._req, msg); - return; - } - if (this.readyState === WebSocket.CLOSING) { - if ( - this._closeFrameSent && - (this._closeFrameReceived || this._receiver._writableState.errorEmitted) - ) { - this._socket.end(); - } - return; - } - this._readyState = WebSocket.CLOSING; - this._sender.close(code, data, !this._isServer, (err) => { - if (err) return; - this._closeFrameSent = true; - if ( - this._closeFrameReceived || - this._receiver._writableState.errorEmitted - ) { - this._socket.end(); - } - }); - setCloseTimer(this); - } - pause() { - if ( - this.readyState === WebSocket.CONNECTING || - this.readyState === WebSocket.CLOSED - ) { - return; - } - this._paused = true; - this._socket.pause(); - } - ping(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - if (typeof data === 'number') data = data.toString(); - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - if (mask === undefined) mask = !this._isServer; - this._sender.ping(data || EMPTY_BUFFER, mask, cb); - } - pong(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - if (typeof data === 'number') data = data.toString(); - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - if (mask === undefined) mask = !this._isServer; - this._sender.pong(data || EMPTY_BUFFER, mask, cb); - } - resume() { - if ( - this.readyState === WebSocket.CONNECTING || - this.readyState === WebSocket.CLOSED - ) { - return; - } - this._paused = false; - if (!this._receiver._writableState.needDrain) this._socket.resume(); - } - send(data, options, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - if (typeof options === 'function') { - cb = options; - options = {}; - } - if (typeof data === 'number') data = data.toString(); - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - const opts = { - binary: typeof data !== 'string', - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - if (!this._extensions[PerMessageDeflate.extensionName]) { - opts.compress = false; - } - this._sender.send(data || EMPTY_BUFFER, opts, cb); - } - terminate() { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - abortHandshake(this, this._req, msg); - return; - } - if (this._socket) { - this._readyState = WebSocket.CLOSING; - this._socket.destroy(); - } - } - } - Object.defineProperty(WebSocket, 'CONNECTING', { - enumerable: true, - value: readyStates.indexOf('CONNECTING') - }); - Object.defineProperty(WebSocket.prototype, 'CONNECTING', { - enumerable: true, - value: readyStates.indexOf('CONNECTING') - }); - Object.defineProperty(WebSocket, 'OPEN', { - enumerable: true, - value: readyStates.indexOf('OPEN') - }); - Object.defineProperty(WebSocket.prototype, 'OPEN', { - enumerable: true, - value: readyStates.indexOf('OPEN') - }); - Object.defineProperty(WebSocket, 'CLOSING', { - enumerable: true, - value: readyStates.indexOf('CLOSING') - }); - Object.defineProperty(WebSocket.prototype, 'CLOSING', { - enumerable: true, - value: readyStates.indexOf('CLOSING') - }); - Object.defineProperty(WebSocket, 'CLOSED', { - enumerable: true, - value: readyStates.indexOf('CLOSED') - }); - Object.defineProperty(WebSocket.prototype, 'CLOSED', { - enumerable: true, - value: readyStates.indexOf('CLOSED') - }); - [ - 'binaryType', - 'bufferedAmount', - 'extensions', - 'isPaused', - 'protocol', - 'readyState', - 'url' - ].forEach((property) => { - Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); - }); - ['open', 'error', 'close', 'message'].forEach((method) => { - Object.defineProperty(WebSocket.prototype, `on${method}`, { - enumerable: true, - get() { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) return listener[kListener]; - } - return null; - }, - set(handler) { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) { - this.removeListener(method, listener); - break; - } - } - if (typeof handler !== 'function') return; - this.addEventListener(method, handler, { - [kForOnEventAttribute]: true - }); - } - }); - }); - WebSocket.prototype.addEventListener = addEventListener; - WebSocket.prototype.removeEventListener = removeEventListener; - websocket = WebSocket; - function initAsClient(websocket, address, protocols, options) { - const opts = { - allowSynchronousEvents: true, - autoPong: true, - closeTimeout: CLOSE_TIMEOUT, - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - socketPath: undefined, - hostname: undefined, - protocol: undefined, - timeout: undefined, - method: 'GET', - host: undefined, - path: undefined, - port: undefined - }; - websocket._autoPong = opts.autoPong; - websocket._closeTimeout = opts.closeTimeout; - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError( - `Unsupported protocol version: ${opts.protocolVersion} ` + - `(supported versions: ${protocolVersions.join(', ')})` - ); - } - let parsedUrl; - if (address instanceof URL) { - parsedUrl = address; - } else { - try { - parsedUrl = new URL(address); - } catch (e) { - throw new SyntaxError(`Invalid URL: ${address}`); - } - } - if (parsedUrl.protocol === 'http:') { - parsedUrl.protocol = 'ws:'; - } else if (parsedUrl.protocol === 'https:') { - parsedUrl.protocol = 'wss:'; - } - websocket._url = parsedUrl.href; - const isSecure = parsedUrl.protocol === 'wss:'; - const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; - let invalidUrlMessage; - if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { - invalidUrlMessage = - 'The URL\'s protocol must be one of "ws:", "wss:", ' + - '"http:", "https:", or "ws+unix:"'; - } else if (isIpcUrl && !parsedUrl.pathname) { - invalidUrlMessage = "The URL's pathname is empty"; - } else if (parsedUrl.hash) { - invalidUrlMessage = 'The URL contains a fragment identifier'; - } - if (invalidUrlMessage) { - const err = new SyntaxError(invalidUrlMessage); - if (websocket._redirects === 0) { - throw err; - } else { - emitErrorAndClose(websocket, err); - return; - } - } - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes(16).toString('base64'); - const request = isSecure ? https.request : http.request; - const protocolSet = new Set(); - let perMessageDeflate; - opts.createConnection = - opts.createConnection || (isSecure ? tlsConnect : netConnect); - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith('[') - ? parsedUrl.hostname.slice(1, -1) - : parsedUrl.hostname; - opts.headers = { - ...opts.headers, - 'Sec-WebSocket-Version': opts.protocolVersion, - 'Sec-WebSocket-Key': key, - Connection: 'Upgrade', - Upgrade: 'websocket' - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - if (opts.perMessageDeflate) { - perMessageDeflate = new PerMessageDeflate( - opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, - false, - opts.maxPayload - ); - opts.headers['Sec-WebSocket-Extensions'] = format({ - [PerMessageDeflate.extensionName]: perMessageDeflate.offer() - }); - } - if (protocols.length) { - for (const protocol of protocols) { - if ( - typeof protocol !== 'string' || - !subprotocolRegex.test(protocol) || - protocolSet.has(protocol) - ) { - throw new SyntaxError( - 'An invalid or duplicated subprotocol was specified' - ); - } - protocolSet.add(protocol); - } - opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); - } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers['Sec-WebSocket-Origin'] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } - } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; - } - if (isIpcUrl) { - const parts = opts.path.split(':'); - opts.socketPath = parts[0]; - opts.path = parts[1]; - } - let req; - if (opts.followRedirects) { - if (websocket._redirects === 0) { - websocket._originalIpc = isIpcUrl; - websocket._originalSecure = isSecure; - websocket._originalHostOrSocketPath = isIpcUrl - ? opts.socketPath - : parsedUrl.host; - const headers = options && options.headers; - options = { ...options, headers: {} }; - if (headers) { - for (const [key, value] of Object.entries(headers)) { - options.headers[key.toLowerCase()] = value; - } - } - } else if (websocket.listenerCount('redirect') === 0) { - const isSameHost = isIpcUrl - ? websocket._originalIpc - ? opts.socketPath === websocket._originalHostOrSocketPath - : false - : websocket._originalIpc - ? false - : parsedUrl.host === websocket._originalHostOrSocketPath; - if (!isSameHost || (websocket._originalSecure && !isSecure)) { - delete opts.headers.authorization; - delete opts.headers.cookie; - if (!isSameHost) delete opts.headers.host; - opts.auth = undefined; - } - } - if (opts.auth && !options.headers.authorization) { - options.headers.authorization = - 'Basic ' + Buffer.from(opts.auth).toString('base64'); - } - req = websocket._req = request(opts); - if (websocket._redirects) { - websocket.emit('redirect', websocket.url, req); - } - } else { - req = websocket._req = request(opts); - } - if (opts.timeout) { - req.on('timeout', () => { - abortHandshake(websocket, req, 'Opening handshake has timed out'); - }); - } - req.on('error', (err) => { - if (req === null || req[kAborted]) return; - req = websocket._req = null; - emitErrorAndClose(websocket, err); - }); - req.on('response', (res) => { - const location = res.headers.location; - const statusCode = res.statusCode; - if ( - location && - opts.followRedirects && - statusCode >= 300 && - statusCode < 400 - ) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake(websocket, req, 'Maximum redirects exceeded'); - return; - } - req.abort(); - let addr; - try { - addr = new URL(location, address); - } catch (e) { - const err = new SyntaxError(`Invalid URL: ${location}`); - emitErrorAndClose(websocket, err); - return; - } - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit('unexpected-response', req, res)) { - abortHandshake( - websocket, - req, - `Unexpected server response: ${res.statusCode}` - ); - } - }); - req.on('upgrade', (res, socket, head) => { - websocket.emit('upgrade', res); - if (websocket.readyState !== WebSocket.CONNECTING) return; - req = websocket._req = null; - const upgrade = res.headers.upgrade; - if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { - abortHandshake(websocket, socket, 'Invalid Upgrade header'); - return; - } - const digest = createHash('sha1') - .update(key + GUID) - .digest('base64'); - if (res.headers['sec-websocket-accept'] !== digest) { - abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); - return; - } - const serverProt = res.headers['sec-websocket-protocol']; - let protError; - if (serverProt !== undefined) { - if (!protocolSet.size) { - protError = 'Server sent a subprotocol but none was requested'; - } else if (!protocolSet.has(serverProt)) { - protError = 'Server sent an invalid subprotocol'; - } - } else if (protocolSet.size) { - protError = 'Server sent no subprotocol'; - } - if (protError) { - abortHandshake(websocket, socket, protError); - return; - } - if (serverProt) websocket._protocol = serverProt; - const secWebSocketExtensions = res.headers['sec-websocket-extensions']; - if (secWebSocketExtensions !== undefined) { - if (!perMessageDeflate) { - const message = - 'Server sent a Sec-WebSocket-Extensions header but no extension ' + - 'was requested'; - abortHandshake(websocket, socket, message); - return; - } - let extensions; - try { - extensions = parse(secWebSocketExtensions); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Extensions header'; - abortHandshake(websocket, socket, message); - return; - } - const extensionNames = Object.keys(extensions); - if ( - extensionNames.length !== 1 || - extensionNames[0] !== PerMessageDeflate.extensionName - ) { - const message = 'Server indicated an extension that was not requested'; - abortHandshake(websocket, socket, message); - return; - } - try { - perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Extensions header'; - abortHandshake(websocket, socket, message); - return; - } - websocket._extensions[PerMessageDeflate.extensionName] = - perMessageDeflate; - } - websocket.setSocket(socket, head, { - allowSynchronousEvents: opts.allowSynchronousEvents, - generateMask: opts.generateMask, - maxPayload: opts.maxPayload, - skipUTF8Validation: opts.skipUTF8Validation - }); - }); - if (opts.finishRequest) { - opts.finishRequest(req, websocket); - } else { - req.end(); - } - } - function emitErrorAndClose(websocket, err) { - websocket._readyState = WebSocket.CLOSING; - websocket._errorEmitted = true; - websocket.emit('error', err); - websocket.emitClose(); - } - function netConnect(options) { - options.path = options.socketPath; - return net.connect(options); - } - function tlsConnect(options) { - options.path = undefined; - if (!options.servername && options.servername !== '') { - options.servername = net.isIP(options.host) ? '' : options.host; - } - return tls.connect(options); - } - function abortHandshake(websocket, stream, message) { - websocket._readyState = WebSocket.CLOSING; - const err = new Error(message); - Error.captureStackTrace(err, abortHandshake); - if (stream.setHeader) { - stream[kAborted] = true; - stream.abort(); - if (stream.socket && !stream.socket.destroyed) { - stream.socket.destroy(); - } - process.nextTick(emitErrorAndClose, websocket, err); - } else { - stream.destroy(err); - stream.once('error', websocket.emit.bind(websocket, 'error')); - stream.once('close', websocket.emitClose.bind(websocket)); - } - } - function sendAfterClose(websocket, data, cb) { - if (data) { - const length = isBlob(data) ? data.size : toBuffer(data).length; - if (websocket._socket) websocket._sender._bufferedBytes += length; - else websocket._bufferedAmount += length; - } - if (cb) { - const err = new Error( - `WebSocket is not open: readyState ${websocket.readyState} ` + - `(${readyStates[websocket.readyState]})` - ); - process.nextTick(cb, err); - } - } - function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket]; - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - if (websocket._socket[kWebSocket] === undefined) return; - websocket._socket.removeListener('data', socketOnData); - process.nextTick(resume, websocket._socket); - if (code === 1005) websocket.close(); - else websocket.close(code, reason); - } - function receiverOnDrain() { - const websocket = this[kWebSocket]; - if (!websocket.isPaused) websocket._socket.resume(); - } - function receiverOnError(err) { - const websocket = this[kWebSocket]; - if (websocket._socket[kWebSocket] !== undefined) { - websocket._socket.removeListener('data', socketOnData); - process.nextTick(resume, websocket._socket); - websocket.close(err[kStatusCode]); - } - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit('error', err); - } - } - function receiverOnFinish() { - this[kWebSocket].emitClose(); - } - function receiverOnMessage(data, isBinary) { - this[kWebSocket].emit('message', data, isBinary); - } - function receiverOnPing(data) { - const websocket = this[kWebSocket]; - if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP); - websocket.emit('ping', data); - } - function receiverOnPong(data) { - this[kWebSocket].emit('pong', data); - } - function resume(stream) { - stream.resume(); - } - function senderOnError(err) { - const websocket = this[kWebSocket]; - if (websocket.readyState === WebSocket.CLOSED) return; - if (websocket.readyState === WebSocket.OPEN) { - websocket._readyState = WebSocket.CLOSING; - setCloseTimer(websocket); - } - this._socket.end(); - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit('error', err); - } - } - function setCloseTimer(websocket) { - websocket._closeTimer = setTimeout( - websocket._socket.destroy.bind(websocket._socket), - websocket._closeTimeout - ); - } - function socketOnClose() { - const websocket = this[kWebSocket]; - this.removeListener('close', socketOnClose); - this.removeListener('data', socketOnData); - this.removeListener('end', socketOnEnd); - websocket._readyState = WebSocket.CLOSING; - if ( - !this._readableState.endEmitted && - !websocket._closeFrameReceived && - !websocket._receiver._writableState.errorEmitted && - this._readableState.length !== 0 - ) { - const chunk = this.read(this._readableState.length); - websocket._receiver.write(chunk); - } - websocket._receiver.end(); - this[kWebSocket] = undefined; - clearTimeout(websocket._closeTimer); - if ( - websocket._receiver._writableState.finished || - websocket._receiver._writableState.errorEmitted - ) { - websocket.emitClose(); - } else { - websocket._receiver.on('error', receiverOnFinish); - websocket._receiver.on('finish', receiverOnFinish); - } - } - function socketOnData(chunk) { - if (!this[kWebSocket]._receiver.write(chunk)) { - this.pause(); - } - } - function socketOnEnd() { - const websocket = this[kWebSocket]; - websocket._readyState = WebSocket.CLOSING; - websocket._receiver.end(); - this.end(); - } - function socketOnError() { - const websocket = this[kWebSocket]; - this.removeListener('error', socketOnError); - this.on('error', NOOP); - if (websocket) { - websocket._readyState = WebSocket.CLOSING; - this.destroy(); - } - } - return websocket; -} - -var stream; -var hasRequiredStream; - -function requireStream () { - if (hasRequiredStream) return stream; - hasRequiredStream = 1; - requireWebsocket(); - const { Duplex } = require$$0$2; - function emitClose(stream) { - stream.emit('close'); - } - function duplexOnEnd() { - if (!this.destroyed && this._writableState.finished) { - this.destroy(); - } - } - function duplexOnError(err) { - this.removeListener('error', duplexOnError); - this.destroy(); - if (this.listenerCount('error') === 0) { - this.emit('error', err); - } - } - function createWebSocketStream(ws, options) { - let terminateOnDestroy = true; - const duplex = new Duplex({ - ...options, - autoDestroy: false, - emitClose: false, - objectMode: false, - writableObjectMode: false - }); - ws.on('message', function message(msg, isBinary) { - const data = - !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; - if (!duplex.push(data)) ws.pause(); - }); - ws.once('error', function error(err) { - if (duplex.destroyed) return; - terminateOnDestroy = false; - duplex.destroy(err); - }); - ws.once('close', function close() { - if (duplex.destroyed) return; - duplex.push(null); - }); - duplex._destroy = function (err, callback) { - if (ws.readyState === ws.CLOSED) { - callback(err); - process.nextTick(emitClose, duplex); - return; - } - let called = false; - ws.once('error', function error(err) { - called = true; - callback(err); - }); - ws.once('close', function close() { - if (!called) callback(err); - process.nextTick(emitClose, duplex); - }); - if (terminateOnDestroy) ws.terminate(); - }; - duplex._final = function (callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - duplex._final(callback); - }); - return; - } - if (ws._socket === null) return; - if (ws._socket._writableState.finished) { - callback(); - if (duplex._readableState.endEmitted) duplex.destroy(); - } else { - ws._socket.once('finish', function finish() { - callback(); - }); - ws.close(); - } - }; - duplex._read = function () { - if (ws.isPaused) ws.resume(); - }; - duplex._write = function (chunk, encoding, callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - duplex._write(chunk, encoding, callback); - }); - return; - } - ws.send(chunk, callback); - }; - duplex.on('end', duplexOnEnd); - duplex.on('error', duplexOnError); - return duplex; - } - stream = createWebSocketStream; - return stream; -} - -requireStream(); - -requireReceiver(); - -requireSender(); - -var websocketExports = requireWebsocket(); -var WebSocket = /*@__PURE__*/getDefaultExportFromCjs(websocketExports); - -var subprotocol; -var hasRequiredSubprotocol; - -function requireSubprotocol () { - if (hasRequiredSubprotocol) return subprotocol; - hasRequiredSubprotocol = 1; - const { tokenChars } = requireValidation(); - function parse(header) { - const protocols = new Set(); - let start = -1; - let end = -1; - let i = 0; - for (i; i < header.length; i++) { - const code = header.charCodeAt(i); - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if ( - i !== 0 && - (code === 0x20 || code === 0x09) - ) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x2c ) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) end = i; - const protocol = header.slice(start, end); - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - protocols.add(protocol); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - if (start === -1 || end !== -1) { - throw new SyntaxError('Unexpected end of input'); - } - const protocol = header.slice(start, i); - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - protocols.add(protocol); - return protocols; - } - subprotocol = { parse }; - return subprotocol; -} - -var websocketServer; -var hasRequiredWebsocketServer; - -function requireWebsocketServer () { - if (hasRequiredWebsocketServer) return websocketServer; - hasRequiredWebsocketServer = 1; - const EventEmitter = require$$0$3; - const http = require$$2; - const { Duplex } = require$$0$2; - const { createHash } = require$$1; - const extension = requireExtension(); - const PerMessageDeflate = requirePermessageDeflate(); - const subprotocol = requireSubprotocol(); - const WebSocket = requireWebsocket(); - const { CLOSE_TIMEOUT, GUID, kWebSocket } = requireConstants(); - const keyRegex = /^[+/0-9A-Za-z]{22}==$/; - const RUNNING = 0; - const CLOSING = 1; - const CLOSED = 2; - class WebSocketServer extends EventEmitter { - constructor(options, callback) { - super(); - options = { - allowSynchronousEvents: true, - autoPong: true, - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - closeTimeout: CLOSE_TIMEOUT, - verifyClient: null, - noServer: false, - backlog: null, - server: null, - host: null, - path: null, - port: null, - WebSocket, - ...options - }; - if ( - (options.port == null && !options.server && !options.noServer) || - (options.port != null && (options.server || options.noServer)) || - (options.server && options.noServer) - ) { - throw new TypeError( - 'One and only one of the "port", "server", or "noServer" options ' + - 'must be specified' - ); - } - if (options.port != null) { - this._server = http.createServer((req, res) => { - const body = http.STATUS_CODES[426]; - res.writeHead(426, { - 'Content-Length': body.length, - 'Content-Type': 'text/plain' - }); - res.end(body); - }); - this._server.listen( - options.port, - options.host, - options.backlog, - callback - ); - } else if (options.server) { - this._server = options.server; - } - if (this._server) { - const emitConnection = this.emit.bind(this, 'connection'); - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, 'listening'), - error: this.emit.bind(this, 'error'), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - if (options.perMessageDeflate === true) options.perMessageDeflate = {}; - if (options.clientTracking) { - this.clients = new Set(); - this._shouldEmitClose = false; - } - this.options = options; - this._state = RUNNING; - } - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - if (!this._server) return null; - return this._server.address(); - } - close(cb) { - if (this._state === CLOSED) { - if (cb) { - this.once('close', () => { - cb(new Error('The server is not running')); - }); - } - process.nextTick(emitClose, this); - return; - } - if (cb) this.once('close', cb); - if (this._state === CLOSING) return; - this._state = CLOSING; - if (this.options.noServer || this.options.server) { - if (this._server) { - this._removeListeners(); - this._removeListeners = this._server = null; - } - if (this.clients) { - if (!this.clients.size) { - process.nextTick(emitClose, this); - } else { - this._shouldEmitClose = true; - } - } else { - process.nextTick(emitClose, this); - } - } else { - const server = this._server; - this._removeListeners(); - this._removeListeners = this._server = null; - server.close(() => { - emitClose(this); - }); - } - } - shouldHandle(req) { - if (this.options.path) { - const index = req.url.indexOf('?'); - const pathname = index !== -1 ? req.url.slice(0, index) : req.url; - if (pathname !== this.options.path) return false; - } - return true; - } - handleUpgrade(req, socket, head, cb) { - socket.on('error', socketOnError); - const key = req.headers['sec-websocket-key']; - const upgrade = req.headers.upgrade; - const version = +req.headers['sec-websocket-version']; - if (req.method !== 'GET') { - const message = 'Invalid HTTP method'; - abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); - return; - } - if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { - const message = 'Invalid Upgrade header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (key === undefined || !keyRegex.test(key)) { - const message = 'Missing or invalid Sec-WebSocket-Key header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (version !== 13 && version !== 8) { - const message = 'Missing or invalid Sec-WebSocket-Version header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { - 'Sec-WebSocket-Version': '13, 8' - }); - return; - } - if (!this.shouldHandle(req)) { - abortHandshake(socket, 400); - return; - } - const secWebSocketProtocol = req.headers['sec-websocket-protocol']; - let protocols = new Set(); - if (secWebSocketProtocol !== undefined) { - try { - protocols = subprotocol.parse(secWebSocketProtocol); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Protocol header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - const secWebSocketExtensions = req.headers['sec-websocket-extensions']; - const extensions = {}; - if ( - this.options.perMessageDeflate && - secWebSocketExtensions !== undefined - ) { - const perMessageDeflate = new PerMessageDeflate( - this.options.perMessageDeflate, - true, - this.options.maxPayload - ); - try { - const offers = extension.parse(secWebSocketExtensions); - if (offers[PerMessageDeflate.extensionName]) { - perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); - extensions[PerMessageDeflate.extensionName] = perMessageDeflate; - } - } catch (err) { - const message = - 'Invalid or unacceptable Sec-WebSocket-Extensions header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - if (this.options.verifyClient) { - const info = { - origin: - req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message, headers); - } - this.completeUpgrade( - extensions, - key, - protocols, - req, - socket, - head, - cb - ); - }); - return; - } - if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); - } - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - } - completeUpgrade(extensions, key, protocols, req, socket, head, cb) { - if (!socket.readable || !socket.writable) return socket.destroy(); - if (socket[kWebSocket]) { - throw new Error( - 'server.handleUpgrade() was called more than once with the same ' + - 'socket, possibly due to a misconfiguration' - ); - } - if (this._state > RUNNING) return abortHandshake(socket, 503); - const digest = createHash('sha1') - .update(key + GUID) - .digest('base64'); - const headers = [ - 'HTTP/1.1 101 Switching Protocols', - 'Upgrade: websocket', - 'Connection: Upgrade', - `Sec-WebSocket-Accept: ${digest}` - ]; - const ws = new this.options.WebSocket(null, undefined, this.options); - if (protocols.size) { - const protocol = this.options.handleProtocols - ? this.options.handleProtocols(protocols, req) - : protocols.values().next().value; - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; - } - } - if (extensions[PerMessageDeflate.extensionName]) { - const params = extensions[PerMessageDeflate.extensionName].params; - const value = extension.format({ - [PerMessageDeflate.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - this.emit('headers', headers, req); - socket.write(headers.concat('\r\n').join('\r\n')); - socket.removeListener('error', socketOnError); - ws.setSocket(socket, head, { - allowSynchronousEvents: this.options.allowSynchronousEvents, - maxPayload: this.options.maxPayload, - skipUTF8Validation: this.options.skipUTF8Validation - }); - if (this.clients) { - this.clients.add(ws); - ws.on('close', () => { - this.clients.delete(ws); - if (this._shouldEmitClose && !this.clients.size) { - process.nextTick(emitClose, this); - } - }); - } - cb(ws, req); - } - } - websocketServer = WebSocketServer; - function addListeners(server, map) { - for (const event of Object.keys(map)) server.on(event, map[event]); - return function removeListeners() { - for (const event of Object.keys(map)) { - server.removeListener(event, map[event]); - } - }; - } - function emitClose(server) { - server._state = CLOSED; - server.emit('close'); - } - function socketOnError() { - this.destroy(); - } - function abortHandshake(socket, code, message, headers) { - message = message || http.STATUS_CODES[code]; - headers = { - Connection: 'close', - 'Content-Type': 'text/html', - 'Content-Length': Buffer.byteLength(message), - ...headers - }; - socket.once('finish', socket.destroy); - socket.end( - `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + - Object.keys(headers) - .map((h) => `${h}: ${headers[h]}`) - .join('\r\n') + - '\r\n\r\n' + - message - ); - } - function abortHandshakeOrEmitwsClientError( - server, - req, - socket, - code, - message, - headers - ) { - if (server.listenerCount('wsClientError')) { - const err = new Error(message); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); - server.emit('wsClientError', err, socket, req); - } else { - abortHandshake(socket, code, message, headers); - } - } - return websocketServer; -} - -requireWebsocketServer(); - -const align = { - right: alignRight, - center: alignCenter -}; -const top = 0; -const right = 1; -const bottom = 2; -const left = 3; -class UI { - constructor(opts) { - var _a; - this.width = opts.width; - this.wrap = (_a = opts.wrap) !== null && _a !== void 0 ? _a : true; - this.rows = []; - } - span(...args) { - const cols = this.div(...args); - cols.span = true; - } - resetOutput() { - this.rows = []; - } - div(...args) { - if (args.length === 0) { - this.div(''); - } - if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === 'string') { - return this.applyLayoutDSL(args[0]); - } - const cols = args.map(arg => { - if (typeof arg === 'string') { - return this.colFromString(arg); - } - return arg; - }); - this.rows.push(cols); - return cols; - } - shouldApplyLayoutDSL(...args) { - return args.length === 1 && typeof args[0] === 'string' && - /[\t\n]/.test(args[0]); - } - applyLayoutDSL(str) { - const rows = str.split('\n').map(row => row.split('\t')); - let leftColumnWidth = 0; - rows.forEach(columns => { - if (columns.length > 1 && mixin$1.stringWidth(columns[0]) > leftColumnWidth) { - leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin$1.stringWidth(columns[0])); - } - }); - rows.forEach(columns => { - this.div(...columns.map((r, i) => { - return { - text: r.trim(), - padding: this.measurePadding(r), - width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined - }; - })); - }); - return this.rows[this.rows.length - 1]; - } - colFromString(text) { - return { - text, - padding: this.measurePadding(text) - }; - } - measurePadding(str) { - const noAnsi = mixin$1.stripAnsi(str); - return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]; - } - toString() { - const lines = []; - this.rows.forEach(row => { - this.rowToString(row, lines); - }); - return lines - .filter(line => !line.hidden) - .map(line => line.text) - .join('\n'); - } - rowToString(row, lines) { - this.rasterize(row).forEach((rrow, r) => { - let str = ''; - rrow.forEach((col, c) => { - const { width } = row[c]; - const wrapWidth = this.negatePadding(row[c]); - let ts = col; - if (wrapWidth > mixin$1.stringWidth(col)) { - ts += ' '.repeat(wrapWidth - mixin$1.stringWidth(col)); - } - if (row[c].align && row[c].align !== 'left' && this.wrap) { - const fn = align[row[c].align]; - ts = fn(ts, wrapWidth); - if (mixin$1.stringWidth(ts) < wrapWidth) { - ts += ' '.repeat((width || 0) - mixin$1.stringWidth(ts) - 1); - } - } - const padding = row[c].padding || [0, 0, 0, 0]; - if (padding[left]) { - str += ' '.repeat(padding[left]); - } - str += addBorder(row[c], ts, '| '); - str += ts; - str += addBorder(row[c], ts, ' |'); - if (padding[right]) { - str += ' '.repeat(padding[right]); - } - if (r === 0 && lines.length > 0) { - str = this.renderInline(str, lines[lines.length - 1]); - } - }); - lines.push({ - text: str.replace(/ +$/, ''), - span: row.span - }); - }); - return lines; - } - renderInline(source, previousLine) { - const match = source.match(/^ */); - const leadingWhitespace = match ? match[0].length : 0; - const target = previousLine.text; - const targetTextWidth = mixin$1.stringWidth(target.trimRight()); - if (!previousLine.span) { - return source; - } - if (!this.wrap) { - previousLine.hidden = true; - return target + source; - } - if (leadingWhitespace < targetTextWidth) { - return source; - } - previousLine.hidden = true; - return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft(); - } - rasterize(row) { - const rrows = []; - const widths = this.columnWidths(row); - let wrapped; - row.forEach((col, c) => { - col.width = widths[c]; - if (this.wrap) { - wrapped = mixin$1.wrap(col.text, this.negatePadding(col), { hard: true }).split('\n'); - } - else { - wrapped = col.text.split('\n'); - } - if (col.border) { - wrapped.unshift('.' + '-'.repeat(this.negatePadding(col) + 2) + '.'); - wrapped.push("'" + '-'.repeat(this.negatePadding(col) + 2) + "'"); - } - if (col.padding) { - wrapped.unshift(...new Array(col.padding[top] || 0).fill('')); - wrapped.push(...new Array(col.padding[bottom] || 0).fill('')); - } - wrapped.forEach((str, r) => { - if (!rrows[r]) { - rrows.push([]); - } - const rrow = rrows[r]; - for (let i = 0; i < c; i++) { - if (rrow[i] === undefined) { - rrow.push(''); - } - } - rrow.push(str); - }); - }); - return rrows; - } - negatePadding(col) { - let wrapWidth = col.width || 0; - if (col.padding) { - wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0); - } - if (col.border) { - wrapWidth -= 4; - } - return wrapWidth; - } - columnWidths(row) { - if (!this.wrap) { - return row.map(col => { - return col.width || mixin$1.stringWidth(col.text); - }); - } - let unset = row.length; - let remainingWidth = this.width; - const widths = row.map(col => { - if (col.width) { - unset--; - remainingWidth -= col.width; - return col.width; - } - return undefined; - }); - const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0; - return widths.map((w, i) => { - if (w === undefined) { - return Math.max(unsetWidth, _minWidth(row[i])); - } - return w; - }); - } -} -function addBorder(col, ts, style) { - if (col.border) { - if (/[.']-+[.']/.test(ts)) { - return ''; - } - if (ts.trim().length !== 0) { - return style; - } - return ' '; - } - return ''; -} -function _minWidth(col) { - const padding = col.padding || []; - const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0); - if (col.border) { - return minWidth + 4; - } - return minWidth; -} -function getWindowWidth() { - if (typeof process === 'object' && process.stdout && process.stdout.columns) { - return process.stdout.columns; - } - return 80; -} -function alignRight(str, width) { - str = str.trim(); - const strWidth = mixin$1.stringWidth(str); - if (strWidth < width) { - return ' '.repeat(width - strWidth) + str; - } - return str; -} -function alignCenter(str, width) { - str = str.trim(); - const strWidth = mixin$1.stringWidth(str); - if (strWidth >= width) { - return str; - } - return ' '.repeat((width - strWidth) >> 1) + str; -} -let mixin$1; -function cliui(opts, _mixin) { - mixin$1 = _mixin; - return new UI({ - width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(), - wrap: opts === null || opts === void 0 ? void 0 : opts.wrap - }); -} - -function ansiRegex({onlyFirst = false} = {}) { - const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'; - const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`; - const csi = '[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]'; - const pattern = `${osc}|${csi}`; - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -} - -const regex = ansiRegex(); -function stripAnsi(string) { - if (typeof string !== 'string') { - throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); - } - if (!string.includes('\u001B') && !string.includes('\u009B')) { - return string; - } - return string.replace(regex, ''); -} - -const ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109]; -const fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510]; -const wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141]; - -const isInRange = (ranges, codePoint) => { - let low = 0; - let high = Math.floor(ranges.length / 2) - 1; - while (low <= high) { - const mid = Math.floor((low + high) / 2); - const i = mid * 2; - if (codePoint < ranges[i]) { - high = mid - 1; - } else if (codePoint > ranges[i + 1]) { - low = mid + 1; - } else { - return true; - } - } - return false; -}; - -const minimumAmbiguousCodePoint = ambiguousRanges[0]; -const maximumAmbiguousCodePoint = ambiguousRanges.at(-1); -const minimumFullWidthCodePoint = fullwidthRanges[0]; -const maximumFullWidthCodePoint = fullwidthRanges.at(-1); -const minimumWideCodePoint = wideRanges[0]; -const maximumWideCodePoint = wideRanges.at(-1); -const commonCjkCodePoint = 0x4E_00; -const [wideFastPathStart, wideFastPathEnd] = findWideFastPathRange(wideRanges); -function findWideFastPathRange(ranges) { - let fastPathStart = ranges[0]; - let fastPathEnd = ranges[1]; - for (let index = 0; index < ranges.length; index += 2) { - const start = ranges[index]; - const end = ranges[index + 1]; - if ( - commonCjkCodePoint >= start - && commonCjkCodePoint <= end - ) { - return [start, end]; - } - if ((end - start) > (fastPathEnd - fastPathStart)) { - fastPathStart = start; - fastPathEnd = end; - } - } - return [fastPathStart, fastPathEnd]; -} -const isAmbiguous = codePoint => { - if ( - codePoint < minimumAmbiguousCodePoint - || codePoint > maximumAmbiguousCodePoint - ) { - return false; - } - return isInRange(ambiguousRanges, codePoint); -}; -const isFullWidth = codePoint => { - if ( - codePoint < minimumFullWidthCodePoint - || codePoint > maximumFullWidthCodePoint - ) { - return false; - } - return isInRange(fullwidthRanges, codePoint); -}; -const isWide = codePoint => { - if ( - codePoint >= wideFastPathStart - && codePoint <= wideFastPathEnd - ) { - return true; - } - if ( - codePoint < minimumWideCodePoint - || codePoint > maximumWideCodePoint - ) { - return false; - } - return isInRange(wideRanges, codePoint); -}; - -function validate(codePoint) { - if (!Number.isSafeInteger(codePoint)) { - throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`); - } -} -function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) { - validate(codePoint); - if ( - isFullWidth(codePoint) - || isWide(codePoint) - || (ambiguousAsWide && isAmbiguous(codePoint)) - ) { - return 2; - } - return 1; -} - -var emojiRegex = () => { - return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; -}; - -const segmenter = new Intl.Segmenter(); -const defaultIgnorableCodePointRegex = /^\p{Default_Ignorable_Code_Point}$/u; -function stringWidth(string, options = {}) { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - const { - ambiguousIsNarrow = true, - countAnsiEscapeCodes = false, - } = options; - if (!countAnsiEscapeCodes) { - string = stripAnsi(string); - } - if (string.length === 0) { - return 0; - } - let width = 0; - const eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow}; - for (const {segment: character} of segmenter.segment(string)) { - const codePoint = character.codePointAt(0); - if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { - continue; - } - if ( - (codePoint >= 0x20_0B && codePoint <= 0x20_0F) - || codePoint === 0xFE_FF - ) { - continue; - } - if ( - (codePoint >= 0x3_00 && codePoint <= 0x3_6F) - || (codePoint >= 0x1A_B0 && codePoint <= 0x1A_FF) - || (codePoint >= 0x1D_C0 && codePoint <= 0x1D_FF) - || (codePoint >= 0x20_D0 && codePoint <= 0x20_FF) - || (codePoint >= 0xFE_20 && codePoint <= 0xFE_2F) - ) { - continue; - } - if (codePoint >= 0xD8_00 && codePoint <= 0xDF_FF) { - continue; - } - if (codePoint >= 0xFE_00 && codePoint <= 0xFE_0F) { - continue; - } - if (defaultIgnorableCodePointRegex.test(character)) { - continue; - } - if (emojiRegex().test(character)) { - width += 2; - continue; - } - width += eastAsianWidth(codePoint, eastAsianWidthOptions); - } - return width; -} - -const ANSI_BACKGROUND_OFFSET = 10; -const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; -const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; -const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; -const styles = { - modifier: { - reset: [0, 0], - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - blackBright: [90, 39], - gray: [90, 39], - grey: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39], - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgBlackBright: [100, 49], - bgGray: [100, 49], - bgGrey: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49], - }, -}; -Object.keys(styles.modifier); -const foregroundColorNames = Object.keys(styles.color); -const backgroundColorNames = Object.keys(styles.bgColor); -[...foregroundColorNames, ...backgroundColorNames]; -function assembleStyles() { - const codes = new Map(); - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m`, - }; - group[styleName] = styles[styleName]; - codes.set(style[0], style[1]); - } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false, - }); - } - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false, - }); - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - styles.color.ansi = wrapAnsi16(); - styles.color.ansi256 = wrapAnsi256(); - styles.color.ansi16m = wrapAnsi16m(); - styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - Object.defineProperties(styles, { - rgbToAnsi256: { - value(red, green, blue) { - if (red === green && green === blue) { - if (red < 8) { - return 16; - } - if (red > 248) { - return 231; - } - return Math.round(((red - 8) / 247) * 24) + 232; - } - return 16 - + (36 * Math.round(red / 255 * 5)) - + (6 * Math.round(green / 255 * 5)) - + Math.round(blue / 255 * 5); - }, - enumerable: false, - }, - hexToRgb: { - value(hex) { - const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } - let [colorString] = matches; - if (colorString.length === 3) { - colorString = [...colorString].map(character => character + character).join(''); - } - const integer = Number.parseInt(colorString, 16); - return [ - (integer >> 16) & 0xFF, - (integer >> 8) & 0xFF, - integer & 0xFF, - ]; - }, - enumerable: false, - }, - hexToAnsi256: { - value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), - enumerable: false, - }, - ansi256ToAnsi: { - value(code) { - if (code < 8) { - return 30 + code; - } - if (code < 16) { - return 90 + (code - 8); - } - let red; - let green; - let blue; - if (code >= 232) { - red = (((code - 232) * 10) + 8) / 255; - green = red; - blue = red; - } else { - code -= 16; - const remainder = code % 36; - red = Math.floor(code / 36) / 5; - green = Math.floor(remainder / 6) / 5; - blue = (remainder % 6) / 5; - } - const value = Math.max(red, green, blue) * 2; - if (value === 0) { - return 30; - } - let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); - if (value === 2) { - result += 60; - } - return result; - }, - enumerable: false, - }, - rgbToAnsi: { - value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), - enumerable: false, - }, - hexToAnsi: { - value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), - enumerable: false, - }, - }); - return styles; -} -const ansiStyles = assembleStyles(); - -const ESCAPES = new Set([ - '\u001B', - '\u009B', -]); -const END_CODE = 39; -const ANSI_ESCAPE_BELL = '\u0007'; -const ANSI_CSI = '['; -const ANSI_OSC = ']'; -const ANSI_SGR_TERMINATOR = 'm'; -const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; -const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; -const wrapAnsiHyperlink = url => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`; -const wordLengths = string => string.split(' ').map(character => stringWidth(character)); -const wrapWord = (rows, word, columns) => { - const characters = [...word]; - let isInsideEscape = false; - let isInsideLinkEscape = false; - let visible = stringWidth(stripAnsi(rows.at(-1))); - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - if (ESCAPES.has(character)) { - isInsideEscape = true; - const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join(''); - isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK; - } - if (isInsideEscape) { - if (isInsideLinkEscape) { - if (character === ANSI_ESCAPE_BELL) { - isInsideEscape = false; - isInsideLinkEscape = false; - } - } else if (character === ANSI_SGR_TERMINATOR) { - isInsideEscape = false; - } - continue; - } - visible += characterLength; - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - if (!visible && rows.at(-1).length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; -const stringVisibleTrimSpacesRight = string => { - const words = string.split(' '); - let last = words.length; - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - last--; - } - if (last === words.length) { - return string; - } - return words.slice(0, last).join(' ') + words.slice(last).join(''); -}; -const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - let returnValue = ''; - let escapeCode; - let escapeUrl; - const lengths = wordLengths(string); - let rows = ['']; - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows.at(-1).trimStart(); - } - let rowLength = stringWidth(rows.at(-1)); - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - rows.push(''); - rowLength = 0; - } - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - wrapWord(rows, word, columns); - continue; - } - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - rows.push(''); - } - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - rows[rows.length - 1] += word; - } - if (options.trim !== false) { - rows = rows.map(row => stringVisibleTrimSpacesRight(row)); - } - const preString = rows.join('\n'); - const pre = [...preString]; - let preStringIndex = 0; - for (const [index, character] of pre.entries()) { - returnValue += character; - if (ESCAPES.has(character)) { - const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || {groups: {}}; - if (groups.code !== undefined) { - const code = Number.parseFloat(groups.code); - escapeCode = code === END_CODE ? undefined : code; - } else if (groups.uri !== undefined) { - escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; - } - } - const code = ansiStyles.codes.get(Number(escapeCode)); - if (pre[index + 1] === '\n') { - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(''); - } - if (escapeCode && code) { - returnValue += wrapAnsiCode(code); - } - } else if (character === '\n') { - if (escapeCode && code) { - returnValue += wrapAnsiCode(escapeCode); - } - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(escapeUrl); - } - } - preStringIndex += character.length; - } - return returnValue; -}; -function wrapAnsi(string, columns, options) { - return String(string) - .normalize() - .replaceAll('\r\n', '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); -} - -function ui (opts) { - return cliui(opts, { - stringWidth, - stripAnsi, - wrap: wrapAnsi - }) -} - -function escalade (start, callback) { - let dir = resolve$1('.', start); - let tmp, stats = statSync(dir); - if (!stats.isDirectory()) { - dir = dirname(dir); - } - while (true) { - tmp = callback(dir, readdirSync(dir)); - if (tmp) return resolve$1(dir, tmp); - dir = dirname(tmp = dir); - if (tmp === dir) break; - } -} - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -function camelCase(str) { - const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); - if (!isCamelCase) { - str = str.toLowerCase(); - } - if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { - return str; - } - else { - let camelcase = ''; - let nextChrUpper = false; - const leadingHyphens = str.match(/^-+/); - for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { - let chr = str.charAt(i); - if (nextChrUpper) { - nextChrUpper = false; - chr = chr.toUpperCase(); - } - if (i !== 0 && (chr === '-' || chr === '_')) { - nextChrUpper = true; - } - else if (chr !== '-' && chr !== '_') { - camelcase += chr; - } - } - return camelcase; - } -} -function decamelize(str, joinString) { - const lowercase = str.toLowerCase(); - joinString = joinString || '-'; - let notCamelcase = ''; - for (let i = 0; i < str.length; i++) { - const chrLower = lowercase.charAt(i); - const chrString = str.charAt(i); - if (chrLower !== chrString && i > 0) { - notCamelcase += `${joinString}${lowercase.charAt(i)}`; - } - else { - notCamelcase += chrString; - } - } - return notCamelcase; -} -function looksLikeNumber(x) { - if (x === null || x === undefined) - return false; - if (typeof x === 'number') - return true; - if (/^0x[0-9a-f]+$/i.test(x)) - return true; - if (/^0[^.]/.test(x)) - return false; - return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -function tokenizeArgString(argString) { - if (Array.isArray(argString)) { - return argString.map(e => typeof e !== 'string' ? e + '' : e); - } - argString = argString.trim(); - let i = 0; - let prevC = null; - let c = null; - let opening = null; - const args = []; - for (let ii = 0; ii < argString.length; ii++) { - prevC = c; - c = argString.charAt(ii); - if (c === ' ' && !opening) { - if (!(prevC === ' ')) { - i++; - } - continue; - } - if (c === opening) { - opening = null; - } - else if ((c === "'" || c === '"') && !opening) { - opening = c; - } - if (!args[i]) - args[i] = ''; - args[i] += c; - } - return args; -} - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -var DefaultValuesForTypeKey; -(function (DefaultValuesForTypeKey) { - DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; - DefaultValuesForTypeKey["STRING"] = "string"; - DefaultValuesForTypeKey["NUMBER"] = "number"; - DefaultValuesForTypeKey["ARRAY"] = "array"; -})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); - -/** - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -let mixin; -class YargsParser { - constructor(_mixin) { - mixin = _mixin; - } - parse(argsInput, options) { - const opts = Object.assign({ - alias: undefined, - array: undefined, - boolean: undefined, - config: undefined, - configObjects: undefined, - configuration: undefined, - coerce: undefined, - count: undefined, - default: undefined, - envPrefix: undefined, - narg: undefined, - normalize: undefined, - string: undefined, - number: undefined, - __: undefined, - key: undefined - }, options); - const args = tokenizeArgString(argsInput); - const inputIsString = typeof argsInput === 'string'; - const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); - const configuration = Object.assign({ - 'boolean-negation': true, - 'camel-case-expansion': true, - 'combine-arrays': false, - 'dot-notation': true, - 'duplicate-arguments-array': true, - 'flatten-duplicate-arrays': true, - 'greedy-arrays': true, - 'halt-at-non-option': false, - 'nargs-eats-options': false, - 'negation-prefix': 'no-', - 'parse-numbers': true, - 'parse-positional-numbers': true, - 'populate--': false, - 'set-placeholder-key': false, - 'short-option-groups': true, - 'strip-aliased': false, - 'strip-dashed': false, - 'unknown-options-as-args': false - }, opts.configuration); - const defaults = Object.assign(Object.create(null), opts.default); - const configObjects = opts.configObjects || []; - const envPrefix = opts.envPrefix; - const notFlagsOption = configuration['populate--']; - const notFlagsArgv = notFlagsOption ? '--' : '_'; - const newAliases = Object.create(null); - const defaulted = Object.create(null); - const __ = opts.__ || mixin.format; - const flags = { - aliases: Object.create(null), - arrays: Object.create(null), - bools: Object.create(null), - strings: Object.create(null), - numbers: Object.create(null), - counts: Object.create(null), - normalize: Object.create(null), - configs: Object.create(null), - nargs: Object.create(null), - coercions: Object.create(null), - keys: [] - }; - const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; - const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); - [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { - const key = typeof opt === 'object' ? opt.key : opt; - const assignment = Object.keys(opt).map(function (key) { - const arrayFlagKeys = { - boolean: 'bools', - string: 'strings', - number: 'numbers' - }; - return arrayFlagKeys[key]; - }).filter(Boolean).pop(); - if (assignment) { - flags[assignment][key] = true; - } - flags.arrays[key] = true; - flags.keys.push(key); - }); - [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - flags.keys.push(key); - }); - [].concat(opts.string || []).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - flags.keys.push(key); - }); - [].concat(opts.number || []).filter(Boolean).forEach(function (key) { - flags.numbers[key] = true; - flags.keys.push(key); - }); - [].concat(opts.count || []).filter(Boolean).forEach(function (key) { - flags.counts[key] = true; - flags.keys.push(key); - }); - [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { - flags.normalize[key] = true; - flags.keys.push(key); - }); - if (typeof opts.narg === 'object') { - Object.entries(opts.narg).forEach(([key, value]) => { - if (typeof value === 'number') { - flags.nargs[key] = value; - flags.keys.push(key); - } - }); - } - if (typeof opts.coerce === 'object') { - Object.entries(opts.coerce).forEach(([key, value]) => { - if (typeof value === 'function') { - flags.coercions[key] = value; - flags.keys.push(key); - } - }); - } - if (typeof opts.config !== 'undefined') { - if (Array.isArray(opts.config) || typeof opts.config === 'string') { - [].concat(opts.config).filter(Boolean).forEach(function (key) { - flags.configs[key] = true; - }); - } - else if (typeof opts.config === 'object') { - Object.entries(opts.config).forEach(([key, value]) => { - if (typeof value === 'boolean' || typeof value === 'function') { - flags.configs[key] = value; - } - }); - } - } - extendAliases(opts.key, aliases, opts.default, flags.arrays); - Object.keys(defaults).forEach(function (key) { - (flags.aliases[key] || []).forEach(function (alias) { - defaults[alias] = defaults[key]; - }); - }); - let error = null; - checkConfiguration(); - let notFlags = []; - const argv = Object.assign(Object.create(null), { _: [] }); - const argvReturn = {}; - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - const truncatedArg = arg.replace(/^-{3,}/, '---'); - let broken; - let key; - let letters; - let m; - let next; - let value; - if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { - pushPositional(arg); - } - else if (truncatedArg.match(/^---+(=|$)/)) { - pushPositional(arg); - continue; - } - else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { - m = arg.match(/^--?([^=]+)=([\s\S]*)$/); - if (m !== null && Array.isArray(m) && m.length >= 3) { - if (checkAllAliases(m[1], flags.arrays)) { - i = eatArray(i, m[1], args, m[2]); - } - else if (checkAllAliases(m[1], flags.nargs) !== false) { - i = eatNargs(i, m[1], args, m[2]); - } - else { - setArg(m[1], m[2], true); - } - } - } - else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { - m = arg.match(negatedBoolean); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); - } - } - else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { - m = arg.match(/^--?(.+)/); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - if (checkAllAliases(key, flags.arrays)) { - i = eatArray(i, key, args); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - i = eatNargs(i, key, args); - } - else { - next = args[i + 1]; - if (next !== undefined && (!next.match(/^-/) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - } - else if (arg.match(/^-.\..+=/)) { - m = arg.match(/^-([^=]+)=([\s\S]*)$/); - if (m !== null && Array.isArray(m) && m.length >= 3) { - setArg(m[1], m[2]); - } - } - else if (arg.match(/^-.\..+/) && !arg.match(negative)) { - next = args[i + 1]; - m = arg.match(/^-(.\..+)/); - if (m !== null && Array.isArray(m) && m.length >= 2) { - key = m[1]; - if (next !== undefined && !next.match(/^-/) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { - letters = arg.slice(1, -1).split(''); - broken = false; - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2); - if (letters[j + 1] && letters[j + 1] === '=') { - value = arg.slice(j + 3); - key = letters[j]; - if (checkAllAliases(key, flags.arrays)) { - i = eatArray(i, key, args, value); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - i = eatNargs(i, key, args, value); - } - else { - setArg(key, value); - } - broken = true; - break; - } - if (next === '-') { - setArg(letters[j], next); - continue; - } - if (/[A-Za-z]/.test(letters[j]) && - /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && - checkAllAliases(next, flags.bools) === false) { - setArg(letters[j], next); - broken = true; - break; - } - if (letters[j + 1] && letters[j + 1].match(/\W/)) { - setArg(letters[j], next); - broken = true; - break; - } - else { - setArg(letters[j], defaultValue(letters[j])); - } - } - key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (checkAllAliases(key, flags.arrays)) { - i = eatArray(i, key, args); - } - else if (checkAllAliases(key, flags.nargs) !== false) { - i = eatNargs(i, key, args); - } - else { - next = args[i + 1]; - if (next !== undefined && (!/^(-|--)[^-]/.test(next) || - next.match(negative)) && - !checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next); - i++; - } - else { - setArg(key, defaultValue(key)); - } - } - } - } - else if (arg.match(/^-[0-9]$/) && - arg.match(negative) && - checkAllAliases(arg.slice(1), flags.bools)) { - key = arg.slice(1); - setArg(key, defaultValue(key)); - } - else if (arg === '--') { - notFlags = args.slice(i + 1); - break; - } - else if (configuration['halt-at-non-option']) { - notFlags = args.slice(i); - break; - } - else { - pushPositional(arg); - } - } - applyEnvVars(argv, true); - applyEnvVars(argv, false); - setConfig(argv); - setConfigObjects(); - applyDefaultsAndAliases(argv, flags.aliases, defaults, true); - applyCoercions(argv); - if (configuration['set-placeholder-key']) - setPlaceholderKeys(argv); - Object.keys(flags.counts).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) - setArg(key, 0); - }); - if (notFlagsOption && notFlags.length) - argv[notFlagsArgv] = []; - notFlags.forEach(function (key) { - argv[notFlagsArgv].push(key); - }); - if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { - Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { - delete argv[key]; - }); - } - if (configuration['strip-aliased']) { - [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { - if (configuration['camel-case-expansion'] && alias.includes('-')) { - delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; - } - delete argv[alias]; - }); - } - function pushPositional(arg) { - const maybeCoercedNumber = maybeCoerceNumber('_', arg); - if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { - argv._.push(maybeCoercedNumber); - } - } - function eatNargs(i, key, args, argAfterEqualSign) { - let ii; - let toEat = checkAllAliases(key, flags.nargs); - toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; - if (toEat === 0) { - if (!isUndefined(argAfterEqualSign)) { - error = Error(__('Argument unexpected for: %s', key)); - } - setArg(key, defaultValue(key)); - return i; - } - let available = isUndefined(argAfterEqualSign) ? 0 : 1; - if (configuration['nargs-eats-options']) { - if (args.length - (i + 1) + available < toEat) { - error = Error(__('Not enough arguments following: %s', key)); - } - available = toEat; - } - else { - for (ii = i + 1; ii < args.length; ii++) { - if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) - available++; - else - break; - } - if (available < toEat) - error = Error(__('Not enough arguments following: %s', key)); - } - let consumed = Math.min(available, toEat); - if (!isUndefined(argAfterEqualSign) && consumed > 0) { - setArg(key, argAfterEqualSign); - consumed--; - } - for (ii = i + 1; ii < (consumed + i + 1); ii++) { - setArg(key, args[ii]); - } - return (i + consumed); - } - function eatArray(i, key, args, argAfterEqualSign) { - let argsToSet = []; - let next = argAfterEqualSign || args[i + 1]; - const nargsCount = checkAllAliases(key, flags.nargs); - if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { - argsToSet.push(true); - } - else if (isUndefined(next) || - (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { - if (defaults[key] !== undefined) { - const defVal = defaults[key]; - argsToSet = Array.isArray(defVal) ? defVal : [defVal]; - } - } - else { - if (!isUndefined(argAfterEqualSign)) { - argsToSet.push(processValue(key, argAfterEqualSign, true)); - } - for (let ii = i + 1; ii < args.length; ii++) { - if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || - (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) - break; - next = args[ii]; - if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) - break; - i = ii; - argsToSet.push(processValue(key, next, inputIsString)); - } - } - if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || - (isNaN(nargsCount) && argsToSet.length === 0))) { - error = Error(__('Not enough arguments following: %s', key)); - } - setArg(key, argsToSet); - return i; - } - function setArg(key, val, shouldStripQuotes = inputIsString) { - if (/-/.test(key) && configuration['camel-case-expansion']) { - const alias = key.split('.').map(function (prop) { - return camelCase(prop); - }).join('.'); - addNewAlias(key, alias); - } - const value = processValue(key, val, shouldStripQuotes); - const splitKey = key.split('.'); - setKey(argv, splitKey, value); - if (flags.aliases[key]) { - flags.aliases[key].forEach(function (x) { - const keyProperties = x.split('.'); - setKey(argv, keyProperties, value); - }); - } - if (splitKey.length > 1 && configuration['dot-notation']) { - (flags.aliases[splitKey[0]] || []).forEach(function (x) { - let keyProperties = x.split('.'); - const a = [].concat(splitKey); - a.shift(); - keyProperties = keyProperties.concat(a); - if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { - setKey(argv, keyProperties, value); - } - }); - } - if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { - const keys = [key].concat(flags.aliases[key] || []); - keys.forEach(function (key) { - Object.defineProperty(argvReturn, key, { - enumerable: true, - get() { - return val; - }, - set(value) { - val = typeof value === 'string' ? mixin.normalize(value) : value; - } - }); - }); - } - } - function addNewAlias(key, alias) { - if (!(flags.aliases[key] && flags.aliases[key].length)) { - flags.aliases[key] = [alias]; - newAliases[alias] = true; - } - if (!(flags.aliases[alias] && flags.aliases[alias].length)) { - addNewAlias(alias, key); - } - } - function processValue(key, val, shouldStripQuotes) { - if (shouldStripQuotes) { - val = stripQuotes(val); - } - if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { - if (typeof val === 'string') - val = val === 'true'; - } - let value = Array.isArray(val) - ? val.map(function (v) { return maybeCoerceNumber(key, v); }) - : maybeCoerceNumber(key, val); - if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { - value = increment(); - } - if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { - if (Array.isArray(val)) - value = val.map((val) => { return mixin.normalize(val); }); - else - value = mixin.normalize(val); - } - return value; - } - function maybeCoerceNumber(key, value) { - if (!configuration['parse-positional-numbers'] && key === '_') - return value; - if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { - const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); - if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { - value = Number(value); - } - } - return value; - } - function setConfig(argv) { - const configLookup = Object.create(null); - applyDefaultsAndAliases(configLookup, flags.aliases, defaults); - Object.keys(flags.configs).forEach(function (configKey) { - const configPath = argv[configKey] || configLookup[configKey]; - if (configPath) { - try { - let config = null; - const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); - const resolveConfig = flags.configs[configKey]; - if (typeof resolveConfig === 'function') { - try { - config = resolveConfig(resolvedConfigPath); - } - catch (e) { - config = e; - } - if (config instanceof Error) { - error = config; - return; - } - } - else { - config = mixin.require(resolvedConfigPath); - } - setConfigObject(config); - } - catch (ex) { - if (ex.name === 'PermissionDenied') - error = ex; - else if (argv[configKey]) - error = Error(__('Invalid JSON config file: %s', configPath)); - } - } - }); - } - function setConfigObject(config, prev) { - Object.keys(config).forEach(function (key) { - const value = config[key]; - const fullKey = prev ? prev + '.' + key : key; - if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { - setConfigObject(value, fullKey); - } - else { - if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { - setArg(fullKey, value); - } - } - }); - } - function setConfigObjects() { - if (typeof configObjects !== 'undefined') { - configObjects.forEach(function (configObject) { - setConfigObject(configObject); - }); - } - } - function applyEnvVars(argv, configOnly) { - if (typeof envPrefix === 'undefined') - return; - const prefix = typeof envPrefix === 'string' ? envPrefix : ''; - const env = mixin.env(); - Object.keys(env).forEach(function (envVar) { - if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { - const keys = envVar.split('__').map(function (key, i) { - if (i === 0) { - key = key.substring(prefix.length); - } - return camelCase(key); - }); - if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { - setArg(keys.join('.'), env[envVar]); - } - } - }); - } - function applyCoercions(argv) { - let coerce; - const applied = new Set(); - Object.keys(argv).forEach(function (key) { - if (!applied.has(key)) { - coerce = checkAllAliases(key, flags.coercions); - if (typeof coerce === 'function') { - try { - const value = maybeCoerceNumber(key, coerce(argv[key])); - ([].concat(flags.aliases[key] || [], key)).forEach(ali => { - applied.add(ali); - argv[ali] = value; - }); - } - catch (err) { - error = err; - } - } - } - }); - } - function setPlaceholderKeys(argv) { - flags.keys.forEach((key) => { - if (~key.indexOf('.')) - return; - if (typeof argv[key] === 'undefined') - argv[key] = undefined; - }); - return argv; - } - function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { - Object.keys(defaults).forEach(function (key) { - if (!hasKey(obj, key.split('.'))) { - setKey(obj, key.split('.'), defaults[key]); - if (canLog) - defaulted[key] = true; - (aliases[key] || []).forEach(function (x) { - if (hasKey(obj, x.split('.'))) - return; - setKey(obj, x.split('.'), defaults[key]); - }); - } - }); - } - function hasKey(obj, keys) { - let o = obj; - if (!configuration['dot-notation']) - keys = [keys.join('.')]; - keys.slice(0, -1).forEach(function (key) { - o = (o[key] || {}); - }); - const key = keys[keys.length - 1]; - if (typeof o !== 'object') - return false; - else - return key in o; - } - function setKey(obj, keys, value) { - let o = obj; - if (!configuration['dot-notation']) - keys = [keys.join('.')]; - keys.slice(0, -1).forEach(function (key) { - key = sanitizeKey(key); - if (typeof o === 'object' && o[key] === undefined) { - o[key] = {}; - } - if (typeof o[key] !== 'object' || Array.isArray(o[key])) { - if (Array.isArray(o[key])) { - o[key].push({}); - } - else { - o[key] = [o[key], {}]; - } - o = o[key][o[key].length - 1]; - } - else { - o = o[key]; - } - }); - const key = sanitizeKey(keys[keys.length - 1]); - const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); - const isValueArray = Array.isArray(value); - let duplicate = configuration['duplicate-arguments-array']; - if (!duplicate && checkAllAliases(key, flags.nargs)) { - duplicate = true; - if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { - o[key] = undefined; - } - } - if (value === increment()) { - o[key] = increment(o[key]); - } - else if (Array.isArray(o[key])) { - if (duplicate && isTypeArray && isValueArray) { - o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); - } - else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { - o[key] = value; - } - else { - o[key] = o[key].concat([value]); - } - } - else if (o[key] === undefined && isTypeArray) { - o[key] = isValueArray ? value : [value]; - } - else if (duplicate && !(o[key] === undefined || - checkAllAliases(key, flags.counts) || - checkAllAliases(key, flags.bools))) { - o[key] = [o[key], value]; - } - else { - o[key] = value; - } - } - function extendAliases(...args) { - args.forEach(function (obj) { - Object.keys(obj || {}).forEach(function (key) { - if (flags.aliases[key]) - return; - flags.aliases[key] = [].concat(aliases[key] || []); - flags.aliases[key].concat(key).forEach(function (x) { - if (/-/.test(x) && configuration['camel-case-expansion']) { - const c = camelCase(x); - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c); - newAliases[c] = true; - } - } - }); - flags.aliases[key].concat(key).forEach(function (x) { - if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { - const c = decamelize(x, '-'); - if (c !== key && flags.aliases[key].indexOf(c) === -1) { - flags.aliases[key].push(c); - newAliases[c] = true; - } - } - }); - flags.aliases[key].forEach(function (x) { - flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); - }); - } - function checkAllAliases(key, flag) { - const toCheck = [].concat(flags.aliases[key] || [], key); - const keys = Object.keys(flag); - const setAlias = toCheck.find(key => keys.includes(key)); - return setAlias ? flag[setAlias] : false; - } - function hasAnyFlag(key) { - const flagsKeys = Object.keys(flags); - const toCheck = [].concat(flagsKeys.map(k => flags[k])); - return toCheck.some(function (flag) { - return Array.isArray(flag) ? flag.includes(key) : flag[key]; - }); - } - function hasFlagsMatching(arg, ...patterns) { - const toCheck = [].concat(...patterns); - return toCheck.some(function (pattern) { - const match = arg.match(pattern); - return match && hasAnyFlag(match[1]); - }); - } - function hasAllShortFlags(arg) { - if (arg.match(negative) || !arg.match(/^-[^-]+/)) { - return false; - } - let hasAllFlags = true; - let next; - const letters = arg.slice(1).split(''); - for (let j = 0; j < letters.length; j++) { - next = arg.slice(j + 2); - if (!hasAnyFlag(letters[j])) { - hasAllFlags = false; - break; - } - if ((letters[j + 1] && letters[j + 1] === '=') || - next === '-' || - (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || - (letters[j + 1] && letters[j + 1].match(/\W/))) { - break; - } - } - return hasAllFlags; - } - function isUnknownOptionAsArg(arg) { - return configuration['unknown-options-as-args'] && isUnknownOption(arg); - } - function isUnknownOption(arg) { - arg = arg.replace(/^-{3,}/, '--'); - if (arg.match(negative)) { - return false; - } - if (hasAllShortFlags(arg)) { - return false; - } - const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; - const normalFlag = /^-+([^=]+?)$/; - const flagEndingInHyphen = /^-+([^=]+?)-$/; - const flagEndingInDigits = /^-+([^=]+?\d+)$/; - const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; - return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); - } - function defaultValue(key) { - if (!checkAllAliases(key, flags.bools) && - !checkAllAliases(key, flags.counts) && - `${key}` in defaults) { - return defaults[key]; - } - else { - return defaultForType(guessType(key)); - } - } - function defaultForType(type) { - const def = { - [DefaultValuesForTypeKey.BOOLEAN]: true, - [DefaultValuesForTypeKey.STRING]: '', - [DefaultValuesForTypeKey.NUMBER]: undefined, - [DefaultValuesForTypeKey.ARRAY]: [] - }; - return def[type]; - } - function guessType(key) { - let type = DefaultValuesForTypeKey.BOOLEAN; - if (checkAllAliases(key, flags.strings)) - type = DefaultValuesForTypeKey.STRING; - else if (checkAllAliases(key, flags.numbers)) - type = DefaultValuesForTypeKey.NUMBER; - else if (checkAllAliases(key, flags.bools)) - type = DefaultValuesForTypeKey.BOOLEAN; - else if (checkAllAliases(key, flags.arrays)) - type = DefaultValuesForTypeKey.ARRAY; - return type; - } - function isUndefined(num) { - return num === undefined; - } - function checkConfiguration() { - Object.keys(flags.counts).find(key => { - if (checkAllAliases(key, flags.arrays)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); - return true; - } - else if (checkAllAliases(key, flags.nargs)) { - error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); - return true; - } - return false; - }); - } - return { - aliases: Object.assign({}, flags.aliases), - argv: Object.assign(argvReturn, argv), - configuration: configuration, - defaulted: Object.assign({}, defaulted), - error: error, - newAliases: Object.assign({}, newAliases) - }; - } -} -function combineAliases(aliases) { - const aliasArrays = []; - const combined = Object.create(null); - let change = true; - Object.keys(aliases).forEach(function (key) { - aliasArrays.push([].concat(aliases[key], key)); - }); - while (change) { - change = false; - for (let i = 0; i < aliasArrays.length; i++) { - for (let ii = i + 1; ii < aliasArrays.length; ii++) { - const intersect = aliasArrays[i].filter(function (v) { - return aliasArrays[ii].indexOf(v) !== -1; - }); - if (intersect.length) { - aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); - aliasArrays.splice(ii, 1); - change = true; - break; - } - } - } - } - aliasArrays.forEach(function (aliasArray) { - aliasArray = aliasArray.filter(function (v, i, self) { - return self.indexOf(v) === i; - }); - const lastAlias = aliasArray.pop(); - if (lastAlias !== undefined && typeof lastAlias === 'string') { - combined[lastAlias] = aliasArray; - } - }); - return combined; -} -function increment(orig) { - return orig !== undefined ? orig + 1 : 1; -} -function sanitizeKey(key) { - if (key === '__proto__') - return '___proto___'; - return key; -} -function stripQuotes(val) { - return (typeof val === 'string' && - (val[0] === "'" || val[0] === '"') && - val[val.length - 1] === val[0]) - ? val.substring(1, val.length - 1) - : val; -} - -/** - * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js - * - * @license - * Copyright (c) 2016, Contributors - * SPDX-License-Identifier: ISC - */ -var _a, _b, _c; -const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) - ? Number(process.env.YARGS_MIN_NODE_VERSION) - : 20; -const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); -if (nodeVersion) { - const major = Number(nodeVersion.match(/^([^.]+)/)[1]); - if (major < minNodeVersion) { - throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); - } -} -const env = process ? process.env : {}; -const require$2 = createRequire ? createRequire(import.meta.url) : undefined; -const parser = new YargsParser({ - cwd: process.cwd, - env: () => { - return env; - }, - format: format$2, - normalize, - resolve: resolve$1, - require: (path) => { - if (typeof require$2 !== 'undefined') { - return require$2(path); - } - else if (path.match(/\.json$/)) { - return JSON.parse(readFileSync(path, 'utf8')); - } - else { - throw Error('only .json config files are supported in ESM'); - } - } -}); -const yargsParser = function Parser(args, opts) { - const result = parser.parse(args.slice(), opts); - return result.argv; -}; -yargsParser.detailed = function (args, opts) { - return parser.parse(args.slice(), opts); -}; -yargsParser.camelCase = camelCase; -yargsParser.decamelize = decamelize; -yargsParser.looksLikeNumber = looksLikeNumber; - -function getProcessArgvBinIndex() { - if (isBundledElectronApp()) - return 0; - return 1; -} -function isBundledElectronApp() { - return isElectronApp() && !process.defaultApp; -} -function isElectronApp() { - return !!process.versions.electron; -} -function hideBin(argv) { - return argv.slice(getProcessArgvBinIndex() + 1); -} -function getProcessArgvBin() { - return process.argv[getProcessArgvBinIndex()]; -} - -var shim$3 = { - fs: { - readFileSync, - writeFile - }, - format: format$2, - resolve: resolve$1, - exists: (file) => { - try { - return statSync(file).isFile(); - } - catch (err) { - return false; - } - } -}; - -let shim$2; -class Y18N { - constructor(opts) { - opts = opts || {}; - this.directory = opts.directory || './locales'; - this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; - this.locale = opts.locale || 'en'; - this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; - this.cache = Object.create(null); - this.writeQueue = []; - } - __(...args) { - if (typeof arguments[0] !== 'string') { - return this._taggedLiteral(arguments[0], ...arguments); - } - const str = args.shift(); - let cb = function () { }; - if (typeof args[args.length - 1] === 'function') - cb = args.pop(); - cb = cb || function () { }; - if (!this.cache[this.locale]) - this._readLocaleFile(); - if (!this.cache[this.locale][str] && this.updateFiles) { - this.cache[this.locale][str] = str; - this._enqueueWrite({ - directory: this.directory, - locale: this.locale, - cb - }); - } - else { - cb(); - } - return shim$2.format.apply(shim$2.format, [this.cache[this.locale][str] || str].concat(args)); - } - __n() { - const args = Array.prototype.slice.call(arguments); - const singular = args.shift(); - const plural = args.shift(); - const quantity = args.shift(); - let cb = function () { }; - if (typeof args[args.length - 1] === 'function') - cb = args.pop(); - if (!this.cache[this.locale]) - this._readLocaleFile(); - let str = quantity === 1 ? singular : plural; - if (this.cache[this.locale][singular]) { - const entry = this.cache[this.locale][singular]; - str = entry[quantity === 1 ? 'one' : 'other']; - } - if (!this.cache[this.locale][singular] && this.updateFiles) { - this.cache[this.locale][singular] = { - one: singular, - other: plural - }; - this._enqueueWrite({ - directory: this.directory, - locale: this.locale, - cb - }); - } - else { - cb(); - } - const values = [str]; - if (~str.indexOf('%d')) - values.push(quantity); - return shim$2.format.apply(shim$2.format, values.concat(args)); - } - setLocale(locale) { - this.locale = locale; - } - getLocale() { - return this.locale; - } - updateLocale(obj) { - if (!this.cache[this.locale]) - this._readLocaleFile(); - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - this.cache[this.locale][key] = obj[key]; - } - } - } - _taggedLiteral(parts, ...args) { - let str = ''; - parts.forEach(function (part, i) { - const arg = args[i + 1]; - str += part; - if (typeof arg !== 'undefined') { - str += '%s'; - } - }); - return this.__.apply(this, [str].concat([].slice.call(args, 1))); - } - _enqueueWrite(work) { - this.writeQueue.push(work); - if (this.writeQueue.length === 1) - this._processWriteQueue(); - } - _processWriteQueue() { - const _this = this; - const work = this.writeQueue[0]; - const directory = work.directory; - const locale = work.locale; - const cb = work.cb; - const languageFile = this._resolveLocaleFile(directory, locale); - const serializedLocale = JSON.stringify(this.cache[locale], null, 2); - shim$2.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { - _this.writeQueue.shift(); - if (_this.writeQueue.length > 0) - _this._processWriteQueue(); - cb(err); - }); - } - _readLocaleFile() { - let localeLookup = {}; - const languageFile = this._resolveLocaleFile(this.directory, this.locale); - try { - if (shim$2.fs.readFileSync) { - localeLookup = JSON.parse(shim$2.fs.readFileSync(languageFile, 'utf-8')); - } - } - catch (err) { - if (err instanceof SyntaxError) { - err.message = 'syntax error in ' + languageFile; - } - if (err.code === 'ENOENT') - localeLookup = {}; - else - throw err; - } - this.cache[this.locale] = localeLookup; - } - _resolveLocaleFile(directory, locale) { - let file = shim$2.resolve(directory, './', locale + '.json'); - if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { - const languageFile = shim$2.resolve(directory, './', locale.split('_')[0] + '.json'); - if (this._fileExistsSync(languageFile)) - file = languageFile; - } - return file; - } - _fileExistsSync(file) { - return shim$2.exists(file); - } -} -function y18n$1(opts, _shim) { - shim$2 = _shim; - const y18n = new Y18N(opts); - return { - __: y18n.__.bind(y18n), - __n: y18n.__n.bind(y18n), - setLocale: y18n.setLocale.bind(y18n), - getLocale: y18n.getLocale.bind(y18n), - updateLocale: y18n.updateLocale.bind(y18n), - locale: y18n.locale - }; -} - -const y18n = (opts) => { - return y18n$1(opts, shim$3) -}; - -var getCallerFile$1; -var hasRequiredGetCallerFile; - -function requireGetCallerFile () { - if (hasRequiredGetCallerFile) return getCallerFile$1; - hasRequiredGetCallerFile = 1; - getCallerFile$1 = function getCallerFile(position) { - if (position === void 0) { position = 2; } - if (position >= Error.stackTraceLimit) { - throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); - } - var oldPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = function (_, stack) { return stack; }; - var stack = new Error().stack; - Error.prepareStackTrace = oldPrepareStackTrace; - if (stack !== null && typeof stack === 'object') { - return stack[position] ? stack[position].getFileName() : undefined; - } - }; - return getCallerFile$1; -} - -var getCallerFileExports = requireGetCallerFile(); -var getCallerFile = /*@__PURE__*/getDefaultExportFromCjs(getCallerFileExports); - -const __dirname$1 = fileURLToPath(import.meta.url); -const mainFilename = __dirname$1.substring(0, __dirname$1.lastIndexOf('node_modules')); -const require$1 = createRequire(import.meta.url); -var shim$1 = { - assert: { - notStrictEqual, - strictEqual - }, - cliui: ui, - findUp: escalade, - getEnv: (key) => { - return process.env[key] - }, - inspect, - getProcessArgvBin, - mainFilename: mainFilename || process.cwd(), - Parser: yargsParser, - path: { - basename, - dirname, - extname, - relative, - resolve: resolve$1, - join - }, - process: { - argv: () => process.argv, - cwd: process.cwd, - emitWarning: (warning, type) => process.emitWarning(warning, type), - execPath: () => process.execPath, - exit: (code) => { - process.exit(code); - }, - nextTick: process.nextTick, - stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null - }, - readFileSync: readFileSync$1, - readdirSync: readdirSync$1, - require: require$1, - getCallerFile: () => { - const callerFile = getCallerFile(3); - return callerFile.match(/^file:\/\//) ? fileURLToPath(callerFile) : callerFile; - }, - stringWidth, - y18n: y18n({ - directory: resolve$1(__dirname$1, '../../../locales'), - updateFiles: false - }) -}; - -function assertNotStrictEqual(actual, expected, shim, message) { - shim.assert.notStrictEqual(actual, expected, message); -} -function assertSingleKey(actual, shim) { - shim.assert.strictEqual(typeof actual, 'string'); -} -function objectKeys(object) { - return Object.keys(object); -} - -function isPromise(maybePromise) { - return (!!maybePromise && - !!maybePromise.then && - typeof maybePromise.then === 'function'); -} - -class YError extends Error { - constructor(msg) { - super(msg || 'yargs error'); - this.name = 'YError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, YError); - } - } -} - -function parseCommand(cmd) { - const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); - const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); - const bregex = /\.*[\][<>]/g; - const firstCommand = splitCommand.shift(); - if (!firstCommand) - throw new Error(`No command found in: ${cmd}`); - const parsedCommand = { - cmd: firstCommand.replace(bregex, ''), - demanded: [], - optional: [], - }; - splitCommand.forEach((cmd, i) => { - let variadic = false; - cmd = cmd.replace(/\s/g, ''); - if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) - variadic = true; - if (/^\[/.test(cmd)) { - parsedCommand.optional.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic, - }); - } - else { - parsedCommand.demanded.push({ - cmd: cmd.replace(bregex, '').split('|'), - variadic, - }); - } - }); - return parsedCommand; -} - -const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; -function argsert(arg1, arg2, arg3) { - function parseArgs() { - return typeof arg1 === 'object' - ? [{ demanded: [], optional: [] }, arg1, arg2] - : [ - parseCommand(`cmd ${arg1}`), - arg2, - arg3, - ]; - } - try { - let position = 0; - const [parsed, callerArguments, _length] = parseArgs(); - const args = [].slice.call(callerArguments); - while (args.length && args[args.length - 1] === undefined) - args.pop(); - const length = _length || args.length; - if (length < parsed.demanded.length) { - throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); - } - const totalCommands = parsed.demanded.length + parsed.optional.length; - if (length > totalCommands) { - throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); - } - parsed.demanded.forEach(demanded => { - const arg = args.shift(); - const observedType = guessType(arg); - const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); - if (matchingTypes.length === 0) - argumentTypeError(observedType, demanded.cmd, position); - position += 1; - }); - parsed.optional.forEach(optional => { - if (args.length === 0) - return; - const arg = args.shift(); - const observedType = guessType(arg); - const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); - if (matchingTypes.length === 0) - argumentTypeError(observedType, optional.cmd, position); - position += 1; - }); - } - catch (err) { - console.warn(err.stack); - } -} -function guessType(arg) { - if (Array.isArray(arg)) { - return 'array'; - } - else if (arg === null) { - return 'null'; - } - return typeof arg; -} -function argumentTypeError(observedType, allowedTypes, position) { - throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); -} - -class GlobalMiddleware { - constructor(yargs) { - this.globalMiddleware = []; - this.frozens = []; - this.yargs = yargs; - } - addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { - argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); - if (Array.isArray(callback)) { - for (let i = 0; i < callback.length; i++) { - if (typeof callback[i] !== 'function') { - throw Error('middleware must be a function'); - } - const m = callback[i]; - m.applyBeforeValidation = applyBeforeValidation; - m.global = global; - } - Array.prototype.push.apply(this.globalMiddleware, callback); - } - else if (typeof callback === 'function') { - const m = callback; - m.applyBeforeValidation = applyBeforeValidation; - m.global = global; - m.mutates = mutates; - this.globalMiddleware.push(callback); - } - return this.yargs; - } - addCoerceMiddleware(callback, option) { - const aliases = this.yargs.getAliases(); - this.globalMiddleware = this.globalMiddleware.filter(m => { - const toCheck = [...(aliases[option] || []), option]; - if (!m.option) - return true; - else - return !toCheck.includes(m.option); - }); - callback.option = option; - return this.addMiddleware(callback, true, true, true); - } - getMiddleware() { - return this.globalMiddleware; - } - freeze() { - this.frozens.push([...this.globalMiddleware]); - } - unfreeze() { - const frozen = this.frozens.pop(); - if (frozen !== undefined) - this.globalMiddleware = frozen; - } - reset() { - this.globalMiddleware = this.globalMiddleware.filter(m => m.global); - } -} -function commandMiddlewareFactory(commandMiddleware) { - if (!commandMiddleware) - return []; - return commandMiddleware.map(middleware => { - middleware.applyBeforeValidation = false; - return middleware; - }); -} -function applyMiddleware(argv, yargs, middlewares, beforeValidation) { - return middlewares.reduce((acc, middleware) => { - if (middleware.applyBeforeValidation !== beforeValidation) { - return acc; - } - if (middleware.mutates) { - if (middleware.applied) - return acc; - middleware.applied = true; - } - if (isPromise(acc)) { - return acc - .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) - .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); - } - else { - const result = middleware(acc, yargs); - return isPromise(result) - ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) - : Object.assign(acc, result); - } - }, argv); -} - -function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { - throw err; -}) { - try { - const result = isFunction(getResult) ? getResult() : getResult; - return isPromise(result) - ? result.then((result) => resultHandler(result)) - : resultHandler(result); - } - catch (err) { - return errorHandler(err); - } -} -function isFunction(arg) { - return typeof arg === 'function'; -} - -const DEFAULT_MARKER = /(^\*)|(^\$0)/; -class CommandInstance { - constructor(usage, validation, globalMiddleware, shim) { - this.requireCache = new Set(); - this.handlers = {}; - this.aliasMap = {}; - this.frozens = []; - this.shim = shim; - this.usage = usage; - this.globalMiddleware = globalMiddleware; - this.validation = validation; - } - addDirectory(dir, req, callerFile, opts) { - opts = opts || {}; - this.requireCache.add(callerFile); - const fullDirPath = this.shim.path.resolve(this.shim.path.dirname(callerFile), dir); - const files = this.shim.readdirSync(fullDirPath, { - recursive: opts.recurse ? true : false, - }); - if (!Array.isArray(opts.extensions)) - opts.extensions = ['js']; - const visit = typeof opts.visit === 'function' ? opts.visit : (o) => o; - for (const fileb of files) { - const file = fileb.toString(); - if (opts.exclude) { - let exclude = false; - if (typeof opts.exclude === 'function') { - exclude = opts.exclude(file); - } - else { - exclude = opts.exclude.test(file); - } - if (exclude) - continue; - } - if (opts.include) { - let include = false; - if (typeof opts.include === 'function') { - include = opts.include(file); - } - else { - include = opts.include.test(file); - } - if (!include) - continue; - } - let supportedExtension = false; - for (const ext of opts.extensions) { - if (file.endsWith(ext)) - supportedExtension = true; - } - if (supportedExtension) { - const joined = this.shim.path.join(fullDirPath, file); - const module = req(joined); - const extendableModule = Object.create(null, Object.getOwnPropertyDescriptors({ ...module })); - const visited = visit(extendableModule, joined, file); - if (visited) { - if (this.requireCache.has(joined)) - continue; - else - this.requireCache.add(joined); - if (!extendableModule.command) { - extendableModule.command = this.shim.path.basename(joined, this.shim.path.extname(joined)); - } - this.addHandler(extendableModule); - } - } - } - } - addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { - let aliases = []; - const middlewares = commandMiddlewareFactory(commandMiddleware); - handler = handler || (() => { }); - if (Array.isArray(cmd)) { - if (isCommandAndAliases(cmd)) { - [cmd, ...aliases] = cmd; - } - else { - for (const command of cmd) { - this.addHandler(command); - } - } - } - else if (isCommandHandlerDefinition(cmd)) { - let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' - ? cmd.command - : null; - if (command === null) { - throw new Error(`No command name given for module: ${this.shim.inspect(cmd)}`); - } - if (cmd.aliases) - command = [].concat(command).concat(cmd.aliases); - this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); - return; - } - else if (isCommandBuilderDefinition(builder)) { - this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); - return; - } - if (typeof cmd === 'string') { - const parsedCommand = parseCommand(cmd); - aliases = aliases.map(alias => parseCommand(alias).cmd); - let isDefault = false; - const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { - if (DEFAULT_MARKER.test(c)) { - isDefault = true; - return false; - } - return true; - }); - if (parsedAliases.length === 0 && isDefault) - parsedAliases.push('$0'); - if (isDefault) { - parsedCommand.cmd = parsedAliases[0]; - aliases = parsedAliases.slice(1); - cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); - } - aliases.forEach(alias => { - this.aliasMap[alias] = parsedCommand.cmd; - }); - if (description !== false) { - this.usage.command(cmd, description, isDefault, aliases, deprecated); - } - this.handlers[parsedCommand.cmd] = { - original: cmd, - description, - handler, - builder: builder || {}, - middlewares, - deprecated, - demanded: parsedCommand.demanded, - optional: parsedCommand.optional, - }; - if (isDefault) - this.defaultCommand = this.handlers[parsedCommand.cmd]; - } - } - getCommandHandlers() { - return this.handlers; - } - getCommands() { - return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); - } - hasDefaultCommand() { - return !!this.defaultCommand; - } - runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { - const commandHandler = this.handlers[command] || - this.handlers[this.aliasMap[command]] || - this.defaultCommand; - const currentContext = yargs.getInternalMethods().getContext(); - const parentCommands = currentContext.commands.slice(); - const isDefaultCommand = !command; - if (command) { - currentContext.commands.push(command); - currentContext.fullCommands.push(commandHandler.original); - } - const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); - return isPromise(builderResult) - ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) - : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); - } - applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { - const builder = commandHandler.builder; - let innerYargs = yargs; - if (isCommandBuilderCallback(builder)) { - yargs.getInternalMethods().getUsageInstance().freeze(); - const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); - if (isPromise(builderOutput)) { - return builderOutput.then(output => { - innerYargs = isYargsInstance(output) ? output : yargs; - return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); - }); - } - } - else if (isCommandBuilderOptionDefinitions(builder)) { - yargs.getInternalMethods().getUsageInstance().freeze(); - innerYargs = yargs.getInternalMethods().reset(aliases); - Object.keys(commandHandler.builder).forEach(key => { - innerYargs.option(key, builder[key]); - }); - } - return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); - } - parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { - if (isDefaultCommand) - innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); - if (this.shouldUpdateUsage(innerYargs)) { - innerYargs - .getInternalMethods() - .getUsageInstance() - .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); - } - const innerArgv = innerYargs - .getInternalMethods() - .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); - return isPromise(innerArgv) - ? innerArgv.then(argv => ({ - aliases: innerYargs.parsed.aliases, - innerArgv: argv, - })) - : { - aliases: innerYargs.parsed.aliases, - innerArgv: innerArgv, - }; - } - shouldUpdateUsage(yargs) { - return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && - yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); - } - usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { - const c = DEFAULT_MARKER.test(commandHandler.original) - ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() - : commandHandler.original; - const pc = parentCommands.filter(c => { - return !DEFAULT_MARKER.test(c); - }); - pc.push(c); - return `$0 ${pc.join(' ')}`; - } - handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { - if (!yargs.getInternalMethods().getHasOutput()) { - const validation = yargs - .getInternalMethods() - .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); - innerArgv = maybeAsyncResult(innerArgv, result => { - validation(result); - return result; - }); - } - if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { - yargs.getInternalMethods().setHasOutput(); - const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; - yargs - .getInternalMethods() - .postProcess(innerArgv, populateDoubleDash, false, false); - innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); - innerArgv = maybeAsyncResult(innerArgv, result => { - const handlerResult = commandHandler.handler(result); - return isPromise(handlerResult) - ? handlerResult.then(() => result) - : result; - }); - if (!isDefaultCommand) { - yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); - } - if (isPromise(innerArgv) && - !yargs.getInternalMethods().hasParseCallback()) { - innerArgv.catch(error => { - try { - yargs.getInternalMethods().getUsageInstance().fail(null, error); - } - catch (_err) { - } - }); - } - } - if (!isDefaultCommand) { - currentContext.commands.pop(); - currentContext.fullCommands.pop(); - } - return innerArgv; - } - applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { - let positionalMap = {}; - if (helpOnly) - return innerArgv; - if (!yargs.getInternalMethods().getHasOutput()) { - positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); - } - const middlewares = this.globalMiddleware - .getMiddleware() - .slice(0) - .concat(commandHandler.middlewares); - const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); - return isPromise(maybePromiseArgv) - ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) - : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); - } - populatePositionals(commandHandler, argv, context, yargs) { - argv._ = argv._.slice(context.commands.length); - const demanded = commandHandler.demanded.slice(0); - const optional = commandHandler.optional.slice(0); - const positionalMap = {}; - this.validation.positionalCount(demanded.length, argv._.length); - while (demanded.length) { - const demand = demanded.shift(); - this.populatePositional(demand, argv, positionalMap); - } - while (optional.length) { - const maybe = optional.shift(); - this.populatePositional(maybe, argv, positionalMap); - } - argv._ = context.commands.concat(argv._.map(a => '' + a)); - this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); - return positionalMap; - } - populatePositional(positional, argv, positionalMap) { - const cmd = positional.cmd[0]; - if (positional.variadic) { - positionalMap[cmd] = argv._.splice(0).map(String); - } - else { - if (argv._.length) - positionalMap[cmd] = [String(argv._.shift())]; - } - } - cmdToParseOptions(cmdString) { - const parseOptions = { - array: [], - default: {}, - alias: {}, - demand: {}, - }; - const parsed = parseCommand(cmdString); - parsed.demanded.forEach(d => { - const [cmd, ...aliases] = d.cmd; - if (d.variadic) { - parseOptions.array.push(cmd); - parseOptions.default[cmd] = []; - } - parseOptions.alias[cmd] = aliases; - parseOptions.demand[cmd] = true; - }); - parsed.optional.forEach(o => { - const [cmd, ...aliases] = o.cmd; - if (o.variadic) { - parseOptions.array.push(cmd); - parseOptions.default[cmd] = []; - } - parseOptions.alias[cmd] = aliases; - }); - return parseOptions; - } - postProcessPositionals(argv, positionalMap, parseOptions, yargs) { - const options = Object.assign({}, yargs.getOptions()); - options.default = Object.assign(parseOptions.default, options.default); - for (const key of Object.keys(parseOptions.alias)) { - options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); - } - options.array = options.array.concat(parseOptions.array); - options.config = {}; - const unparsed = []; - Object.keys(positionalMap).forEach(key => { - positionalMap[key].map(value => { - if (options.configuration['unknown-options-as-args']) - options.key[key] = true; - unparsed.push(`--${key}`); - unparsed.push(value); - }); - }); - if (!unparsed.length) - return; - const config = Object.assign({}, options.configuration, { - 'populate--': false, - }); - const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { - configuration: config, - })); - if (parsed.error) { - yargs - .getInternalMethods() - .getUsageInstance() - .fail(parsed.error.message, parsed.error); - } - else { - const positionalKeys = Object.keys(positionalMap); - Object.keys(positionalMap).forEach(key => { - positionalKeys.push(...parsed.aliases[key]); - }); - Object.keys(parsed.argv).forEach(key => { - if (positionalKeys.includes(key)) { - if (!positionalMap[key]) - positionalMap[key] = parsed.argv[key]; - if (!this.isInConfigs(yargs, key) && - !this.isDefaulted(yargs, key) && - Object.prototype.hasOwnProperty.call(argv, key) && - Object.prototype.hasOwnProperty.call(parsed.argv, key) && - (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { - argv[key] = [].concat(argv[key], parsed.argv[key]); - } - else { - argv[key] = parsed.argv[key]; - } - } - }); - } - } - isDefaulted(yargs, key) { - const { default: defaults } = yargs.getOptions(); - return (Object.prototype.hasOwnProperty.call(defaults, key) || - Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); - } - isInConfigs(yargs, key) { - const { configObjects } = yargs.getOptions(); - return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || - configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); - } - runDefaultBuilderOn(yargs) { - if (!this.defaultCommand) - return; - if (this.shouldUpdateUsage(yargs)) { - const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) - ? this.defaultCommand.original - : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); - yargs - .getInternalMethods() - .getUsageInstance() - .usage(commandString, this.defaultCommand.description); - } - const builder = this.defaultCommand.builder; - if (isCommandBuilderCallback(builder)) { - return builder(yargs, true); - } - else if (!isCommandBuilderDefinition(builder)) { - Object.keys(builder).forEach(key => { - yargs.option(key, builder[key]); - }); - } - return undefined; - } - extractDesc({ describe, description, desc }) { - for (const test of [describe, description, desc]) { - if (typeof test === 'string' || test === false) - return test; - assertNotStrictEqual(test, true, this.shim); - } - return false; - } - freeze() { - this.frozens.push({ - handlers: this.handlers, - aliasMap: this.aliasMap, - defaultCommand: this.defaultCommand, - }); - } - unfreeze() { - const frozen = this.frozens.pop(); - assertNotStrictEqual(frozen, undefined, this.shim); - ({ - handlers: this.handlers, - aliasMap: this.aliasMap, - defaultCommand: this.defaultCommand, - } = frozen); - } - reset() { - this.handlers = {}; - this.aliasMap = {}; - this.defaultCommand = undefined; - this.requireCache = new Set(); - return this; - } -} -function command(usage, validation, globalMiddleware, shim) { - return new CommandInstance(usage, validation, globalMiddleware, shim); -} -function isCommandBuilderDefinition(builder) { - return (typeof builder === 'object' && - !!builder.builder && - typeof builder.handler === 'function'); -} -function isCommandAndAliases(cmd) { - return cmd.every(c => typeof c === 'string'); -} -function isCommandBuilderCallback(builder) { - return typeof builder === 'function'; -} -function isCommandBuilderOptionDefinitions(builder) { - return typeof builder === 'object'; -} -function isCommandHandlerDefinition(cmd) { - return typeof cmd === 'object' && !Array.isArray(cmd); -} - -function objFilter(original = {}, filter = () => true) { - const obj = {}; - objectKeys(original).forEach(key => { - if (filter(key, original[key])) { - obj[key] = original[key]; - } - }); - return obj; -} - -function setBlocking(blocking) { - if (typeof process === 'undefined') - return; - [process.stdout, process.stderr].forEach(_stream => { - const stream = _stream; - if (stream._handle && - stream.isTTY && - typeof stream._handle.setBlocking === 'function') { - stream._handle.setBlocking(blocking); - } - }); -} - -function isBoolean(fail) { - return typeof fail === 'boolean'; -} -function usage(yargs, shim) { - const __ = shim.y18n.__; - const self = {}; - const fails = []; - self.failFn = function failFn(f) { - fails.push(f); - }; - let failMessage = null; - let globalFailMessage = null; - let showHelpOnFail = true; - self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { - const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; - if (yargs.getInternalMethods().isGlobalContext()) { - globalFailMessage = message; - } - failMessage = message; - showHelpOnFail = enabled; - return self; - }; - let failureOutput = false; - self.fail = function fail(msg, err) { - const logger = yargs.getInternalMethods().getLoggerInstance(); - if (fails.length) { - for (let i = fails.length - 1; i >= 0; --i) { - const fail = fails[i]; - if (isBoolean(fail)) { - if (err) - throw err; - else if (msg) - throw Error(msg); - } - else { - fail(msg, err, self); - } - } - } - else { - if (yargs.getExitProcess()) - setBlocking(true); - if (!failureOutput) { - failureOutput = true; - if (showHelpOnFail) { - yargs.showHelp('error'); - logger.error(); - } - if (msg || err) - logger.error(msg || err); - const globalOrCommandFailMessage = failMessage || globalFailMessage; - if (globalOrCommandFailMessage) { - if (msg || err) - logger.error(''); - logger.error(globalOrCommandFailMessage); - } - } - err = err || new YError(msg); - if (yargs.getExitProcess()) { - return yargs.exit(1); - } - else if (yargs.getInternalMethods().hasParseCallback()) { - return yargs.exit(1, err); - } - else { - throw err; - } - } - }; - let usages = []; - let usageDisabled = false; - self.usage = (msg, description) => { - if (msg === null) { - usageDisabled = true; - usages = []; - return self; - } - usageDisabled = false; - usages.push([msg, description || '']); - return self; - }; - self.getUsage = () => { - return usages; - }; - self.getUsageDisabled = () => { - return usageDisabled; - }; - self.getPositionalGroupName = () => { - return __('Positionals:'); - }; - let examples = []; - self.example = (cmd, description) => { - examples.push([cmd, description || '']); - }; - let commands = []; - self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { - if (isDefault) { - commands = commands.map(cmdArray => { - cmdArray[2] = false; - return cmdArray; - }); - } - commands.push([cmd, description || '', isDefault, aliases, deprecated]); - }; - self.getCommands = () => commands; - let descriptions = {}; - self.describe = function describe(keyOrKeys, desc) { - if (Array.isArray(keyOrKeys)) { - keyOrKeys.forEach(k => { - self.describe(k, desc); - }); - } - else if (typeof keyOrKeys === 'object') { - Object.keys(keyOrKeys).forEach(k => { - self.describe(k, keyOrKeys[k]); - }); - } - else { - descriptions[keyOrKeys] = desc; - } - }; - self.getDescriptions = () => descriptions; - let epilogs = []; - self.epilog = msg => { - epilogs.push(msg); - }; - let wrapSet = false; - let wrap; - self.wrap = cols => { - wrapSet = true; - wrap = cols; - }; - self.getWrap = () => { - if (shim.getEnv('YARGS_DISABLE_WRAP')) { - return null; - } - if (!wrapSet) { - wrap = windowWidth(); - wrapSet = true; - } - return wrap; - }; - const deferY18nLookupPrefix = '__yargsString__:'; - self.deferY18nLookup = str => deferY18nLookupPrefix + str; - self.help = function help() { - if (cachedHelpMessage) - return cachedHelpMessage; - normalizeAliases(); - const base$0 = yargs.customScriptName - ? yargs.$0 - : shim.path.basename(yargs.$0); - const demandedOptions = yargs.getDemandedOptions(); - const demandedCommands = yargs.getDemandedCommands(); - const deprecatedOptions = yargs.getDeprecatedOptions(); - const groups = yargs.getGroups(); - const options = yargs.getOptions(); - let keys = []; - keys = keys.concat(Object.keys(descriptions)); - keys = keys.concat(Object.keys(demandedOptions)); - keys = keys.concat(Object.keys(demandedCommands)); - keys = keys.concat(Object.keys(options.default)); - keys = keys.filter(filterHiddenOptions); - keys = Object.keys(keys.reduce((acc, key) => { - if (key !== '_') - acc[key] = true; - return acc; - }, {})); - const theWrap = self.getWrap(); - const ui = shim.cliui({ - width: theWrap, - wrap: !!theWrap, - }); - if (!usageDisabled) { - if (usages.length) { - usages.forEach(usage => { - ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); - if (usage[1]) { - ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); - } - }); - ui.div(); - } - else if (commands.length) { - let u = null; - if (demandedCommands._) { - u = `${base$0} <${__('command')}>\n`; - } - else { - u = `${base$0} [${__('command')}]\n`; - } - ui.div(`${u}`); - } - } - if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { - ui.div(__('Commands:')); - const context = yargs.getInternalMethods().getContext(); - const parentCommands = context.commands.length - ? `${context.commands.join(' ')} ` - : ''; - if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === - true) { - commands = commands.sort((a, b) => a[0].localeCompare(b[0])); - } - const prefix = base$0 ? `${base$0} ` : ''; - commands.forEach(command => { - const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; - ui.span({ - text: commandString, - padding: [0, 2, 0, 2], - width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, - }, { text: command[1] }); - const hints = []; - if (command[2]) - hints.push(`[${__('default')}]`); - if (command[3] && command[3].length) { - hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); - } - if (command[4]) { - if (typeof command[4] === 'string') { - hints.push(`[${__('deprecated: %s', command[4])}]`); - } - else { - hints.push(`[${__('deprecated')}]`); - } - } - if (hints.length) { - ui.div({ - text: hints.join(' '), - padding: [0, 0, 0, 2], - align: 'right', - }); - } - else { - ui.div(); - } - }); - ui.div(); - } - const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); - keys = keys.filter(key => !yargs.parsed.newAliases[key] && - aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); - const defaultGroup = __('Options:'); - if (!groups[defaultGroup]) - groups[defaultGroup] = []; - addUngroupedKeys(keys, options.alias, groups, defaultGroup); - const isLongSwitch = (sw) => /^--/.test(getText(sw)); - const displayedGroups = Object.keys(groups) - .filter(groupName => groups[groupName].length > 0) - .map(groupName => { - const normalizedKeys = groups[groupName] - .filter(filterHiddenOptions) - .map(key => { - if (aliasKeys.includes(key)) - return key; - for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { - if ((options.alias[aliasKey] || []).includes(key)) - return aliasKey; - } - return key; - }); - return { groupName, normalizedKeys }; - }) - .filter(({ normalizedKeys }) => normalizedKeys.length > 0) - .map(({ groupName, normalizedKeys }) => { - const switches = normalizedKeys.reduce((acc, key) => { - acc[key] = [key] - .concat(options.alias[key] || []) - .map(sw => { - if (groupName === self.getPositionalGroupName()) - return sw; - else { - return ((/^[0-9]$/.test(sw) - ? options.boolean.includes(key) - ? '-' - : '--' - : sw.length > 1 - ? '--' - : '-') + sw); - } - }) - .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) - ? 0 - : isLongSwitch(sw1) - ? 1 - : -1) - .join(', '); - return acc; - }, {}); - return { groupName, normalizedKeys, switches }; - }); - const shortSwitchesUsed = displayedGroups - .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) - .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); - if (shortSwitchesUsed) { - displayedGroups - .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) - .forEach(({ normalizedKeys, switches }) => { - normalizedKeys.forEach(key => { - if (isLongSwitch(switches[key])) { - switches[key] = addIndentation(switches[key], '-x, '.length); - } - }); - }); - } - displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { - ui.div(groupName); - normalizedKeys.forEach(key => { - const kswitch = switches[key]; - let desc = descriptions[key] || ''; - let type = null; - if (desc.includes(deferY18nLookupPrefix)) - desc = __(desc.substring(deferY18nLookupPrefix.length)); - if (options.boolean.includes(key)) - type = `[${__('boolean')}]`; - if (options.count.includes(key)) - type = `[${__('count')}]`; - if (options.string.includes(key)) - type = `[${__('string')}]`; - if (options.normalize.includes(key)) - type = `[${__('string')}]`; - if (options.array.includes(key)) - type = `[${__('array')}]`; - if (options.number.includes(key)) - type = `[${__('number')}]`; - const deprecatedExtra = (deprecated) => typeof deprecated === 'string' - ? `[${__('deprecated: %s', deprecated)}]` - : `[${__('deprecated')}]`; - const extra = [ - key in deprecatedOptions - ? deprecatedExtra(deprecatedOptions[key]) - : null, - type, - key in demandedOptions ? `[${__('required')}]` : null, - options.choices && options.choices[key] - ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` - : null, - defaultString(options.default[key], options.defaultDescription[key]), - ] - .filter(Boolean) - .join(' '); - ui.span({ - text: getText(kswitch), - padding: [0, 2, 0, 2 + getIndentation(kswitch)], - width: maxWidth(switches, theWrap) + 4, - }, desc); - const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === - true; - if (extra && !shouldHideOptionExtras) - ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); - else - ui.div(); - }); - ui.div(); - }); - if (examples.length) { - ui.div(__('Examples:')); - examples.forEach(example => { - example[0] = example[0].replace(/\$0/g, base$0); - }); - examples.forEach(example => { - if (example[1] === '') { - ui.div({ - text: example[0], - padding: [0, 2, 0, 2], - }); - } - else { - ui.div({ - text: example[0], - padding: [0, 2, 0, 2], - width: maxWidth(examples, theWrap) + 4, - }, { - text: example[1], - }); - } - }); - ui.div(); - } - if (epilogs.length > 0) { - const e = epilogs - .map(epilog => epilog.replace(/\$0/g, base$0)) - .join('\n'); - ui.div(`${e}\n`); - } - return ui.toString().replace(/\s*$/, ''); - }; - function maxWidth(table, theWrap, modifier) { - let width = 0; - if (!Array.isArray(table)) { - table = Object.values(table).map(v => [v]); - } - table.forEach(v => { - width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); - }); - if (theWrap) - width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); - return width; - } - function normalizeAliases() { - const demandedOptions = yargs.getDemandedOptions(); - const options = yargs.getOptions(); - (Object.keys(options.alias) || []).forEach(key => { - options.alias[key].forEach(alias => { - if (descriptions[alias]) - self.describe(key, descriptions[alias]); - if (alias in demandedOptions) - yargs.demandOption(key, demandedOptions[alias]); - if (options.boolean.includes(alias)) - yargs.boolean(key); - if (options.count.includes(alias)) - yargs.count(key); - if (options.string.includes(alias)) - yargs.string(key); - if (options.normalize.includes(alias)) - yargs.normalize(key); - if (options.array.includes(alias)) - yargs.array(key); - if (options.number.includes(alias)) - yargs.number(key); - }); - }); - } - let cachedHelpMessage; - self.cacheHelpMessage = function () { - cachedHelpMessage = this.help(); - }; - self.clearCachedHelpMessage = function () { - cachedHelpMessage = undefined; - }; - self.hasCachedHelpMessage = function () { - return !!cachedHelpMessage; - }; - function addUngroupedKeys(keys, aliases, groups, defaultGroup) { - let groupedKeys = []; - let toCheck = null; - Object.keys(groups).forEach(group => { - groupedKeys = groupedKeys.concat(groups[group]); - }); - keys.forEach(key => { - toCheck = [key].concat(aliases[key]); - if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { - groups[defaultGroup].push(key); - } - }); - return groupedKeys; - } - function filterHiddenOptions(key) { - return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || - yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); - } - self.showHelp = (level) => { - const logger = yargs.getInternalMethods().getLoggerInstance(); - if (!level) - level = 'error'; - const emit = typeof level === 'function' ? level : logger[level]; - emit(self.help()); - }; - self.functionDescription = fn => { - const description = fn.name - ? shim.Parser.decamelize(fn.name, '-') - : __('generated-value'); - return ['(', description, ')'].join(''); - }; - self.stringifiedValues = function stringifiedValues(values, separator) { - let string = ''; - const sep = separator || ', '; - const array = [].concat(values); - if (!values || !array.length) - return string; - array.forEach(value => { - if (string.length) - string += sep; - string += JSON.stringify(value); - }); - return string; - }; - function defaultString(value, defaultDescription) { - let string = `[${__('default:')} `; - if (value === undefined && !defaultDescription) - return null; - if (defaultDescription) { - string += defaultDescription; - } - else { - switch (typeof value) { - case 'string': - string += `"${value}"`; - break; - case 'object': - string += JSON.stringify(value); - break; - default: - string += value; - } - } - return `${string}]`; - } - function windowWidth() { - const maxWidth = 80; - if (shim.process.stdColumns) { - return Math.min(maxWidth, shim.process.stdColumns); - } - else { - return maxWidth; - } - } - let version = null; - self.version = ver => { - version = ver; - }; - self.showVersion = level => { - const logger = yargs.getInternalMethods().getLoggerInstance(); - if (!level) - level = 'error'; - const emit = typeof level === 'function' ? level : logger[level]; - emit(version); - }; - self.reset = function reset(localLookup) { - failMessage = null; - failureOutput = false; - usages = []; - usageDisabled = false; - epilogs = []; - examples = []; - commands = []; - descriptions = objFilter(descriptions, k => !localLookup[k]); - return self; - }; - const frozens = []; - self.freeze = function freeze() { - frozens.push({ - failMessage, - failureOutput, - usages, - usageDisabled, - epilogs, - examples, - commands, - descriptions, - }); - }; - self.unfreeze = function unfreeze(defaultCommand = false) { - const frozen = frozens.pop(); - if (!frozen) - return; - if (defaultCommand) { - descriptions = { ...frozen.descriptions, ...descriptions }; - commands = [...frozen.commands, ...commands]; - usages = [...frozen.usages, ...usages]; - examples = [...frozen.examples, ...examples]; - epilogs = [...frozen.epilogs, ...epilogs]; - } - else { - ({ - failMessage, - failureOutput, - usages, - usageDisabled, - epilogs, - examples, - commands, - descriptions, - } = frozen); - } - }; - return self; -} -function isIndentedText(text) { - return typeof text === 'object'; -} -function addIndentation(text, indent) { - return isIndentedText(text) - ? { text: text.text, indentation: text.indentation + indent } - : { text, indentation: indent }; -} -function getIndentation(text) { - return isIndentedText(text) ? text.indentation : 0; -} -function getText(text) { - return isIndentedText(text) ? text.text : text; -} - -const completionShTemplate = `###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc -# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. -# -_{{app_name}}_yargs_completions() -{ - local cur_word args type_list - - cur_word="\${COMP_WORDS[COMP_CWORD]}" - args=("\${COMP_WORDS[@]}") - - # ask yargs to generate completions. - # see https://stackoverflow.com/a/40944195/7080036 for the spaces-handling awk - mapfile -t type_list < <({{app_path}} --get-yargs-completions "\${args[@]}") - mapfile -t COMPREPLY < <(compgen -W "$( printf '%q ' "\${type_list[@]}" )" -- "\${cur_word}" | - awk '/ / { print "\\""$0"\\"" } /^[^ ]+$/ { print $0 }') - - # if no match was found, fall back to filename completion - if [ \${#COMPREPLY[@]} -eq 0 ]; then - COMPREPLY=() - fi - - return 0 -} -complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} -###-end-{{app_name}}-completions-### -`; -const completionZshTemplate = `#compdef {{app_name}} -###-begin-{{app_name}}-completions-### -# -# yargs command completion script -# -# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc -# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. -# -_{{app_name}}_yargs_completions() -{ - local reply - local si=$IFS - IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) - IFS=$si - if [[ \${#reply} -gt 0 ]]; then - _describe 'values' reply - else - _default - fi -} -if [[ "'\${zsh_eval_context[-1]}" == "loadautofunc" ]]; then - _{{app_name}}_yargs_completions "$@" -else - compdef _{{app_name}}_yargs_completions {{app_name}} -fi -###-end-{{app_name}}-completions-### -`; - -class Completion { - constructor(yargs, usage, command, shim) { - var _a, _b, _c; - this.yargs = yargs; - this.usage = usage; - this.command = command; - this.shim = shim; - this.completionKey = 'get-yargs-completions'; - this.aliases = null; - this.customCompletionFunction = null; - this.indexAfterLastReset = 0; - this.zshShell = - (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || - ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; - } - defaultCompletion(args, argv, current, done) { - const handlers = this.command.getCommandHandlers(); - for (let i = 0, ii = args.length; i < ii; ++i) { - if (handlers[args[i]] && handlers[args[i]].builder) { - const builder = handlers[args[i]].builder; - if (isCommandBuilderCallback(builder)) { - this.indexAfterLastReset = i + 1; - const y = this.yargs.getInternalMethods().reset(); - builder(y, true); - return y.argv; - } - } - } - const completions = []; - this.commandCompletions(completions, args, current); - this.optionCompletions(completions, args, argv, current); - this.choicesFromOptionsCompletions(completions, args, argv, current); - this.choicesFromPositionalsCompletions(completions, args, argv, current); - done(null, completions); - } - commandCompletions(completions, args, current) { - const parentCommands = this.yargs - .getInternalMethods() - .getContext().commands; - if (!current.match(/^-/) && - parentCommands[parentCommands.length - 1] !== current && - !this.previousArgHasChoices(args)) { - this.usage.getCommands().forEach(usageCommand => { - const commandName = parseCommand(usageCommand[0]).cmd; - if (args.indexOf(commandName) === -1) { - if (!this.zshShell) { - completions.push(commandName); - } - else { - const desc = usageCommand[1] || ''; - completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); - } - } - }); - } - } - optionCompletions(completions, args, argv, current) { - if ((current.match(/^-/) || (current === '' && completions.length === 0)) && - !this.previousArgHasChoices(args)) { - const options = this.yargs.getOptions(); - const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; - Object.keys(options.key).forEach(key => { - const negable = !!options.configuration['boolean-negation'] && - options.boolean.includes(key); - const isPositionalKey = positionalKeys.includes(key); - if (!isPositionalKey && - !options.hiddenOptions.includes(key) && - !this.argsContainKey(args, key, negable)) { - this.completeOptionKey(key, completions, current, negable && !!options.default[key]); - } - }); - } - } - choicesFromOptionsCompletions(completions, args, argv, current) { - if (this.previousArgHasChoices(args)) { - const choices = this.getPreviousArgChoices(args); - if (choices && choices.length > 0) { - completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); - } - } - } - choicesFromPositionalsCompletions(completions, args, argv, current) { - if (current === '' && - completions.length > 0 && - this.previousArgHasChoices(args)) { - return; - } - const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; - const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + - 1); - const positionalKey = positionalKeys[argv._.length - offset - 1]; - if (!positionalKey) { - return; - } - const choices = this.yargs.getOptions().choices[positionalKey] || []; - for (const choice of choices) { - if (choice.startsWith(current)) { - completions.push(choice.replace(/:/g, '\\:')); - } - } - } - getPreviousArgChoices(args) { - if (args.length < 1) - return; - let previousArg = args[args.length - 1]; - let filter = ''; - if (!previousArg.startsWith('-') && args.length > 1) { - filter = previousArg; - previousArg = args[args.length - 2]; - } - if (!previousArg.startsWith('-')) - return; - const previousArgKey = previousArg.replace(/^-+/, ''); - const options = this.yargs.getOptions(); - const possibleAliases = [ - previousArgKey, - ...(this.yargs.getAliases()[previousArgKey] || []), - ]; - let choices; - for (const possibleAlias of possibleAliases) { - if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && - Array.isArray(options.choices[possibleAlias])) { - choices = options.choices[possibleAlias]; - break; - } - } - if (choices) { - return choices.filter(choice => !filter || choice.startsWith(filter)); - } - } - previousArgHasChoices(args) { - const choices = this.getPreviousArgChoices(args); - return choices !== undefined && choices.length > 0; - } - argsContainKey(args, key, negable) { - const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; - if (argsContains(key)) - return true; - if (negable && argsContains(`no-${key}`)) - return true; - if (this.aliases) { - for (const alias of this.aliases[key]) { - if (argsContains(alias)) - return true; - } - } - return false; - } - completeOptionKey(key, completions, current, negable) { - var _a, _b, _c, _d; - let keyWithDesc = key; - if (this.zshShell) { - const descs = this.usage.getDescriptions(); - const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { - const desc = descs[alias]; - return typeof desc === 'string' && desc.length > 0; - }); - const descFromAlias = aliasKey ? descs[aliasKey] : undefined; - const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; - keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc - .replace('__yargsString__:', '') - .replace(/(\r\n|\n|\r)/gm, ' ')}`; - } - const startsByTwoDashes = (s) => /^--/.test(s); - const isShortOption = (s) => /^[^0-9]$/.test(s); - const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; - completions.push(dashes + keyWithDesc); - if (negable) { - completions.push(dashes + 'no-' + keyWithDesc); - } - } - customCompletion(args, argv, current, done) { - assertNotStrictEqual(this.customCompletionFunction, null, this.shim); - if (isSyncCompletionFunction(this.customCompletionFunction)) { - const result = this.customCompletionFunction(current, argv); - if (isPromise(result)) { - return result - .then(list => { - this.shim.process.nextTick(() => { - done(null, list); - }); - }) - .catch(err => { - this.shim.process.nextTick(() => { - done(err, undefined); - }); - }); - } - return done(null, result); - } - else if (isFallbackCompletionFunction(this.customCompletionFunction)) { - return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { - done(null, completions); - }); - } - else { - return this.customCompletionFunction(current, argv, completions => { - done(null, completions); - }); - } - } - getCompletion(args, done) { - const current = args.length ? args[args.length - 1] : ''; - const argv = this.yargs.parse(args, true); - const completionFunction = this.customCompletionFunction - ? (argv) => this.customCompletion(args, argv, current, done) - : (argv) => this.defaultCompletion(args, argv, current, done); - return isPromise(argv) - ? argv.then(completionFunction) - : completionFunction(argv); - } - generateCompletionScript($0, cmd) { - let script = this.zshShell - ? completionZshTemplate - : completionShTemplate; - const name = this.shim.path.basename($0); - if ($0.match(/\.js$/)) - $0 = `./${$0}`; - script = script.replace(/{{app_name}}/g, name); - script = script.replace(/{{completion_command}}/g, cmd); - return script.replace(/{{app_path}}/g, $0); - } - registerFunction(fn) { - this.customCompletionFunction = fn; - } - setParsed(parsed) { - this.aliases = parsed.aliases; - } -} -function completion(yargs, usage, command, shim) { - return new Completion(yargs, usage, command, shim); -} -function isSyncCompletionFunction(completionFunction) { - return completionFunction.length < 3; -} -function isFallbackCompletionFunction(completionFunction) { - return completionFunction.length > 3; -} - -function levenshtein(a, b) { - if (a.length === 0) - return b.length; - if (b.length === 0) - return a.length; - const matrix = []; - let i; - for (i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } - let j; - for (j = 0; j <= a.length; j++) { - matrix[0][j] = j; - } - for (i = 1; i <= b.length; i++) { - for (j = 1; j <= a.length; j++) { - if (b.charAt(i - 1) === a.charAt(j - 1)) { - matrix[i][j] = matrix[i - 1][j - 1]; - } - else { - if (i > 1 && - j > 1 && - b.charAt(i - 2) === a.charAt(j - 1) && - b.charAt(i - 1) === a.charAt(j - 2)) { - matrix[i][j] = matrix[i - 2][j - 2] + 1; - } - else { - matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); - } - } - } - } - return matrix[b.length][a.length]; -} - -const specialKeys = ['$0', '--', '_']; -function validation(yargs, usage, shim) { - const __ = shim.y18n.__; - const __n = shim.y18n.__n; - const self = {}; - self.nonOptionCount = function nonOptionCount(argv) { - const demandedCommands = yargs.getDemandedCommands(); - const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); - const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; - if (demandedCommands._ && - (_s < demandedCommands._.min || _s > demandedCommands._.max)) { - if (_s < demandedCommands._.min) { - if (demandedCommands._.minMsg !== undefined) { - usage.fail(demandedCommands._.minMsg - ? demandedCommands._.minMsg - .replace(/\$0/g, _s.toString()) - .replace(/\$1/, demandedCommands._.min.toString()) - : null); - } - else { - usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); - } - } - else if (_s > demandedCommands._.max) { - if (demandedCommands._.maxMsg !== undefined) { - usage.fail(demandedCommands._.maxMsg - ? demandedCommands._.maxMsg - .replace(/\$0/g, _s.toString()) - .replace(/\$1/, demandedCommands._.max.toString()) - : null); - } - else { - usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); - } - } - } - }; - self.positionalCount = function positionalCount(required, observed) { - if (observed < required) { - usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); - } - }; - self.requiredArguments = function requiredArguments(argv, demandedOptions) { - let missing = null; - for (const key of Object.keys(demandedOptions)) { - if (!Object.prototype.hasOwnProperty.call(argv, key) || - typeof argv[key] === 'undefined') { - missing = missing || {}; - missing[key] = demandedOptions[key]; - } - } - if (missing) { - const customMsgs = []; - for (const key of Object.keys(missing)) { - const msg = missing[key]; - if (msg && customMsgs.indexOf(msg) < 0) { - customMsgs.push(msg); - } - } - const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; - usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); - } - }; - self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { - var _a; - const commandKeys = yargs - .getInternalMethods() - .getCommandInstance() - .getCommands(); - const unknown = []; - const currentContext = yargs.getInternalMethods().getContext(); - Object.keys(argv).forEach(key => { - if (!specialKeys.includes(key) && - !Object.prototype.hasOwnProperty.call(positionalMap, key) && - !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && - !self.isValidAndSomeAliasIsNotNew(key, aliases)) { - unknown.push(key); - } - }); - if (checkPositionals && - (currentContext.commands.length > 0 || - commandKeys.length > 0 || - isDefaultCommand)) { - argv._.slice(currentContext.commands.length).forEach(key => { - if (!commandKeys.includes('' + key)) { - unknown.push('' + key); - } - }); - } - if (checkPositionals) { - const demandedCommands = yargs.getDemandedCommands(); - const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; - const expected = currentContext.commands.length + maxNonOptDemanded; - if (expected < argv._.length) { - argv._.slice(expected).forEach(key => { - key = String(key); - if (!currentContext.commands.includes(key) && - !unknown.includes(key)) { - unknown.push(key); - } - }); - } - } - if (unknown.length) { - usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); - } - }; - self.unknownCommands = function unknownCommands(argv) { - const commandKeys = yargs - .getInternalMethods() - .getCommandInstance() - .getCommands(); - const unknown = []; - const currentContext = yargs.getInternalMethods().getContext(); - if (currentContext.commands.length > 0 || commandKeys.length > 0) { - argv._.slice(currentContext.commands.length).forEach(key => { - if (!commandKeys.includes('' + key)) { - unknown.push('' + key); - } - }); - } - if (unknown.length > 0) { - usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); - return true; - } - else { - return false; - } - }; - self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { - if (!Object.prototype.hasOwnProperty.call(aliases, key)) { - return false; - } - const newAliases = yargs.parsed.newAliases; - return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); - }; - self.limitedChoices = function limitedChoices(argv) { - const options = yargs.getOptions(); - const invalid = {}; - if (!Object.keys(options.choices).length) - return; - Object.keys(argv).forEach(key => { - if (specialKeys.indexOf(key) === -1 && - Object.prototype.hasOwnProperty.call(options.choices, key)) { - [].concat(argv[key]).forEach(value => { - if (options.choices[key].indexOf(value) === -1 && - value !== undefined) { - invalid[key] = (invalid[key] || []).concat(value); - } - }); - } - }); - const invalidKeys = Object.keys(invalid); - if (!invalidKeys.length) - return; - let msg = __('Invalid values:'); - invalidKeys.forEach(key => { - msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; - }); - usage.fail(msg); - }; - let implied = {}; - self.implies = function implies(key, value) { - argsert(' [array|number|string]', [key, value], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach(k => { - self.implies(k, key[k]); - }); - } - else { - yargs.global(key); - if (!implied[key]) { - implied[key] = []; - } - if (Array.isArray(value)) { - value.forEach(i => self.implies(key, i)); - } - else { - assertNotStrictEqual(value, undefined, shim); - implied[key].push(value); - } - } - }; - self.getImplied = function getImplied() { - return implied; - }; - function keyExists(argv, val) { - const num = Number(val); - val = isNaN(num) ? val : num; - if (typeof val === 'number') { - val = argv._.length >= val; - } - else if (val.match(/^--no-.+/)) { - val = val.match(/^--no-(.+)/)[1]; - val = !Object.prototype.hasOwnProperty.call(argv, val); - } - else { - val = Object.prototype.hasOwnProperty.call(argv, val); - } - return val; - } - self.implications = function implications(argv) { - const implyFail = []; - Object.keys(implied).forEach(key => { - const origKey = key; - (implied[key] || []).forEach(value => { - let key = origKey; - const origValue = value; - key = keyExists(argv, key); - value = keyExists(argv, value); - if (key && !value) { - implyFail.push(` ${origKey} -> ${origValue}`); - } - }); - }); - if (implyFail.length) { - let msg = `${__('Implications failed:')}\n`; - implyFail.forEach(value => { - msg += value; - }); - usage.fail(msg); - } - }; - let conflicting = {}; - self.conflicts = function conflicts(key, value) { - argsert(' [array|string]', [key, value], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach(k => { - self.conflicts(k, key[k]); - }); - } - else { - yargs.global(key); - if (!conflicting[key]) { - conflicting[key] = []; - } - if (Array.isArray(value)) { - value.forEach(i => self.conflicts(key, i)); - } - else { - conflicting[key].push(value); - } - } - }; - self.getConflicting = () => conflicting; - self.conflicting = function conflictingFn(argv) { - Object.keys(argv).forEach(key => { - if (conflicting[key]) { - conflicting[key].forEach(value => { - if (value && argv[key] !== undefined && argv[value] !== undefined) { - usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); - } - }); - } - }); - if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { - Object.keys(conflicting).forEach(key => { - conflicting[key].forEach(value => { - if (value && - argv[shim.Parser.camelCase(key)] !== undefined && - argv[shim.Parser.camelCase(value)] !== undefined) { - usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); - } - }); - }); - } - }; - self.recommendCommands = function recommendCommands(cmd, potentialCommands) { - const threshold = 3; - potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); - let recommended = null; - let bestDistance = Infinity; - for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { - const d = levenshtein(cmd, candidate); - if (d <= threshold && d < bestDistance) { - bestDistance = d; - recommended = candidate; - } - } - if (recommended) - usage.fail(__('Did you mean %s?', recommended)); - }; - self.reset = function reset(localLookup) { - implied = objFilter(implied, k => !localLookup[k]); - conflicting = objFilter(conflicting, k => !localLookup[k]); - return self; - }; - const frozens = []; - self.freeze = function freeze() { - frozens.push({ - implied, - conflicting, - }); - }; - self.unfreeze = function unfreeze() { - const frozen = frozens.pop(); - assertNotStrictEqual(frozen, undefined, shim); - ({ implied, conflicting } = frozen); - }; - return self; -} - -let previouslyVisitedConfigs = []; -let shim; -function applyExtends(config, cwd, mergeExtends, _shim) { - shim = _shim; - let defaultConfig = {}; - if (Object.prototype.hasOwnProperty.call(config, 'extends')) { - if (typeof config.extends !== 'string') - return defaultConfig; - const isPath = /\.json|\..*rc$/.test(config.extends); - let pathToDefault = null; - if (!isPath) { - try { - pathToDefault = import.meta.resolve(config.extends); - } - catch (_err) { - return config; - } - } - else { - pathToDefault = getPathToDefaultConfig(cwd, config.extends); - } - checkForCircularExtends(pathToDefault); - previouslyVisitedConfigs.push(pathToDefault); - defaultConfig = isPath - ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) - : _shim.require(config.extends); - delete config.extends; - defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); - } - previouslyVisitedConfigs = []; - return mergeExtends - ? mergeDeep(defaultConfig, config) - : Object.assign({}, defaultConfig, config); -} -function checkForCircularExtends(cfgPath) { - if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { - throw new YError(`Circular extended configurations: '${cfgPath}'.`); - } -} -function getPathToDefaultConfig(cwd, pathToExtend) { - return shim.path.resolve(cwd, pathToExtend); -} -function mergeDeep(config1, config2) { - const target = {}; - function isObject(obj) { - return obj && typeof obj === 'object' && !Array.isArray(obj); - } - Object.assign(target, config1); - for (const key of Object.keys(config2)) { - if (isObject(config2[key]) && isObject(target[key])) { - target[key] = mergeDeep(config1[key], config2[key]); - } - else { - target[key] = config2[key]; - } - } - return target; -} - -var __classPrivateFieldSet = (globalThis && globalThis.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __classPrivateFieldGet = (globalThis && globalThis.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; -function YargsFactory(_shim) { - return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { - const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); - Object.defineProperty(yargs, 'argv', { - get: () => { - return yargs.parse(); - }, - enumerable: true, - }); - yargs.help(); - yargs.version(); - return yargs; - }; -} -const kCopyDoubleDash = Symbol('copyDoubleDash'); -const kCreateLogger = Symbol('copyDoubleDash'); -const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); -const kEmitWarning = Symbol('emitWarning'); -const kFreeze = Symbol('freeze'); -const kGetDollarZero = Symbol('getDollarZero'); -const kGetParserConfiguration = Symbol('getParserConfiguration'); -const kGetUsageConfiguration = Symbol('getUsageConfiguration'); -const kGuessLocale = Symbol('guessLocale'); -const kGuessVersion = Symbol('guessVersion'); -const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); -const kPkgUp = Symbol('pkgUp'); -const kPopulateParserHintArray = Symbol('populateParserHintArray'); -const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); -const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); -const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); -const kSanitizeKey = Symbol('sanitizeKey'); -const kSetKey = Symbol('setKey'); -const kUnfreeze = Symbol('unfreeze'); -const kValidateAsync = Symbol('validateAsync'); -const kGetCommandInstance = Symbol('getCommandInstance'); -const kGetContext = Symbol('getContext'); -const kGetHasOutput = Symbol('getHasOutput'); -const kGetLoggerInstance = Symbol('getLoggerInstance'); -const kGetParseContext = Symbol('getParseContext'); -const kGetUsageInstance = Symbol('getUsageInstance'); -const kGetValidationInstance = Symbol('getValidationInstance'); -const kHasParseCallback = Symbol('hasParseCallback'); -const kIsGlobalContext = Symbol('isGlobalContext'); -const kPostProcess = Symbol('postProcess'); -const kRebase = Symbol('rebase'); -const kReset = Symbol('reset'); -const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); -const kRunValidation = Symbol('runValidation'); -const kSetHasOutput = Symbol('setHasOutput'); -const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); -const DEFAULT_LOCALE = 'en_US'; -class YargsInstance { - constructor(processArgs = [], cwd, parentRequire, shim) { - this.customScriptName = false; - this.parsed = false; - _YargsInstance_command.set(this, void 0); - _YargsInstance_cwd.set(this, void 0); - _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); - _YargsInstance_completion.set(this, null); - _YargsInstance_completionCommand.set(this, null); - _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); - _YargsInstance_exitError.set(this, null); - _YargsInstance_detectLocale.set(this, true); - _YargsInstance_emittedWarnings.set(this, {}); - _YargsInstance_exitProcess.set(this, true); - _YargsInstance_frozens.set(this, []); - _YargsInstance_globalMiddleware.set(this, void 0); - _YargsInstance_groups.set(this, {}); - _YargsInstance_hasOutput.set(this, false); - _YargsInstance_helpOpt.set(this, null); - _YargsInstance_isGlobalContext.set(this, true); - _YargsInstance_logger.set(this, void 0); - _YargsInstance_output.set(this, ''); - _YargsInstance_options.set(this, void 0); - _YargsInstance_parentRequire.set(this, void 0); - _YargsInstance_parserConfig.set(this, {}); - _YargsInstance_parseFn.set(this, null); - _YargsInstance_parseContext.set(this, null); - _YargsInstance_pkgs.set(this, {}); - _YargsInstance_preservedGroups.set(this, {}); - _YargsInstance_processArgs.set(this, void 0); - _YargsInstance_recommendCommands.set(this, false); - _YargsInstance_shim.set(this, void 0); - _YargsInstance_strict.set(this, false); - _YargsInstance_strictCommands.set(this, false); - _YargsInstance_strictOptions.set(this, false); - _YargsInstance_usage.set(this, void 0); - _YargsInstance_usageConfig.set(this, {}); - _YargsInstance_versionOpt.set(this, null); - _YargsInstance_validation.set(this, void 0); - __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); - __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); - __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); - __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); - __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); - this.$0 = this[kGetDollarZero](); - this[kReset](); - __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); - __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); - __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); - __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); - __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); - __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); - __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(DEFAULT_LOCALE); - } - addHelpOpt(opt, msg) { - const defaultHelpOpt = 'help'; - argsert('[string|boolean] [string]', [opt, msg], arguments.length); - if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { - this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); - __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); - } - if (opt === false && msg === undefined) - return this; - __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); - this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); - this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); - return this; - } - help(opt, msg) { - return this.addHelpOpt(opt, msg); - } - addShowHiddenOpt(opt, msg) { - argsert('[string|boolean] [string]', [opt, msg], arguments.length); - if (opt === false && msg === undefined) - return this; - const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); - this.boolean(showHiddenOpt); - this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); - __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; - return this; - } - showHidden(opt, msg) { - return this.addShowHiddenOpt(opt, msg); - } - alias(key, value) { - argsert(' [string|array]', [key, value], arguments.length); - this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); - return this; - } - array(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('array', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - boolean(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('boolean', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - check(f, global) { - argsert(' [boolean]', [f, global], arguments.length); - this.middleware((argv, _yargs) => { - return maybeAsyncResult(() => { - return f(argv, _yargs.getOptions()); - }, (result) => { - if (!result) { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); - } - else if (typeof result === 'string' || result instanceof Error) { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); - } - return argv; - }, (err) => { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); - return argv; - }); - }, false, global); - return this; - } - choices(key, value) { - argsert(' [string|array]', [key, value], arguments.length); - this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); - return this; - } - coerce(keys, value) { - argsert(' [function]', [keys, value], arguments.length); - if (Array.isArray(keys)) { - if (!value) { - throw new YError('coerce callback must be provided'); - } - for (const key of keys) { - this.coerce(key, value); - } - return this; - } - else if (typeof keys === 'object') { - for (const key of Object.keys(keys)) { - this.coerce(key, keys[key]); - } - return this; - } - if (!value) { - throw new YError('coerce callback must be provided'); - } - const coerceKey = keys; - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[coerceKey] = true; - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { - var _a; - const coerceKeyAliases = (_a = yargs.getAliases()[coerceKey]) !== null && _a !== void 0 ? _a : []; - const argvKeys = [coerceKey, ...coerceKeyAliases].filter(key => Object.prototype.hasOwnProperty.call(argv, key)); - if (argvKeys.length === 0) { - return argv; - } - return maybeAsyncResult(() => { - return value(argv[argvKeys[0]]); - }, (result) => { - argvKeys.forEach(key => { - argv[key] = result; - }); - return argv; - }, (err) => { - throw new YError(err.message); - }); - }, coerceKey); - return this; - } - conflicts(key1, key2) { - argsert(' [string|array]', [key1, key2], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); - return this; - } - config(key = 'config', msg, parseFn) { - argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); - if (typeof key === 'object' && !Array.isArray(key)) { - key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); - return this; - } - if (typeof msg === 'function') { - parseFn = msg; - msg = undefined; - } - this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); - (Array.isArray(key) ? key : [key]).forEach(k => { - __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; - }); - return this; - } - completion(cmd, desc, fn) { - argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); - if (typeof desc === 'function') { - fn = desc; - desc = undefined; - } - __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); - if (!desc && desc !== false) { - desc = 'generate completion script'; - } - this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); - if (fn) - __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); - return this; - } - command(cmd, description, builder, handler, middlewares, deprecated) { - argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); - return this; - } - commands(cmd, description, builder, handler, middlewares, deprecated) { - return this.command(cmd, description, builder, handler, middlewares, deprecated); - } - commandDir(dir, opts) { - argsert(' [object]', [dir, opts], arguments.length); - const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; - __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); - return this; - } - count(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('count', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - default(key, value, defaultDescription) { - argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); - if (defaultDescription) { - assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; - } - if (typeof value === 'function') { - assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) - __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = - __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); - value = value.call(); - } - this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); - return this; - } - defaults(key, value, defaultDescription) { - return this.default(key, value, defaultDescription); - } - demandCommand(min = 1, max, minMsg, maxMsg) { - argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); - if (typeof max !== 'number') { - minMsg = max; - max = Infinity; - } - this.global('_', false); - __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { - min, - max, - minMsg, - maxMsg, - }; - return this; - } - demand(keys, max, msg) { - if (Array.isArray(max)) { - max.forEach(key => { - assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - this.demandOption(key, msg); - }); - max = Infinity; - } - else if (typeof max !== 'number') { - msg = max; - max = Infinity; - } - if (typeof keys === 'number') { - assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - this.demandCommand(keys, max, msg, msg); - } - else if (Array.isArray(keys)) { - keys.forEach(key => { - assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - this.demandOption(key, msg); - }); - } - else { - if (typeof msg === 'string') { - this.demandOption(keys, msg); - } - else if (msg === true || typeof msg === 'undefined') { - this.demandOption(keys); - } - } - return this; - } - demandOption(keys, msg) { - argsert(' [string]', [keys, msg], arguments.length); - this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); - return this; - } - deprecateOption(option, message) { - argsert(' [string|boolean]', [option, message], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; - return this; - } - describe(keys, description) { - argsert(' [string]', [keys, description], arguments.length); - this[kSetKey](keys, true); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); - return this; - } - detectLocale(detect) { - argsert('', [detect], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); - return this; - } - env(prefix) { - argsert('[string|boolean]', [prefix], arguments.length); - if (prefix === false) - delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; - else - __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; - return this; - } - epilogue(msg) { - argsert('', [msg], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); - return this; - } - epilog(msg) { - return this.epilogue(msg); - } - example(cmd, description) { - argsert(' [string]', [cmd, description], arguments.length); - if (Array.isArray(cmd)) { - cmd.forEach(exampleParams => this.example(...exampleParams)); - } - else { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); - } - return this; - } - exit(code, err) { - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); - } - exitProcess(enabled = true) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); - return this; - } - fail(f) { - argsert('', [f], arguments.length); - if (typeof f === 'boolean' && f !== false) { - throw new YError("Invalid first argument. Expected function or boolean 'false'"); - } - __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); - return this; - } - getAliases() { - return this.parsed ? this.parsed.aliases : {}; - } - async getCompletion(args, done) { - argsert(' [function]', [args, done], arguments.length); - if (!done) { - return new Promise((resolve, reject) => { - __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { - if (err) - reject(err); - else - resolve(completions); - }); - }); - } - else { - return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); - } - } - getDemandedOptions() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; - } - getDemandedCommands() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; - } - getDeprecatedOptions() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; - } - getDetectLocale() { - return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); - } - getExitProcess() { - return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); - } - getGroups() { - return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); - } - getHelp() { - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { - if (!this.parsed) { - const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); - if (isPromise(parse)) { - return parse.then(() => { - return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); - }); - } - } - const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); - if (isPromise(builderResponse)) { - return builderResponse.then(() => { - return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); - }); - } - } - return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); - } - getOptions() { - return __classPrivateFieldGet(this, _YargsInstance_options, "f"); - } - getStrict() { - return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); - } - getStrictCommands() { - return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); - } - getStrictOptions() { - return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); - } - global(globals, global) { - argsert(' [boolean]', [globals, global], arguments.length); - globals = [].concat(globals); - if (global !== false) { - __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); - } - else { - globals.forEach(g => { - if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) - __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); - }); - } - return this; - } - group(opts, groupName) { - argsert(' ', [opts, groupName], arguments.length); - const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; - if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { - delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; - } - const seen = {}; - __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { - if (seen[key]) - return false; - return (seen[key] = true); - }); - return this; - } - hide(key) { - argsert('', [key], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); - return this; - } - implies(key, value) { - argsert(' [number|string|array]', [key, value], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); - return this; - } - locale(locale) { - argsert('[string]', [locale], arguments.length); - if (locale === undefined) { - this[kGuessLocale](); - return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); - } - __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); - __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); - return this; - } - middleware(callback, applyBeforeValidation, global) { - return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); - } - nargs(key, value) { - argsert(' [number]', [key, value], arguments.length); - this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); - return this; - } - normalize(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('normalize', keys); - return this; - } - number(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('number', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - option(key, opt) { - argsert(' [object]', [key, opt], arguments.length); - if (typeof key === 'object') { - Object.keys(key).forEach(k => { - this.options(k, key[k]); - }); - } - else { - if (typeof opt !== 'object') { - opt = {}; - } - this[kTrackManuallySetKeys](key); - if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { - this[kEmitWarning]([ - '"version" is a reserved word.', - 'Please do one of the following:', - '- Disable version with `yargs.version(false)` if using "version" as an option', - '- Use the built-in `yargs.version` method instead (if applicable)', - '- Use a different option key', - 'https://yargs.js.org/docs/#api-reference-version', - ].join('\n'), undefined, 'versionWarning'); - } - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; - if (opt.alias) - this.alias(key, opt.alias); - const deprecate = opt.deprecate || opt.deprecated; - if (deprecate) { - this.deprecateOption(key, deprecate); - } - const demand = opt.demand || opt.required || opt.require; - if (demand) { - this.demand(key, demand); - } - if (opt.demandOption) { - this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); - } - if (opt.conflicts) { - this.conflicts(key, opt.conflicts); - } - if ('default' in opt) { - this.default(key, opt.default); - } - if (opt.implies !== undefined) { - this.implies(key, opt.implies); - } - if (opt.nargs !== undefined) { - this.nargs(key, opt.nargs); - } - if (opt.config) { - this.config(key, opt.configParser); - } - if (opt.normalize) { - this.normalize(key); - } - if (opt.choices) { - this.choices(key, opt.choices); - } - if (opt.coerce) { - this.coerce(key, opt.coerce); - } - if (opt.group) { - this.group(key, opt.group); - } - if (opt.boolean || opt.type === 'boolean') { - this.boolean(key); - if (opt.alias) - this.boolean(opt.alias); - } - if (opt.array || opt.type === 'array') { - this.array(key); - if (opt.alias) - this.array(opt.alias); - } - if (opt.number || opt.type === 'number') { - this.number(key); - if (opt.alias) - this.number(opt.alias); - } - if (opt.string || opt.type === 'string') { - this.string(key); - if (opt.alias) - this.string(opt.alias); - } - if (opt.count || opt.type === 'count') { - this.count(key); - } - if (typeof opt.global === 'boolean') { - this.global(key, opt.global); - } - if (opt.defaultDescription) { - __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; - } - if (opt.skipValidation) { - this.skipValidation(key); - } - const desc = opt.describe || opt.description || opt.desc; - const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); - if (!Object.prototype.hasOwnProperty.call(descriptions, key) || - typeof desc === 'string') { - this.describe(key, desc); - } - if (opt.hidden) { - this.hide(key); - } - if (opt.requiresArg) { - this.requiresArg(key); - } - } - return this; - } - options(key, opt) { - return this.option(key, opt); - } - parse(args, shortCircuit, _parseFn) { - argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); - this[kFreeze](); - if (typeof args === 'undefined') { - args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); - } - if (typeof shortCircuit === 'object') { - __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); - shortCircuit = _parseFn; - } - if (typeof shortCircuit === 'function') { - __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); - shortCircuit = false; - } - if (!shortCircuit) - __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) - __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); - const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); - const tmpParsed = this.parsed; - __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); - if (isPromise(parsed)) { - return parsed - .then(argv => { - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) - __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); - return argv; - }) - .catch(err => { - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { - __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); - } - throw err; - }) - .finally(() => { - this[kUnfreeze](); - this.parsed = tmpParsed; - }); - } - else { - if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) - __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); - this[kUnfreeze](); - this.parsed = tmpParsed; - } - return parsed; - } - parseAsync(args, shortCircuit, _parseFn) { - const maybePromise = this.parse(args, shortCircuit, _parseFn); - return !isPromise(maybePromise) - ? Promise.resolve(maybePromise) - : maybePromise; - } - parseSync(args, shortCircuit, _parseFn) { - const maybePromise = this.parse(args, shortCircuit, _parseFn); - if (isPromise(maybePromise)) { - throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); - } - return maybePromise; - } - parserConfiguration(config) { - argsert('', [config], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); - return this; - } - pkgConf(key, rootPath) { - argsert(' [string]', [key, rootPath], arguments.length); - let conf = null; - const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); - if (obj[key] && typeof obj[key] === 'object') { - conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); - } - return this; - } - positional(key, opts) { - argsert(' ', [key, opts], arguments.length); - const supportedOpts = [ - 'default', - 'defaultDescription', - 'implies', - 'normalize', - 'choices', - 'conflicts', - 'coerce', - 'type', - 'describe', - 'desc', - 'description', - 'alias', - ]; - opts = objFilter(opts, (k, v) => { - if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) - return false; - return supportedOpts.includes(k); - }); - const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; - const parseOptions = fullCommand - ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) - : { - array: [], - alias: {}, - default: {}, - demand: {}, - }; - objectKeys(parseOptions).forEach(pk => { - const parseOption = parseOptions[pk]; - if (Array.isArray(parseOption)) { - if (parseOption.indexOf(key) !== -1) - opts[pk] = true; - } - else { - if (parseOption[key] && !(pk in opts)) - opts[pk] = parseOption[key]; - } - }); - this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); - return this.option(key, opts); - } - recommendCommands(recommend = true) { - argsert('[boolean]', [recommend], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); - return this; - } - required(keys, max, msg) { - return this.demand(keys, max, msg); - } - require(keys, max, msg) { - return this.demand(keys, max, msg); - } - requiresArg(keys) { - argsert(' [number]', [keys], arguments.length); - if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { - return this; - } - else { - this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); - } - return this; - } - showCompletionScript($0, cmd) { - argsert('[string] [string]', [$0, cmd], arguments.length); - $0 = $0 || this.$0; - __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); - return this; - } - showHelp(level) { - argsert('[string|function]', [level], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { - if (!this.parsed) { - const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); - if (isPromise(parse)) { - parse.then(() => { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); - }); - return this; - } - } - const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); - if (isPromise(builderResponse)) { - builderResponse.then(() => { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); - }); - return this; - } - } - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); - return this; - } - scriptName(scriptName) { - this.customScriptName = true; - this.$0 = scriptName; - return this; - } - showHelpOnFail(enabled, message) { - argsert('[boolean|string] [string]', [enabled, message], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); - return this; - } - showVersion(level) { - argsert('[string|function]', [level], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); - return this; - } - skipValidation(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('skipValidation', keys); - return this; - } - strict(enabled) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); - return this; - } - strictCommands(enabled) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); - return this; - } - strictOptions(enabled) { - argsert('[boolean]', [enabled], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); - return this; - } - string(keys) { - argsert('', [keys], arguments.length); - this[kPopulateParserHintArray]('string', keys); - this[kTrackManuallySetKeys](keys); - return this; - } - terminalWidth() { - argsert([], 0); - return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; - } - updateLocale(obj) { - return this.updateStrings(obj); - } - updateStrings(obj) { - argsert('', [obj], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); - __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); - return this; - } - usage(msg, description, builder, handler) { - argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); - if (description !== undefined) { - assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - if ((msg || '').match(/^\$0( |$)/)) { - return this.command(msg, description, builder, handler); - } - else { - throw new YError('.usage() description must start with $0 if being used as alias for .command()'); - } - } - else { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); - return this; - } - } - usageConfiguration(config) { - argsert('', [config], arguments.length); - __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); - return this; - } - version(opt, msg, ver) { - const defaultVersionOpt = 'version'; - argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); - if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { - this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); - __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); - } - if (arguments.length === 0) { - ver = this[kGuessVersion](); - opt = defaultVersionOpt; - } - else if (arguments.length === 1) { - if (opt === false) { - return this; - } - ver = opt; - opt = defaultVersionOpt; - } - else if (arguments.length === 2) { - ver = msg; - msg = undefined; - } - __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); - msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); - this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); - this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); - return this; - } - wrap(cols) { - argsert('', [cols], arguments.length); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); - return this; - } - [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { - if (!argv._ || !argv['--']) - return argv; - argv._.push.apply(argv._, argv['--']); - try { - delete argv['--']; - } - catch (_err) { } - return argv; - } - [kCreateLogger]() { - return { - log: (...args) => { - if (!this[kHasParseCallback]()) - console.log(...args); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); - }, - error: (...args) => { - if (!this[kHasParseCallback]()) - console.error(...args); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); - __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); - }, - }; - } - [kDeleteFromParserHintObject](optionKey) { - objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { - if (((key) => key === 'configObjects')(hintKey)) - return; - const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; - if (Array.isArray(hint)) { - if (hint.includes(optionKey)) - hint.splice(hint.indexOf(optionKey), 1); - } - else if (typeof hint === 'object') { - delete hint[optionKey]; - } - }); - delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; - } - [kEmitWarning](warning, type, deduplicationId) { - if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { - __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); - __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; - } - } - [kFreeze]() { - __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ - options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), - configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), - exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), - groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), - strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), - strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), - strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), - completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), - output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), - exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), - hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), - parsed: this.parsed, - parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), - parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), - }); - __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); - __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); - } - [kGetDollarZero]() { - let $0 = ''; - let default$0; - if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { - default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); - } - else { - default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); - } - $0 = default$0 - .map(x => { - const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); - return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; - }) - .join(' ') - .trim(); - if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { - $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") - .getEnv('_') - .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); - } - return $0; - } - [kGetParserConfiguration]() { - return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); - } - [kGetUsageConfiguration]() { - return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); - } - [kGuessLocale]() { - if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) - return; - const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || - __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || - 'en_US'; - this.locale(locale.replace(/[.:].*/, '')); - } - [kGuessVersion]() { - const obj = this[kPkgUp](); - return obj.version || 'unknown'; - } - [kParsePositionalNumbers](argv) { - const args = argv['--'] ? argv['--'] : argv._; - for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { - if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && - Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { - args[i] = Number(arg); - } - } - return argv; - } - [kPkgUp](rootPath) { - const npath = rootPath || '*'; - if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) - return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; - let obj = {}; - try { - let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; - if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { - startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); - } - const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { - if (names.includes('package.json')) { - return 'package.json'; - } - else { - return undefined; - } - }); - assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); - } - catch (_noop) { } - __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; - return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; - } - [kPopulateParserHintArray](type, keys) { - keys = [].concat(keys); - keys.forEach(key => { - key = this[kSanitizeKey](key); - __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); - }); - } - [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { - this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { - __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; - }); - } - [kPopulateParserHintArrayDictionary](builder, type, key, value) { - this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { - __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); - }); - } - [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { - if (Array.isArray(key)) { - key.forEach(k => { - builder(k, value); - }); - } - else if (((key) => typeof key === 'object')(key)) { - for (const k of objectKeys(key)) { - builder(k, key[k]); - } - } - else { - singleKeyHandler(type, this[kSanitizeKey](key), value); - } - } - [kSanitizeKey](key) { - if (key === '__proto__') - return '___proto___'; - return key; - } - [kSetKey](key, set) { - this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); - return this; - } - [kUnfreeze]() { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; - const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); - assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); - let configObjects; - (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { - options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, - configObjects, - exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, - groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, - output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, - exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, - hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, - parsed: this.parsed, - strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, - strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, - strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, - completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, - parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, - parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, - } = frozen); - __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; - __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); - __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); - } - [kValidateAsync](validation, argv) { - return maybeAsyncResult(argv, result => { - validation(result); - return result; - }); - } - getInternalMethods() { - return { - getCommandInstance: this[kGetCommandInstance].bind(this), - getContext: this[kGetContext].bind(this), - getHasOutput: this[kGetHasOutput].bind(this), - getLoggerInstance: this[kGetLoggerInstance].bind(this), - getParseContext: this[kGetParseContext].bind(this), - getParserConfiguration: this[kGetParserConfiguration].bind(this), - getUsageConfiguration: this[kGetUsageConfiguration].bind(this), - getUsageInstance: this[kGetUsageInstance].bind(this), - getValidationInstance: this[kGetValidationInstance].bind(this), - hasParseCallback: this[kHasParseCallback].bind(this), - isGlobalContext: this[kIsGlobalContext].bind(this), - postProcess: this[kPostProcess].bind(this), - reset: this[kReset].bind(this), - runValidation: this[kRunValidation].bind(this), - runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), - setHasOutput: this[kSetHasOutput].bind(this), - }; - } - [kGetCommandInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_command, "f"); - } - [kGetContext]() { - return __classPrivateFieldGet(this, _YargsInstance_context, "f"); - } - [kGetHasOutput]() { - return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); - } - [kGetLoggerInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); - } - [kGetParseContext]() { - return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; - } - [kGetUsageInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); - } - [kGetValidationInstance]() { - return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); - } - [kHasParseCallback]() { - return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); - } - [kIsGlobalContext]() { - return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); - } - [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { - if (calledFromCommand) - return argv; - if (isPromise(argv)) - return argv; - if (!populateDoubleDash) { - argv = this[kCopyDoubleDash](argv); - } - const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || - this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; - if (parsePositionalNumbers) { - argv = this[kParsePositionalNumbers](argv); - } - if (runGlobalMiddleware) { - argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); - } - return argv; - } - [kReset](aliases = {}) { - __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); - const tmpOptions = {}; - tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; - tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; - const localLookup = {}; - tmpOptions.local.forEach(l => { - localLookup[l] = true; - (aliases[l] || []).forEach(a => { - localLookup[a] = true; - }); - }); - Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { - const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); - if (keys.length > 0) { - acc[groupName] = keys; - } - return acc; - }, {})); - __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); - const arrayOptions = [ - 'array', - 'boolean', - 'string', - 'skipValidation', - 'count', - 'normalize', - 'number', - 'hiddenOptions', - ]; - const objectOptions = [ - 'narg', - 'key', - 'alias', - 'default', - 'defaultDescription', - 'config', - 'choices', - 'demandedOptions', - 'demandedCommands', - 'deprecatedOptions', - ]; - arrayOptions.forEach(k => { - tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); - }); - objectOptions.forEach((k) => { - tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); - }); - tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; - __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); - __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") - ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) - : usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") - ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) - : validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") - ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() - : command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) - __classPrivateFieldSet(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); - __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); - __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); - __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); - __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); - __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); - this.parsed = false; - return this; - } - [kRebase](base, dir) { - return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); - } - [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { - var _a, _b, _c, _d; - let skipValidation = !!calledFromCommand || helpOnly; - args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); - __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; - __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); - const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; - const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { - 'populate--': true, - }); - const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { - configuration: { 'parse-positional-numbers': false, ...config }, - })); - const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); - let argvPromise = undefined; - const aliases = parsed.aliases; - let helpOptSet = false; - let versionOptSet = false; - Object.keys(argv).forEach(key => { - if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { - helpOptSet = true; - } - else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { - versionOptSet = true; - } - }); - argv.$0 = this.$0; - this.parsed = parsed; - if (commandIndex === 0) { - __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); - } - try { - this[kGuessLocale](); - if (shortCircuit) { - return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); - } - if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { - const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] - .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) - .filter(k => k.length > 1); - if (helpCmds.includes('' + argv._[argv._.length - 1])) { - argv._.pop(); - helpOptSet = true; - } - } - __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); - const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); - const requestCompletions = ((_a = __classPrivateFieldGet(this, _YargsInstance_completion, "f")) === null || _a === void 0 ? void 0 : _a.completionKey) - ? [ - (_b = __classPrivateFieldGet(this, _YargsInstance_completion, "f")) === null || _b === void 0 ? void 0 : _b.completionKey, - ...((_d = this.getAliases()[(_c = __classPrivateFieldGet(this, _YargsInstance_completion, "f")) === null || _c === void 0 ? void 0 : _c.completionKey]) !== null && _d !== void 0 ? _d : []), - ].some((key) => Object.prototype.hasOwnProperty.call(argv, key)) - : false; - const skipRecommendation = helpOptSet || requestCompletions || helpOnly; - if (argv._.length) { - if (handlerKeys.length) { - let firstUnknownCommand; - for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { - cmd = String(argv._[i]); - if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { - const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); - return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); - } - else if (!firstUnknownCommand && - cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { - firstUnknownCommand = cmd; - break; - } - } - if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && - __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && - firstUnknownCommand && - !skipRecommendation) { - __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); - } - } - if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && - argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && - !requestCompletions) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - this.showCompletionScript(); - this.exit(0); - } - } - if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { - const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); - return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); - } - if (requestCompletions) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - args = [].concat(args); - const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); - __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { - if (err) - throw new YError(err.message); - (completions || []).forEach(completion => { - __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); - }); - this.exit(0); - }); - return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); - } - if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { - if (helpOptSet) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - skipValidation = true; - this.showHelp(message => { - __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(message); - this.exit(0); - }); - } - else if (versionOptSet) { - if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) - setBlocking(true); - skipValidation = true; - __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); - this.exit(0); - } - } - if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { - skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); - } - if (!skipValidation) { - if (parsed.error) - throw new YError(parsed.error.message); - if (!requestCompletions) { - const validation = this[kRunValidation](aliases, {}, parsed.error); - if (!calledFromCommand) { - argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); - } - argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); - if (isPromise(argvPromise) && !calledFromCommand) { - argvPromise = argvPromise.then(() => { - return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); - }); - } - } - } - } - catch (err) { - if (err instanceof YError) - __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); - else - throw err; - } - return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); - } - [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { - const demandedOptions = { ...this.getDemandedOptions() }; - return (argv) => { - if (parseErrors) - throw new YError(parseErrors.message); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); - let failedStrictCommands = false; - if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { - failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); - } - if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { - __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); - } - else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { - __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); - } - __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); - __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); - }; - } - [kSetHasOutput]() { - __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); - } - [kTrackManuallySetKeys](keys) { - if (typeof keys === 'string') { - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; - } - else { - for (const k of keys) { - __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; - } - } - } -} -function isYargsInstance(y) { - return !!y && typeof y.getInternalMethods === 'function'; -} - -const Yargs = YargsFactory(shim$1); - -export { McpServer, StdioServerTransport, WebSocket, hideBin, Yargs as yargs, z }; diff --git a/tunnel/build/src/transport.js b/tunnel/build/src/transport.js deleted file mode 100644 index 62dec528..00000000 --- a/tunnel/build/src/transport.js +++ /dev/null @@ -1,53 +0,0 @@ -/** Convert wire headers (Record) to fetch Headers. */ -export function wireHeadersToHeaders(wire) { - const h = new Headers(); - for (const [name, values] of Object.entries(wire)) { - for (const v of values) { - h.append(name, v); - } - } - return h; -} -/** - * Convert fetch Headers to wire headers (Record). - * - * Note: Headers.forEach provides comma-joined values per the Fetch spec. - * This is lossy for headers whose values contain commas internally. - * Set-Cookie is handled correctly via getSetCookie(). For the tunnel proxy - * use case this is effectively harmless. - */ -export function headersToWireHeaders(headers) { - const wire = {}; - const setCookies = headers.getSetCookie(); - if (setCookies.length > 0) { - wire['set-cookie'] = setCookies; - } - headers.forEach((value, name) => { - if (name.toLowerCase() === 'set-cookie') - return; - wire[name] = [value]; - }); - return wire; -} -/** - * Strip transfer-encoding headers that are invalid after transparent - * decompression by Node's fetch. Both transports call this after - * headersToWireHeaders(). - */ -export function stripTransferHeaders(wire) { - delete wire['content-encoding']; - delete wire['content-length']; -} -/** Parse a host:port string, returning hostname and numeric port. */ -export function parseHostPort(hostport, defaultPort = 80) { - const lastColon = hostport.lastIndexOf(':'); - if (lastColon >= 0) { - return { - hostname: hostport.slice(0, lastColon), - port: parseInt(hostport.slice(lastColon + 1), 10) || defaultPort, - }; - } - return { hostname: hostport, port: defaultPort }; -} -/** Maximum size for JSON headers received over the yamux wire format. */ -export const MAX_YAMUX_HEADER_BYTES = 1024 * 1024; // 1 MB diff --git a/tunnel/build/src/transport_legacy.js b/tunnel/build/src/transport_legacy.js deleted file mode 100644 index 1b9a2783..00000000 --- a/tunnel/build/src/transport_legacy.js +++ /dev/null @@ -1,247 +0,0 @@ -import { WebSocket } from './third_party/index.js'; -import * as net from 'node:net'; -import { gzip } from 'node:zlib'; -import { promisify } from 'node:util'; -const gzipAsync = promisify(gzip); -import { MAX_INFLIGHT, MAX_RESPONSE_BODY_BYTES } from './types.js'; -import { matchesAny } from './allowlist.js'; -import { resolveLoopbackOrigin } from './loopback.js'; -import { wireHeadersToHeaders, headersToWireHeaders, stripTransferHeaders, parseHostPort } from './transport.js'; -/** - * LegacyTransport handles the JSON-over-WebSocket protocol with base64-encoded - * bodies, channel-based stream management, and pause/resume flow control. - */ -export class LegacyTransport { - #ws; - #log; - #onActivity; - #allowedOrigins; - #inflight = new Map(); - #streams = new Map(); - constructor(opts) { - this.#ws = opts.ws; - this.#log = opts.log; - this.#onActivity = opts.onActivity; - this.#allowedOrigins = opts.allowedOrigins ?? []; - } - serve() { - return new Promise((resolve) => { - const handler = (data) => { - this.#onActivity(); - let msg; - try { - msg = JSON.parse(data.toString()); - } - catch { - this.#log(`Invalid message from relay: ${data.toString().slice(0, 200)}`); - return; - } - switch (msg.type) { - case 'request': - void this.#handleRequest(msg); - break; - case 'connect': - void this.#handleConnect(msg); - break; - case 'data': - this.#handleStreamData(msg); - break; - case 'end': - this.#handleStreamEnd(msg); - break; - case 'pause': - this.#handleStreamPause(msg); - break; - case 'resume': - this.#handleStreamResume(msg); - break; - case 'ping': - this.#send({ type: 'pong' }); - break; - default: - this.#log(`Unknown message type: ${msg.type}`); - } - }; - this.#ws.on('message', handler); - this.#ws.once('close', () => { - this.#ws.removeListener('message', handler); - resolve(); - }); - }); - } - close() { - this.#abortInflight(); - this.#closeStreams(); - } - // ----- Request handling ----- - async #handleRequest(msg) { - if (this.#inflight.size >= MAX_INFLIGHT) { - this.#send({ - type: 'error', - requestId: msg.requestId, - message: `Too many inflight requests (max ${MAX_INFLIGHT})`, - }); - return; - } - const ac = new AbortController(); - this.#inflight.set(msg.requestId, ac); - try { - // The relay is the source of truth for which origin a request belongs - // to. A request without `origin` is a protocol violation by the relay. - if (!msg.origin) { - throw new Error('legacy request missing origin'); - } - const origin = msg.origin; - if (this.#allowedOrigins.length > 0 && !matchesAny(this.#allowedOrigins, origin)) { - throw new Error(`origin not in allowlist: ${origin}`); - } - const resolved = await resolveLoopbackOrigin(origin); - const url = resolved.ipUrl + msg.url; - const headers = wireHeadersToHeaders(msg.headers); - headers.set('Host', `${resolved.hostname}:${resolved.port}`); - const body = msg.body !== null ? Buffer.from(msg.body, 'base64') : undefined; - const resp = await fetch(url, { - method: msg.method, - headers, - body, - signal: ac.signal, - redirect: 'manual', - }); - const respBody = await resp.arrayBuffer(); - if (respBody.byteLength > MAX_RESPONSE_BODY_BYTES) { - this.#send({ - type: 'error', - requestId: msg.requestId, - message: `Response body too large: ${respBody.byteLength} bytes (max ${MAX_RESPONSE_BODY_BYTES})`, - }); - return; - } - const respHeaders = headersToWireHeaders(resp.headers); - stripTransferHeaders(respHeaders); - let bodyBuf = Buffer.from(respBody); - let encoding; - if (bodyBuf.length > 0) { - const compressed = await gzipAsync(bodyBuf); - if (compressed.length < bodyBuf.length) { - bodyBuf = compressed; - encoding = 'gzip'; - } - } - const encodedBody = bodyBuf.length > 0 ? bodyBuf.toString('base64') : null; - this.#send({ - type: 'response', - requestId: msg.requestId, - status: resp.status, - headers: respHeaders, - body: encodedBody, - encoding, - }); - } - catch (err) { - if (ac.signal.aborted) - return; - const message = err instanceof Error ? err.message : String(err); - this.#send({ - type: 'error', - requestId: msg.requestId, - message, - }); - } - finally { - this.#inflight.delete(msg.requestId); - } - } - // ----- CONNECT stream handling ----- - async #handleConnect(msg) { - const { streamId, host } = msg; - this.#log(`Stream ${streamId}: connecting to ${host}`); - const { hostname, port } = parseHostPort(host); - // Resolve and pin to a loopback IP before connecting. Same IPv4-preference - // logic as HTTP: avoids ::1 winning on dual-stack hosts when the server - // only binds 127.0.0.1. - let resolvedIp; - try { - ({ resolvedIp } = await resolveLoopbackOrigin(`http://${hostname}:${port}`)); - } - catch (err) { - this.#log(`Stream ${streamId}: loopback resolve failed: ${err.message}`); - this.#send({ type: 'stream_error', streamId, message: err.message }); - return; - } - const socket = net.connect({ host: resolvedIp, port }); - socket.once('connect', () => { - this.#log(`Stream ${streamId}: connected to ${host}`); - this.#streams.set(streamId, socket); - this.#send({ type: 'connected', streamId }); - socket.on('data', (chunk) => { - this.#send({ - type: 'data', - streamId, - data: chunk.toString('base64'), - }); - }); - socket.on('end', () => { - this.#log(`Stream ${streamId}: remote end closed`); - this.#streams.delete(streamId); - this.#send({ type: 'end', streamId }); - }); - socket.on('error', (err) => { - this.#log(`Stream ${streamId}: socket error: ${err.message}`); - this.#streams.delete(streamId); - this.#send({ type: 'end', streamId }); - }); - }); - socket.once('error', (err) => { - if (!this.#streams.has(streamId)) { - this.#log(`Stream ${streamId}: connect error: ${err.message}`); - this.#send({ type: 'stream_error', streamId, message: err.message }); - } - }); - } - #handleStreamData(msg) { - const socket = this.#streams.get(msg.streamId); - if (socket) { - socket.write(Buffer.from(msg.data, 'base64')); - } - } - #handleStreamEnd(msg) { - const socket = this.#streams.get(msg.streamId); - if (socket) { - this.#streams.delete(msg.streamId); - socket.end(); - } - } - #handleStreamPause(msg) { - const socket = this.#streams.get(msg.streamId); - if (socket) { - socket.pause(); - } - } - #handleStreamResume(msg) { - const socket = this.#streams.get(msg.streamId); - if (socket) { - socket.resume(); - } - } - // ----- Helpers ----- - #send(msg) { - if (this.#ws?.readyState === WebSocket.OPEN) { - this.#ws.send(JSON.stringify(msg)); - return true; - } - this.#log(`Dropped ${msg.type} message (ws state=${this.#ws?.readyState})`); - return false; - } - #abortInflight() { - for (const ac of this.#inflight.values()) { - ac.abort(); - } - this.#inflight.clear(); - } - #closeStreams() { - for (const socket of this.#streams.values()) { - socket.end(); - } - this.#streams.clear(); - } -} diff --git a/tunnel/build/src/transport_yamux.js b/tunnel/build/src/transport_yamux.js deleted file mode 100644 index 269f6e58..00000000 --- a/tunnel/build/src/transport_yamux.js +++ /dev/null @@ -1,251 +0,0 @@ -import * as net from 'node:net'; -import { matchesAny } from './allowlist.js'; -import { resolveLoopbackOrigin } from './loopback.js'; -import { MAX_RESPONSE_BODY_BYTES } from './types.js'; -import { wireHeadersToHeaders, headersToWireHeaders, stripTransferHeaders, parseHostPort, MAX_YAMUX_HEADER_BYTES, } from './transport.js'; -import { YamuxSession } from './yamux.js'; -export const STREAM_TYPE_REQUEST = 0x01; -export const STREAM_TYPE_CONNECT = 0x02; -export const CONNECT_STATUS_OK = 0x00; -export const CONNECT_STATUS_ERR = 0x01; -/** - * YamuxTransport handles the binary yamux multiplexing protocol. After the - * hello/ready handshake, the WebSocket carries raw yamux frames. The server - * opens streams; each stream starts with a 1-byte type prefix: - * - * - STREAM_TYPE_REQUEST (0x01): HTTP request/response - * - STREAM_TYPE_CONNECT (0x02): CONNECT (TCP pipe) - */ -export class YamuxTransport { - #log; - #session; - #streaming; - #allowedOrigins; - constructor(opts) { - this.#log = opts.log; - this.#session = new YamuxSession(opts.ws, { - onActivity: opts.onActivity, - pingIntervalMs: opts.pingIntervalMs, - }); - this.#streaming = opts.streaming ?? false; - this.#allowedOrigins = opts.allowedOrigins ?? []; - } - async serve() { - while (true) { - const stream = await this.#session.accept(); - if (stream === null) - break; - void this.#handleStream(stream).catch((err) => { - this.#log(`yamux stream ${stream.id} error: ${errMsg(err)}`); - }); - } - } - close() { - this.#session.close(); - } - // ----- Stream dispatch ----- - async #handleStream(stream) { - const typeBuf = await stream.readExact(1); - const streamType = typeBuf[0]; - if (streamType === STREAM_TYPE_REQUEST) { - await this.#handleHttpStream(stream); - } - else if (streamType === STREAM_TYPE_CONNECT) { - await this.#handleConnectStream(stream); - } - else { - this.#log(`yamux stream ${stream.id}: unknown type 0x${streamType.toString(16)}`); - stream.close(); - } - } - // ----- Shared: read length-prefixed JSON header from stream ----- - async #readJsonHeader(stream) { - const lenBuf = await stream.readExact(4); - const headerLen = lenBuf.readUInt32BE(0); - if (headerLen > MAX_YAMUX_HEADER_BYTES) { - throw new Error(`header too large: ${headerLen} bytes (max ${MAX_YAMUX_HEADER_BYTES})`); - } - const headerBuf = await stream.readExact(headerLen); - return JSON.parse(headerBuf.toString()); - } - // ----- HTTP request/response ----- - async #handleHttpStream(stream) { - try { - const header = await this.#readJsonHeader(stream); - let reqBody; - if (header.bodyLen > 0) { - reqBody = await stream.readExact(header.bodyLen); - } - // The relay is the source of truth for which origin a request belongs - // to. A header without `origin` is a protocol violation by the relay. - if (!header.origin) { - throw new Error('yamux request header missing origin'); - } - const origin = header.origin; - // Allowlist gate: defense in depth. The relay also enforces this — but - // a compromised or buggy relay must not be able to drive us to fetch an - // origin the user didn't opt into. - if (this.#allowedOrigins.length > 0 && !matchesAny(this.#allowedOrigins, origin)) { - throw new Error(`origin not in allowlist: ${origin}`); - } - // DNS resolve-and-pin: rebinding defense. resolveLoopbackOrigin does - // ONE DNS lookup, asserts loopback, and gives us back a URL with the - // resolved IP literal so fetch() doesn't re-resolve. The Host: header - // is restored to the original hostname so virtual-host routing on the - // upstream still works. - const resolved = await resolveLoopbackOrigin(origin); - const url = resolved.ipUrl + header.url; - const fetchHeaders = wireHeadersToHeaders(header.headers); - // Set Host explicitly even when it's already in headers — the - // resolved IP URL has the wrong authority for Host inference. - fetchHeaders.set('Host', `${resolved.hostname}:${resolved.port}`); - const resp = await fetch(url, { - method: header.method, - headers: fetchHeaders, - body: reqBody, - redirect: 'manual', - }); - const respHeaders = headersToWireHeaders(resp.headers); - stripTransferHeaders(respHeaders); - if (this.#streaming) { - // Send header immediately, then stream body bytes until FIN. - await stream.write(streamingResponseFrame(resp.status, respHeaders)); - if (resp.body) { - const reader = resp.body.getReader(); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) - break; - await stream.write(Buffer.from(value.buffer, value.byteOffset, value.byteLength)); - } - } - finally { - reader.releaseLock(); - } - } - } - else { - const respBody = await resp.arrayBuffer(); - if (respBody.byteLength > MAX_RESPONSE_BODY_BYTES) { - throw new Error(`response body too large: ${respBody.byteLength} bytes (max ${MAX_RESPONSE_BODY_BYTES})`); - } - await stream.write(bufferedResponseFrame(resp.status, respHeaders, Buffer.from(respBody))); - } - } - catch (err) { - await this.#writeHttpError(stream, err); - throw err; - } - finally { - stream.close(); - } - } - // ----- CONNECT (TCP pipe) ----- - async #handleConnectStream(stream) { - const { host } = await this.#readJsonHeader(stream); - this.#log(`yamux stream ${stream.id}: CONNECT ${host}`); - const { hostname, port } = parseHostPort(host); - // Resolve and pin to a loopback IP before connecting. Same IPv4-preference - // logic as HTTP: avoids ::1 winning on dual-stack hosts when the server - // only binds 127.0.0.1. - let resolvedIp; - try { - ({ resolvedIp } = await resolveLoopbackOrigin(`http://${hostname}:${port}`)); - } - catch (err) { - const msg = err instanceof Error ? err.message : String(err); - this.#log(`yamux stream ${stream.id}: loopback resolve error: ${msg}`); - const errBuf = Buffer.from(msg); - const resp = Buffer.allocUnsafe(1 + errBuf.length); - resp[0] = CONNECT_STATUS_ERR; - errBuf.copy(resp, 1); - await stream.write(resp).catch(() => undefined); - stream.close(); - return; - } - const socket = net.connect({ host: resolvedIp, port }); - try { - await new Promise((resolve, reject) => { - socket.once('connect', resolve); - socket.once('error', reject); - }); - } - catch (err) { - const msg = err instanceof Error ? err.message : String(err); - this.#log(`yamux stream ${stream.id}: connect error: ${msg}`); - const errBuf = Buffer.from(msg); - const resp = Buffer.allocUnsafe(1 + errBuf.length); - resp[0] = CONNECT_STATUS_ERR; - errBuf.copy(resp, 1); - await stream.write(resp).catch(() => undefined); - stream.close(); - return; - } - // Write success byte. - await stream.write(Buffer.from([CONNECT_STATUS_OK])); - // Pump socket -> yamux stream with backpressure. - const socketDone = new Promise((resolve) => { - socket.on('data', (chunk) => { - socket.pause(); - stream - .write(chunk) - .then(() => { - socket.resume(); - }) - .catch(() => { - socket.destroy(); - resolve(); - }); - }); - socket.once('end', () => { - stream.close(); - resolve(); - }); - socket.once('error', () => { - stream.close(); - resolve(); - }); - }); - // Pump yamux stream -> socket (read loop). - const yamuxDone = (async () => { - try { - while (true) { - const chunk = await stream.read(); - if (chunk.length === 0) { - socket.end(); - break; - } - socket.write(chunk); - } - } - catch { - socket.destroy(); - } - })(); - await Promise.all([socketDone, yamuxDone]); - } - // Write a synthetic 502 so the relay reads a valid framed response instead of EOF. - // Mirrors the error-response path in #handleConnectStream. - async #writeHttpError(stream, err) { - const body = Buffer.from(errMsg(err)); - await stream.write(bufferedResponseFrame(502, {}, body)).catch(() => undefined); - } -} -function errMsg(err) { - return err instanceof Error ? err.message : String(err); -} -/** Build a length-prefixed JSON frame: [4-byte hdr len][hdr JSON][optional body]. */ -export function frameJson(hdrJson, body) { - const lenPrefix = Buffer.allocUnsafe(4); - lenPrefix.writeUInt32BE(hdrJson.length, 0); - return body ? Buffer.concat([lenPrefix, hdrJson, body]) : Buffer.concat([lenPrefix, hdrJson]); -} -/** Streaming response frame: header only, body follows as raw chunks until FIN. */ -export function streamingResponseFrame(status, headers) { - return frameJson(Buffer.from(JSON.stringify({ status, headers }))); -} -/** Buffered response frame: header + full body in one write. */ -export function bufferedResponseFrame(status, headers, body) { - return frameJson(Buffer.from(JSON.stringify({ status, headers, bodyLen: body.length })), body); -} diff --git a/tunnel/build/src/types.js b/tunnel/build/src/types.js deleted file mode 100644 index 54446263..00000000 --- a/tunnel/build/src/types.js +++ /dev/null @@ -1,22 +0,0 @@ -// Wire protocol message types for the tunnel relay. -// See docs/design.md for the full protocol specification. -// Resume subprotocol: the client sends `${RESUME_SUBPROTOCOL_PREFIX}${token}` -// as a Sec-WebSocket-Protocol; the server echoes the same full string on success. -export const RESUME_SUBPROTOCOL = 'subtext-resume.v1'; -export const RESUME_SUBPROTOCOL_PREFIX = RESUME_SUBPROTOCOL + '.'; -// Limits -export const MAX_INFLIGHT = 20; -export const MAX_RESPONSE_BODY_BYTES = 200 * 1024 * 1024; // 200 MB -export const REQUEST_TIMEOUT_MS = 30_000; // 30s -export const RECONNECT_BASE_MS = 1_000; // 1s -export const RECONNECT_MAX_MS = 30_000; // 30s -// 90s — if no message at all (yamux frame, ping, ack) arrives within this -// window, we treat the WS as silently dropped and reconnect. Applies to both -// legacy and yamux transports; yamux liveness used to rely solely on -// server-initiated keepalives, which silently failed when intermediate -// infra (linkerd, NATs, LBs) dropped the connection without delivering FIN. -export const STALE_CONNECTION_MS = 90_000; -// 30s — yamux client-initiated PING cadence. Well under STALE_CONNECTION_MS -// so a single missed round-trip doesn't trip the stale timer, but frequent -// enough to keep stateful intermediaries from idling the WS out. -export const YAMUX_PING_INTERVAL_MS = 30_000; diff --git a/tunnel/build/src/yamux.js b/tunnel/build/src/yamux.js deleted file mode 100644 index 626165b0..00000000 --- a/tunnel/build/src/yamux.js +++ /dev/null @@ -1,449 +0,0 @@ -/** - * Minimal yamux client implementation. - * - * Only implements the CLIENT role: accepts streams opened by the server, - * reads/writes data on those streams, and responds to pings. It never - * initiates streams (no Open) and never sends GoAway. - * - * Wire format reference: https://github.com/hashicorp/yamux/blob/master/spec.md - * - * Each yamux frame has a 12-byte header (big-endian): - * [0] version (always 0) - * [1] type (0=data, 1=window_update, 2=ping, 3=go_away) - * [2-3] flags (SYN=0x01, ACK=0x02, FIN=0x04, RST=0x08) - * [4-7] streamId - * [8-11] length (for DATA: payload size; for others: a value, no payload follows) - */ -// ----- Protocol constants ----- -const PROTO_VERSION = 0; -export const HEADER_SIZE = 12; -/** Initial send/receive window per stream (matches hashicorp/yamux default). */ -export const INITIAL_WINDOW = 256 * 1024; -export const TYPE_DATA = 0; -export const TYPE_WINDOW_UPDATE = 1; -export const TYPE_PING = 2; -export const TYPE_GO_AWAY = 3; -export const FLAG_SYN = 0x01; -export const FLAG_ACK = 0x02; -export const FLAG_FIN = 0x04; -export const FLAG_RST = 0x08; -// ----- YamuxStream ----- -/** - * One bidirectional stream opened by the server. Supports sequential - * readExact / readAll / write operations. Not safe for concurrent reads or - * concurrent writes; the use-pattern is one reader and one writer. - */ -export class YamuxStream { - id; - #session; - // Receive side - #recvBuf = Buffer.alloc(0); - #recvWindow = INITIAL_WINDOW; // remaining receive quota - #recvConsumed = 0; // bytes consumed since last window update sent - // Send side (starts at INITIAL_WINDOW; incremented by window_update from server) - #sendWindow = INITIAL_WINDOW; - #sendWaiters = []; - #finReceived = false; - #rstReceived = false; - #closed = false; - // Resolved when new data (or FIN/RST) is added to #recvBuf. - // Only one outstanding waiter at a time (sequential reads). - #recvWaiter = null; - constructor(id, session) { - this.id = id; - this.#session = session; - } - // ----- Called by YamuxSession ----- - _onData(data) { - this.#recvWindow -= data.length; - if (this.#recvWindow < 0) { - // Server violated our receive window — treat as protocol error. - this._onRst(); - return; - } - this.#recvBuf = Buffer.concat([this.#recvBuf, data]); - this.#recvWaiter?.(); - this.#recvWaiter = null; - } - _onFin() { - this.#finReceived = true; - this.#recvWaiter?.(); - this.#recvWaiter = null; - } - _onRst() { - this.#rstReceived = true; - this.#closed = true; - this.#recvWaiter?.(); - this.#recvWaiter = null; - const waiters = this.#sendWaiters.splice(0); - for (const w of waiters) - w(); - } - _onWindowUpdate(delta) { - this.#sendWindow += delta; - const waiters = this.#sendWaiters.splice(0); - for (const w of waiters) - w(); - } - // ----- Public API ----- - /** - * Read exactly `n` bytes. Waits until enough bytes have arrived. - * Throws if the stream is reset or closed before `n` bytes arrive. - */ - async readExact(n) { - while (this.#recvBuf.length < n) { - if (this.#rstReceived) - throw new Error(`yamux stream ${this.id} reset`); - if (this.#finReceived || this.#closed) { - throw new Error(`yamux stream ${this.id} closed before ${n} bytes (have ${this.#recvBuf.length})`); - } - await new Promise((resolve) => { - this.#recvWaiter = resolve; - }); - } - const result = Buffer.from(this.#recvBuf.subarray(0, n)); - this.#recvBuf = this.#recvBuf.subarray(n); - this.#creditWindowFor(n); - return result; - } - /** - * Read and return whatever data is currently buffered, waiting if the buffer - * is empty. Returns an empty buffer on FIN (EOF). Throws on RST. - * Suitable for streaming/piping use cases where chunk boundaries don't matter. - */ - async read() { - while (this.#recvBuf.length === 0) { - if (this.#rstReceived) - throw new Error(`yamux stream ${this.id} reset`); - if (this.#finReceived || this.#closed) - return Buffer.alloc(0); - await new Promise((resolve) => { - this.#recvWaiter = resolve; - }); - } - const result = Buffer.from(this.#recvBuf); - const consumed = result.length; - this.#recvBuf = Buffer.alloc(0); - this.#creditWindowFor(consumed); - return result; - } - /** - * Read all remaining bytes until the stream is FIN-closed. - * Throws if the stream is reset. - */ - async readAll() { - const chunks = []; - while (true) { - if (this.#rstReceived) - throw new Error(`yamux stream ${this.id} reset`); - if ((this.#finReceived || this.#closed) && this.#recvBuf.length === 0) - break; - if (this.#recvBuf.length > 0) { - const consumed = this.#recvBuf.length; - chunks.push(Buffer.from(this.#recvBuf)); - this.#recvBuf = Buffer.alloc(0); - this.#creditWindowFor(consumed); - } - else { - await new Promise((resolve) => { - this.#recvWaiter = resolve; - }); - } - } - return Buffer.concat(chunks); - } - /** - * Write `data` to the stream, respecting the send window. - * Blocks if the window is exhausted until the server grants more credit. - */ - async write(data) { - if (this.#closed || this.#rstReceived) { - throw new Error(`yamux stream ${this.id} closed`); - } - let offset = 0; - while (offset < data.length) { - while (this.#sendWindow === 0) { - if (this.#rstReceived) - throw new Error(`yamux stream ${this.id} reset`); - if (this.#closed) - throw new Error(`yamux stream ${this.id} closed`); - await new Promise((resolve) => { - this.#sendWaiters.push(resolve); - }); - } - const n = Math.min(this.#sendWindow, data.length - offset); - this.#session._sendData(this.id, data.subarray(offset, offset + n)); - this.#sendWindow -= n; - offset += n; - } - } - /** Send FIN and remove this stream from the session. */ - close() { - if (this.#closed) - return; - this.#closed = true; - this.#session._sendFin(this.id); - this.#session._removeStream(this.id); - // Wake any blocked reader so it can observe the closed state. - this.#recvWaiter?.(); - this.#recvWaiter = null; - // Wake any blocked writer so it can observe the closed state. - const waiters = this.#sendWaiters.splice(0); - for (const w of waiters) - w(); - } - // ----- Private helpers ----- - /** Account for consumed bytes and send a window update when the threshold is met. */ - #creditWindowFor(n) { - this.#recvConsumed += n; - // Send update when consumed >= half the window (matches yamux heuristic). - if (this.#recvConsumed >= INITIAL_WINDOW / 2) { - this.#session._sendWindowUpdate(this.id, this.#recvConsumed); - this.#recvWindow += this.#recvConsumed; - this.#recvConsumed = 0; - } - } -} -export class YamuxSession { - #ws; - #streams = new Map(); - #onActivity; - #acceptQueue = []; - #acceptWaiters = []; - #closed = false; - #pingTimer = null; - #pingNonce = 0; - /** Accumulator for incomplete frames across WebSocket messages. */ - #readBuf = Buffer.alloc(0); - constructor(ws, opts = {}) { - this.#ws = ws; - this.#onActivity = opts.onActivity; - ws.on('message', (data) => { - // Any WS message — yamux frame, ping ack, anything — counts as the - // peer being alive. Reset the upstream stale timer before parsing so - // that even malformed frames keep liveness honest. - this.#onActivity?.(); - const chunk = toBuffer(data); - this.#readBuf = - this.#readBuf.length === 0 - ? chunk - : Buffer.concat([this.#readBuf, chunk]); - this.#processFrames(); - }); - ws.on('close', () => { - this.#onClose(); - }); - // Client-initiated keepalive. Server PINGs alone don't help when an - // intermediary has silently dropped our outbound path: we'd happily - // ack the next PING that arrives, but it never does, and we have no - // way to provoke one. Sending our own PINGs makes the WS bidirectional- - // active so stateful intermediaries don't idle-time us out, and forces - // an ACK back from the server which the activity hook above observes. - const pingMs = opts.pingIntervalMs ?? 0; - if (pingMs > 0) { - this.#pingTimer = setInterval(() => this.#sendPing(), pingMs); - // unref so a quiet session doesn't keep the event loop alive on its own. - this.#pingTimer.unref?.(); - } - } - #sendPing() { - if (this.#closed) - return; - // PING is identified by the SYN flag with a nonce in the length field; - // server echoes back with FLAG_ACK and the same nonce. - const nonce = (this.#pingNonce = (this.#pingNonce + 1) >>> 0); - try { - this.#ws.send(makeHeader(TYPE_PING, FLAG_SYN, 0, nonce)); - } - catch { - // WS may have torn down between ticks; close handler will reconcile. - } - } - // ----- Public API ----- - /** - * Wait for the next server-initiated stream. - * Returns `null` when the session closes. - */ - async accept() { - if (this.#acceptQueue.length > 0) - return this.#acceptQueue.shift(); - if (this.#closed) - return null; - return new Promise((resolve) => { - this.#acceptWaiters.push(resolve); - }); - } - /** Send GoAway (normal termination) and tear down all streams locally. */ - close() { - if (this.#closed) - return; - this.#closed = true; - if (this.#pingTimer !== null) { - clearInterval(this.#pingTimer); - this.#pingTimer = null; - } - try { - this.#ws.send(makeHeader(TYPE_GO_AWAY, 0, 0, 0 /* normal termination */)); - } - catch { - // WebSocket may already be closed — best effort. - } - for (const stream of this.#streams.values()) { - stream._onRst(); - } - this.#streams.clear(); - this.#drainWaiters(); - } - // ----- Called by YamuxStream ----- - _sendData(streamId, data) { - const hdr = makeHeader(TYPE_DATA, 0, streamId, data.length); - this.#ws.send(Buffer.concat([hdr, data])); - } - _sendWindowUpdate(streamId, delta) { - this.#ws.send(makeHeader(TYPE_WINDOW_UPDATE, 0, streamId, delta)); - } - _sendFin(streamId) { - // Send an empty DATA frame with FIN flag. - this.#ws.send(makeHeader(TYPE_DATA, FLAG_FIN, streamId, 0)); - } - _removeStream(streamId) { - this.#streams.delete(streamId); - } - // ----- Frame processing ----- - #processFrames() { - const buf = this.#readBuf; - let offset = 0; - while (offset + HEADER_SIZE <= buf.length) { - const version = buf[offset]; - if (version !== PROTO_VERSION) { - this.close(); - return; - } - const type = buf[offset + 1]; - const flags = buf.readUInt16BE(offset + 2); - const streamId = buf.readUInt32BE(offset + 4); - const length = buf.readUInt32BE(offset + 8); - if (type === TYPE_DATA) { - // DATA frames carry a payload of `length` bytes. - if (offset + HEADER_SIZE + length > buf.length) - break; // incomplete - const payload = buf.subarray(offset + HEADER_SIZE, offset + HEADER_SIZE + length); - this.#handleData(flags, streamId, payload); - offset += HEADER_SIZE + length; - } - else { - // All other frame types have no payload; `length` is a scalar value. - this.#handleControl(type, flags, streamId, length); - offset += HEADER_SIZE; - } - } - // Keep leftover bytes for the next message. - this.#readBuf = offset === 0 ? buf : buf.subarray(offset); - } - #handleData(flags, streamId, payload) { - if (flags & FLAG_SYN) { - this.#openStream(streamId); - } - const stream = this.#streams.get(streamId); - if (!stream) - return; - if (flags & FLAG_RST) { - stream._onRst(); - this.#streams.delete(streamId); - return; - } - if (payload.length > 0) { - stream._onData(payload); - } - if (flags & FLAG_FIN) { - stream._onFin(); - } - } - #handleControl(type, flags, streamId, length) { - switch (type) { - case TYPE_WINDOW_UPDATE: { - if (flags & FLAG_SYN) { - this.#openStream(streamId); - } - const stream = this.#streams.get(streamId); - if (stream) { - // Apply window delta regardless of SYN — the spec allows SYN/ACK - // to carry an initial window update indicating a larger window. - if (length > 0) { - stream._onWindowUpdate(length); - } - if (flags & FLAG_FIN) - stream._onFin(); - if (flags & FLAG_RST) { - stream._onRst(); - this.#streams.delete(streamId); - } - } - break; - } - case TYPE_PING: { - if (flags & FLAG_SYN) { - this.#ws.send(makeHeader(TYPE_PING, FLAG_ACK, 0, length)); - } - break; - } - case TYPE_GO_AWAY: - this.close(); - break; - default: - // Unknown frame type — protocol error, close the session. - this.close(); - break; - } - } - #openStream(streamId) { - if (this.#streams.has(streamId)) - return; // duplicate SYN; ignore - const stream = new YamuxStream(streamId, this); - this.#streams.set(streamId, stream); - // Respond with ACK (length=0 — both sides start with INITIAL_WINDOW already). - this.#ws.send(makeHeader(TYPE_WINDOW_UPDATE, FLAG_ACK, streamId, 0)); - if (this.#acceptWaiters.length > 0) { - this.#acceptWaiters.shift()(stream); - } - else { - this.#acceptQueue.push(stream); - } - } - #onClose() { - this.#closed = true; - if (this.#pingTimer !== null) { - clearInterval(this.#pingTimer); - this.#pingTimer = null; - } - for (const stream of this.#streams.values()) { - stream._onRst(); - } - this.#streams.clear(); - this.#drainWaiters(); - } - #drainWaiters() { - const waiters = this.#acceptWaiters.splice(0); - for (const w of waiters) - w(null); - } -} -// ----- Helpers ----- -export function makeHeader(type, flags, streamId, length) { - const hdr = Buffer.allocUnsafe(HEADER_SIZE); - hdr[0] = PROTO_VERSION; - hdr[1] = type; - hdr.writeUInt16BE(flags, 2); - hdr.writeUInt32BE(streamId, 4); - hdr.writeUInt32BE(length, 8); - return hdr; -} -function toBuffer(data) { - if (Buffer.isBuffer(data)) - return data; - if (data instanceof ArrayBuffer) - return Buffer.from(data); - if (Array.isArray(data)) - return Buffer.concat(data); - return Buffer.from(data); -} diff --git a/tunnel/package.json b/tunnel/package.json index 8b16184a..40bec743 100644 --- a/tunnel/package.json +++ b/tunnel/package.json @@ -1,20 +1,21 @@ { "name": "@fullstory/subtext-tunnel", - "version": "0.1.17", + "version": "0.1.18", "description": "MCP server for reverse tunneling to localhost — connects hosted Subtext browser tools to local dev servers.", "type": "module", "bin": { - "subtext-tunnel": "./build/src/index.js" + "subtext-tunnel": "./dist/index.js" }, "files": [ - "build/src/" + "dist/" ], "scripts": { - "clean": "node -e \"require('fs').rmSync('build', {recursive: true, force: true})\"", - "build": "tsc", - "bundle": "npm run clean && npm run build && rollup -c rollup.config.mjs", - "test": "node --test build/tests/**/*.js", - "prepublishOnly": "npm run bundle" + "clean": "node -e \"require('fs').rmSync('build', {recursive: true, force: true}); require('fs').rmSync('dist', {recursive: true, force: true})\"", + "build": "npm run clean && tsc", + "bundle": "npm run build && rollup -c rollup.config.mjs", + "test": "npm run build && node --test build/tests/**/*.js", + "verify": "npm pack --dry-run", + "prepack": "npm run bundle" }, "keywords": [ "mcp", diff --git a/tunnel/rollup.config.mjs b/tunnel/rollup.config.mjs index a2817458..9ae0fc4b 100644 --- a/tunnel/rollup.config.mjs +++ b/tunnel/rollup.config.mjs @@ -1,27 +1,30 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import commonjs from '@rollup/plugin-commonjs'; -import json from '@rollup/plugin-json'; -import {nodeResolve} from '@rollup/plugin-node-resolve'; -import cleanup from 'rollup-plugin-cleanup'; - -const thirdPartyDir = './build/src/third_party'; +import commonjs from "@rollup/plugin-commonjs"; +import json from "@rollup/plugin-json"; +import { nodeResolve } from "@rollup/plugin-node-resolve"; +import cleanup from "rollup-plugin-cleanup"; +// Bundle the entire CLI into a single self-contained file. tsc emits to +// build/ (used by tests + dev); rollup reads that and emits to dist/, which +// is what `npm publish` ships. Keeping input/output in different trees means +// `build` and `bundle` never clobber each other's output. export default { - input: path.join(thirdPartyDir, 'index.js'), + // index.ts is the real entry point: it does a Node-version-check and then + // dynamic-imports main. inlineDynamicImports below pulls main into the same + // bundled file so we ship one self-contained ./dist/index.js. + input: "./build/src/index.js", output: { - file: path.join(thirdPartyDir, 'index.js'), + file: "./dist/index.js", sourcemap: false, - format: 'esm', + format: "esm", inlineDynamicImports: true, + // Shebang is carried over from src/index.ts; no banner needed. }, // yargs and tslib emit TypeScript's __classPrivateField helpers that read // `this` at module top-level for a CJS caching trick. Rollup's ESM output // rewrites `this` to undefined and warns; pointing it at globalThis lets // the helper's `(this && this.x) || fallback` pattern evaluate cleanly. moduleContext: (id) => - /node_modules\/(yargs|tslib)\//.test(id) ? 'globalThis' : undefined, + /node_modules\/(yargs|tslib)\//.test(id) ? "globalThis" : undefined, plugins: [ cleanup({ comments: [/Copyright/i], @@ -34,8 +37,8 @@ export default { // Cycles inside third-party packages (zod, zod-to-json-schema) are not // something we can fix. Still warn about cycles in our own code. if ( - warning.code === 'CIRCULAR_DEPENDENCY' && - warning.message.includes('node_modules') + warning.code === "CIRCULAR_DEPENDENCY" && + warning.message.includes("node_modules") ) { return; } diff --git a/tunnel/src/main.ts b/tunnel/src/main.ts index be5f6ec6..6d1e7f0d 100644 --- a/tunnel/src/main.ts +++ b/tunnel/src/main.ts @@ -1,5 +1,5 @@ import process from "node:process"; -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; @@ -18,20 +18,27 @@ import { } from "./allowlist.js"; // Single source of truth: read version from package.json at runtime so it -// can't drift from what npm publishes. From build/src/main.js, package.json -// sits two levels up at the package root. -const pkg = JSON.parse( - readFileSync( - join(dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json"), - "utf8", - ), -) as { version: string }; +// can't drift from what npm publishes. The relative depth depends on where +// this file ends up: build/src/main.js (tsc, dev) is two levels deep; +// dist/index.js (rollup, published) is one level deep. Walk up until a +// package.json is found. +function findPackageJson(): string { + let dir = dirname(fileURLToPath(import.meta.url)); + for (let i = 0; i < 5; i++) { + const candidate = join(dir, "package.json"); + if (existsSync(candidate)) return candidate; + const parent = dirname(dir); + if (parent === dir) break; + dir = parent; + } + throw new Error("package.json not found near tunnel binary"); +} +const pkg = JSON.parse(readFileSync(findPackageJson(), "utf8")) as { + version: string; +}; const VERSION = pkg.version; -await yargs(hideBin(process.argv)) - .version(VERSION) - .help() - .parse(); +await yargs(hideBin(process.argv)).version(VERSION).help().parse(); // Wrap console.error so a broken stderr (e.g. parent process died and closed // the read side of the pipe) cannot recurse into our error handlers below. @@ -147,7 +154,7 @@ server.registerTool( { type: "text" as const, text: JSON.stringify( - {error: err instanceof Error ? err.message : String(err)}, + { error: err instanceof Error ? err.message : String(err) }, null, 2, ), @@ -159,7 +166,7 @@ server.registerTool( // Surface a clear error if the initial handshake fails with a rejection. let needsLiveTunnel = false; - client.once('need_live_tunnel', () => { + client.once("need_live_tunnel", () => { needsLiveTunnel = true; log(`Tunnel needs a fresh live-tunnel call (resume token rejected)`); }); @@ -168,7 +175,11 @@ server.registerTool( // Wait briefly for the handshake to complete const deadline = Date.now() + 5000; - while (client.state !== "ready" && !needsLiveTunnel && Date.now() < deadline) { + while ( + client.state !== "ready" && + !needsLiveTunnel && + Date.now() < deadline + ) { await new Promise((r) => setTimeout(r, 100)); } @@ -178,7 +189,7 @@ server.registerTool( // Capture id now: tunnelId is cleared by #onDisconnect() before the // reconnect that triggers need_live_tunnel, so reading client.tunnelId // at event-fire time is always undefined → stale map entry. - client.once('need_live_tunnel', () => clients.delete(id)); + client.once("need_live_tunnel", () => clients.delete(id)); } if (needsLiveTunnel) { @@ -187,7 +198,10 @@ server.registerTool( { type: "text" as const, text: JSON.stringify( - {error: "resume token rejected; call live-tunnel to get a fresh relay URL"}, + { + error: + "resume token rejected; call live-tunnel to get a fresh relay URL", + }, null, 2, ), @@ -325,7 +339,9 @@ process.on("SIGTERM", shutdown); // Claude Code loses the tunnel tools entirely. log() above is internally // guarded so it cannot itself throw and re-enter these handlers. process.on("unhandledRejection", (reason: unknown) => { - log(`Unhandled rejection: ${reason instanceof Error ? reason.stack ?? reason.message : String(reason)}`); + log( + `Unhandled rejection: ${reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)}`, + ); }); process.on("uncaughtException", (err: Error) => { log(`Uncaught exception: ${err.stack ?? err.message}`); @@ -352,7 +368,8 @@ process.stdout.on("error", (err: NodeJS.ErrnoException) => { // Default 30s; overridable for tests. unref() so the timer alone doesn't // keep the event loop alive. -const orphanCheckMs = Number(process.env.SUBTEXT_TUNNEL_ORPHAN_CHECK_MS) || 30_000; +const orphanCheckMs = + Number(process.env.SUBTEXT_TUNNEL_ORPHAN_CHECK_MS) || 30_000; const orphanTimer = setInterval(() => { if (process.ppid === 1) process.exit(0); }, orphanCheckMs); From c976e872b95ea204b7626f789e3344f0494a62af Mon Sep 17 00:00:00 2001 From: Chip Lay Date: Thu, 21 May 2026 22:29:43 -0400 Subject: [PATCH 2/2] Add changeset for tunnel package hygiene (minor bump) --- .changeset/tunnel-package-hygiene.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/tunnel-package-hygiene.md diff --git a/.changeset/tunnel-package-hygiene.md b/.changeset/tunnel-package-hygiene.md new file mode 100644 index 00000000..d6f94df7 --- /dev/null +++ b/.changeset/tunnel-package-hygiene.md @@ -0,0 +1,17 @@ +--- +"subtext": minor +--- + +tunnel: package hygiene — split build/dist, untrack artifacts, harden publish. + +Cleans up the publish flow so the tarball is always self-contained and local +builds can't get into a half-built state. + +- `tunnel/build/` and `tunnel/dist/` are now gitignored; reproducible from + sources via `npm run build` / `npm run bundle`. +- `bin`/`files` point at `dist/`; `prepack` runs `bundle` so `npm publish` and + `npm pack` are always self-contained. +- `npm test` and `npm run build` are self-bootstrapping (`clean && tsc`). +- Adds `npm run verify` (`npm pack --dry-run`) for quick "what would ship?" checks. +- `main.ts` walks up to find `package.json` so it works from both the tsc + output (`build/src/main.js`) and the rollup bundle (`dist/index.js`).